Skip to content

symfonic.capabilities.knowledge.labels

labels

Turning attacker-supplied names into labels that can only be displayed.

Two functions, one rule: a name that arrived with untrusted content is a label, never an identifier the framework acts on. AS-ING-2 states it for filenames — a filename must not select a filesystem path — and the same argument covers a source name that is about to be interpolated into SOURCE [...]: a name carrying ] forges the delimiter that was supposed to contain it.

This module performs no filesystem or network access of any kind. That is the enforcement: there is no path here for a label to select.

safe_label

safe_label(raw: str) -> str

Reduce a filename to an opaque display label.

Path structure is discarded rather than escaped: the basename is taken after splitting on both separators, so a POSIX host still refuses a Windows-shaped traversal. Anything that reduces to "", . or .. becomes :data:FALLBACK_LABEL, because a caller that received an empty label would be tempted to substitute the original.

Source code in src/symfonic/capabilities/knowledge/labels.py
def safe_label(raw: str) -> str:
    """Reduce a filename to an opaque display label.

    Path structure is discarded rather than escaped: the basename is taken
    after splitting on *both* separators, so a POSIX host still refuses a
    Windows-shaped traversal. Anything that reduces to ``""``, ``.`` or ``..``
    becomes :data:`FALLBACK_LABEL`, because a caller that received an empty
    label would be tempted to substitute the original.
    """
    cleaned = _CONTROL.sub("", raw)
    basename = cleaned.replace("\\", "/").rpartition("/")[2]
    basename = basename.strip()
    if basename in ("", ".", ".."):
        return FALLBACK_LABEL
    label = _LABEL_DISALLOWED.sub("_", basename)[:MAX_LABEL_CHARS]
    return label or FALLBACK_LABEL

safe_source

safe_source(raw: str) -> str

Reduce a citation source name to something that cannot forge a delimiter.

Spaces survive — a source name is read by a human — but every bracket-ish character is removed. SOURCE [x]: is a delimiter, and a name allowed to contain ] decides where that delimiter ends.

Source code in src/symfonic/capabilities/knowledge/labels.py
def safe_source(raw: str) -> str:
    """Reduce a citation source name to something that cannot forge a delimiter.

    Spaces survive — a source name is read by a human — but every bracket-ish
    character is removed. ``SOURCE [x]:`` is a delimiter, and a name allowed to
    contain ``]`` decides where that delimiter ends.
    """
    cleaned = _CONTROL.sub("", raw)
    cleaned = _SOURCE_DISALLOWED.sub("", cleaned)
    cleaned = _WHITESPACE_RUN.sub(" ", cleaned).strip()
    return cleaned[:MAX_SOURCE_CHARS]