HKUDS/DeepTutor · error · ValueError

Invalid book id

Error message

Invalid book id: {book_id!r}

What it means

Containment guard _safe_book_id: the caller-supplied book_id contains characters outside [A-Za-z0-9_-] (path separators, dots, traversal segments). Engine-minted ids are bk_<hex>; anything else here is a bug or a path-traversal attempt and must never reach the filesystem.

Solutions

  1. Only use book ids returned by the engine (bk_<hex>)
  2. Reject or regenerate caller-minted ids that contain '/', '\\', or '.' segments client-side
  3. Never build paths from raw request ids — always route through _safe_book_id
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at deeptutor/book/storage.py:73 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of HKUDS/DeepTutor@3e82f13042 (2026-08-27). Data as JSON: /api/errors/a80500b675880d2b. Report an issue: GitHub.

Appendix: source

Thrown at deeptutor/book/storage.py:73

    text = json.dumps(payload, ensure_ascii=False, indent=2, default=str)
    _atomic_write_text(path, text)


_SAFE_ID = re.compile(r"[^A-Za-z0-9_-]")


def _safe_book_id(book_id: str) -> str:
    """Reduce a caller-supplied id to something that cannot escape its root.

    Book ids arrive in request bodies and are used verbatim as directory names.
    Ids the engine mints are ``bk_<hex>``; anything containing a separator or a
    dot segment is either a bug or an attempt to walk out of the workspace, and
    neither should reach the filesystem. Mirrors the containment rule in
    ``services/storage/attachment_store.py``.
    """
    cleaned = _SAFE_ID.sub("", (book_id or "").strip())
    if not cleaned:
        raise ValueError(f"Invalid book id: {book_id!r}")
    return cleaned


def _read_json(path: Path) -> Any | None:
    if not path.exists():
        return None
    try:
        with open(path, encoding="utf-8") as f:
            return json.load(f)
    except (OSError, json.JSONDecodeError) as exc:
        logger.warning(f"Failed to read JSON {path}: {exc}")
        return None


# ─────────────────────────────────────────────────────────────────────────────
# Public API
# ─────────────────────────────────────────────────────────────────────────────

View on GitHub (pinned to 3e82f13042)