Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

8.2 KB
Raw Blame
import os
from pathlib import Path, PureWindowsPath

# Read at call time by `is_contained_filename`, so tests can exercise both platforms' rules on either.
_ON_WINDOWS = os.name == "nt"

# C0, DEL and C1. `str.splitlines()` also splits on U+0085 (in C1), U+2028 and U+2029, so a name containing one
# of those forges a second line in any log record that interpolates it.
_CONTROL_CHARS = (
    frozenset(chr(c) for c in range(0x20)) | frozenset(chr(c) for c in range(0x7F, 0xA0)) | {"\u2028", "\u2029"}
)

# Characters Windows does not allow in a filename. `:` is the one that matters for containment - see the
# docstring - and the rest come along because a name that is not a valid filename everywhere is not a name we
# should be joining onto a directory.
_RESERVED_CHARS = frozenset('<>:"|?*')

# Windows resolves these to the device namespace from *any* directory, so they never name a file in the directory
# they were joined onto - `<store>/NUL.webp` is the NUL device, and a write to it is silently discarded. Matched on
# the stem, case-insensitively: `CON.txt` is reserved, `CONTEXT` is not.
# `COM`/`LPT` are reserved with the superscript digits too (Microsoft's "Naming Files, Paths, and Namespaces"
# lists them explicitly), and with `0` on current Windows.
_RESERVED_STEMS = frozenset(
    {"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "CLOCK$", "CONFIG$", "KEYBD$", "SCREEN$"}
    | {f"{dev}{d}" for dev in ("COM", "LPT") for d in "0123456789\u00b9\u00b2\u00b3"}
)


def is_plain_filename(name: str) -> bool:
    r"""Checks whether a name is safe to join onto a storage directory.

    Names that identify a stored file - object serializer names, model keys, image names - are generated by the
    server, but they travel out to the client and come back as request parameters or node inputs, so on the way in
    they are untrusted. Joining one onto a directory is only safe if it is a bare filename: anything carrying a
    separator, a drive letter or a `..` would resolve outside that directory.

    Five details are worth spelling out:

    - `PureWindowsPath` is used for the check rather than the platform's `Path`. It treats both `/` and `\` as
      separators and understands drive letters, so backslash- and drive-shaped payloads are rejected on posix too,
      instead of passing here and only escaping on Windows deployments.
    - Colons are rejected outright rather than left to `PureWindowsPath`, which only reads a *single* leading
      character as a drive: it parses `C:foo` as drive `C:` plus `foo`, but hands back `..:stream` whole. On NTFS
      that names the alternate data stream `stream` on the file `..` - the parent directory - so
      `<store>/..:stream` writes outside the store while looking like one bare component to `pathlib`.
    - Trailing dots and spaces are stripped before the `.`/`..` comparison. `pathlib` keeps them, but the Win32
      path normaliser drops them from the final component when the file is opened, so `".. "` would reach the
      parent directory on Windows.
    - Windows device names (`NUL`, `CON`, `COM1`, ...) are rejected. They do not escape upwards, but they do not
      stay put either: Win32 resolves them to the device namespace from any directory, so the join silently does
      not address a file in the store at all.
    - Control characters are rejected outright. They cannot escape a directory on their own, but a name is only
      "safe to join" if it also survives being put in a log line.

    Nothing the server generates - a uuid, `f"{cls.__name__}_{uuid}"`, or a `slugify()`ed external-model key -
    can contain any of the rejected characters, so this never turns away a name we produced ourselves.
    """
    if not name or _CONTROL_CHARS.intersection(name) or _RESERVED_CHARS.intersection(name):
        return False
    # Win32 strips trailing dots and spaces from the final component when it opens the file, so compare against
    # what it would actually be left holding.
    normalised = name.rstrip(" .")
    if normalised in ("", ".", ".."):
        return False
    # Win32 takes the base name up to the first `.` and trims trailing spaces from it before the device lookup,
    # so `"NUL .webp"` is still the NUL device - strip again after the split, not only before it.
    if normalised.split(".", 1)[0].rstrip(" ").upper() in _RESERVED_STEMS:
        return False
    return PureWindowsPath(name).name == name


def is_contained_filename(name: str) -> bool:
    r"""Checks whether a name that may already be on disk can be joined onto its storage directory.

    `is_plain_filename` is the gate for a name we are about to *accept*: it applies Windows' rules everywhere, so
    nothing new can be stored that some deployment could not hold. But no released version checked model keys, and
    on posix `: ? * | < > " \` and names like `NUL` are ordinary filename characters, so records exist whose keys
    fail it - and whose files (a model's cover image, say) are sitting in the store under those names. Applying the
    portable rules to *those* would only strand the data: its cover stops being served and can no longer be replaced
    or deleted.

    So this checks containment on the platform we are running on, and nothing more. On Windows that is exactly
    `is_plain_filename`, since every rule there exists because Win32 would otherwise leave the directory (or the
    file namespace). On posix, only an empty name, `.`, `..` or a `/` can leave it; control characters are refused
    on both for the same log-safety reason `is_plain_filename` gives.
    """
    if _ON_WINDOWS:
        return is_plain_filename(name)
    return bool(name) and not _CONTROL_CHARS.intersection(name) and "/" not in name and name not in (".", "..")


def resolve_contained_path(root: Path, candidate: str) -> Path:
    r"""Resolves a client-supplied relative path strictly inside `root`.

    `is_plain_filename` and `is_contained_filename` gate a *single* name. This gates a whole
    relative path - `exports/2026`, `lists/fantasy.txt` - for the case where a node or route lets
    the caller address a file under a directory the operator has designated. The caller never gets
    to name the root, only a path beneath it.

    Containment is checked twice, because the two checks catch different things:

    - Each component must pass `is_contained_filename`, which rejects `.`, `..`, separators,
      control characters and (on Windows) drive letters, colons and device names. This is the
      textual check, and it refuses the payload before it ever touches the filesystem.
      `is_contained_filename` rather than `is_plain_filename`: these paths address files that are
      *already on disk*, placed there by an operator, so a prompt list that a posix admin named
      `aux.txt` or `notes:1.txt` must stay readable. Windows containment is identical either way.
    - The joined path is then `resolve()`d and required to sit under the resolved root. This is
      what catches a symlink inside the root pointing out of it, which no amount of string
      inspection can see.

    `PureWindowsPath` parses the input so that backslash-separated and drive-shaped payloads are
    split and rejected on posix too, instead of passing here and only escaping on Windows.

    Raises:
        ValueError: if the path is absolute, drive-qualified, empty, or escapes `root`.
    """
    if not candidate:
        raise ValueError("A path is required.")

    raw = PureWindowsPath(candidate)
    if raw.is_absolute() or raw.drive or raw.root:
        raise ValueError(
            f"Absolute paths are not allowed: {candidate!r}. Use a path relative to the permitted directory."
        )

    # `.` and `./` carry no components and address the root itself, which is contained by definition.
    # `""` is refused above instead: an empty input is a missing value, not a reference to the root.
    parts = raw.parts
    if not parts:
        return root.resolve()
    for part in parts:
        if not is_contained_filename(part):
            raise ValueError(f"Path component {part!r} is not allowed in {candidate!r}.")

    resolved = (root / Path(*parts)).resolve()
    root_resolved = root.resolve()
    if resolved != root_resolved and root_resolved not in resolved.parents:
        raise ValueError(f"Path must stay within the permitted directory: {candidate!r}")
    return resolved