AI-Assisted Coding Lab · Store Uploads Under Safe Paths

45:00left of 45:00

Store Uploads Under Safe Paths

Users upload attachments, and the upload service stores each file under the name the client sent. The README has the rules, and uploads.py has the store. Build the path handling with the assistant and decide what to keep.

uploads.py1 of 3

Files

uploads.py

Python · Editable
import os
# Windows device names. Windows reserves them with any extension too.
RESERVED = {"CON", "PRN", "AUX", "NUL"} | {f"COM{i}" for i in range(1, 10)} | {f"LPT{i}" for i in range(1, 10)}
class UnsafeName(ValueError):
"""Raised for a client filename that can't be stored."""
def clean_name(filename):
"""Returns the name to store a client's filename under, or raises UnsafeName."""
if "\x00" in filename:
raise UnsafeName("filename contains a NUL byte")
name = filename
if name in ("", ".", ".."):
raise UnsafeName(f"no usable name in {filename!r}")
if name.startswith("."):
raise UnsafeName(f"hidden files are not allowed: {name!r}")
if is_reserved(name):
raise UnsafeName(f"reserved name: {name!r}")
if len(name) > 255:
raise UnsafeName("filename is longer than 255 characters")
return name
def is_reserved(name):
"""True for a Windows device name, in any case, with or without an extension."""
raise NotImplementedError
def is_inside(root, path):
"""True when path is root or inside it. Both paths are absolute and normalized."""
raise NotImplementedError
class UploadStore:
"""Keeps each user's uploads at <root>/<user_id>/<name>."""
def __init__(self, root):
self.root = os.path.abspath(root)
def path_for(self, user_id, filename):
"""The absolute path to store a client's filename at for user_id."""
raise NotImplementedError

Test Output

No runs yet.

Assistant

Scripted
  1. Send the first prompt to start.

Next Prompt

Make clean_name strip directories from the client's filename so nothing can escape the upload folder.