@astram/file-analyser
v0.3.0
Published
Astram framework — the isolated file analyser for the AI assistant's file capabilities (G-037 D2a): a Python service that reads untrusted xlsx, csv, pdf and docx bytes with fixed caps, no network and no evaluation, and answers schema-checked JSON over a u
Readme
@astram/file-analyser
The isolated file analyser behind the AI assistant's file capabilities (STATUS G-037 D2a,
SPEC §5 A). A small Python service that reads one untrusted
xlsx, csv, pdf or docx file per call and answers one JSON response. Only the app server calls it, over a
unix socket; the app re-opens the file through FilesService (and decide()) on every call and sends the
bytes. The analyser keeps nothing between calls, has no network and holds no credentials.
This npm package ships the build inputs only: Dockerfile, src/, schemas/v1/ (response JSON Schemas,
shared with the app client), deploy/ (systemd unit), requirements.lock, pyproject.toml. It is not a
JavaScript library and has no build step. The app builds the image.
Operations
| Op | Formats | Arguments | Result (schemas/v1/<op>.schema.json) |
|---|---|---|---|
| sheets.list | xlsx, csv | — | sheets (name, index, state, kind, readable), partial |
| sheet.read | xlsx, csv | sheet?, rowStart (1-based over data rows, default 1), rowCount (1–200, default 200) | sheet list, header row, typed cells, columns, partial {shown,total}, nextRowStart |
| sheet.profile | xlsx, csv | sheet? | per column: header, inferred type, empty count, distinct count (cap 1000), min/max (numbers, dates), top 5 values when distinct ≤ 20; ≤ 5 sample rows; row count; partial (columns) |
| pdf.text | pdf | pageStart (1-based, default 1), pageCount (1–10, default 10) | text per page (text layer only; a page without one: "" + note no_text_layer), page count, partial, nextPageStart |
| doc.text | docx | charStart (0-based, default 0), charCount (1–20000, default 20000) | paragraph and table text in document order, total chars, partial, nextCharStart |
| workbook.outline | xlsx, csv | hints? | workbook counts (sheets, defined names, external links, tables, charts); per sheet in workbook order: state, kind, scanned, computed usedRange, hidden row/column counts, counts (merges, tables, charts, names, validations, pivot tables, formulas, external / volatile / unparsed formulas); partial |
| sheet.grid | xlsx, csv | sheet, range (A1, ≤ 32 chars, ≤ 400 columns wide), hints? | cells of the range with A1 addresses (a, typed v, formula indicator f, merge index m, hint kind p), merges, hidden rows/columns, shown, usedRange, truncated {reason, nextRange}, truncatedCells |
| sheet.structure | xlsx, csv | sheet, range?, parts? (distinct subset of merges, formulas, tables, names, validations, charts; default all), offset? (0–100000, only with exactly one part), hints? | per part {items, partial}: merged ranges, formula groups (shape, example, kind, anchor, ≤ 8 rectangles, count), tables (name, range, header/totals rows, column names), defined names (scope, hidden, refersTo shape), validations (cells, type, list items / range source, p), charts (type, title, series refs) |
| capabilities | none (no format, no body) | none | {v: 1, package: <this package's version>, ops: [every op name]} |
workbook.outline, sheet.grid and sheet.structure are the G1 structure reads
(SPEC §5 A–C); capabilities is the version probe (§5 B).
Rules every op follows:
sheet.readandsheet.profiletreat row 1 of a sheet as its header; data rows run to the last row holding a value. The G1 ops make no header assumption: they address cells by A1 coordinates, and the caller picks the range. A csv file is one sheet namedcsv(UTF-8, a BOM is allowed; comma, or semicolon / tab when the first line has more of them). A csv in any other encoding (invalid UTF-8 bytes, e.g. Windows-1252, or a UTF-16 / UTF-32 byte-order mark) answers the reasonencoding: the app tells the user to save the csv as UTF-8. The analyser does not guess encodings.sheet.readnever answers an empty page while rows remain: when the first row alone is over the size bound (a very wide row of long, multibyte cells), its cells are cut further (250, 128, 64, then 32 chars; below that each text cell is the ellipsis alone, counted intruncatedCells) andnextRowStartadvances by at least one.- Formulas are never evaluated: a formula cell returns the value cached in the file (
nullwhen none). No macro runs, no link is fetched, no external entity is resolved (any DTD is refused). - OOXML entries are found through the central directory only; every part read is inflated in chunks with the
bytes really produced counted (a declared size can lie) and XML-scanned for depth and DTDs before a
parser sees it. Only the parts an op expects are opened: for xlsx the workbook, its relationships, shared
strings, styles and the one worksheet asked for (passed to openpyxl as a subset archive); for docx the
main document part. The G1 ops stream worksheet parts themselves (defusedxml
iterparse, after the same scan) and also read, through the same checks, the sheet's relationships, its table parts, its drawing's relationships and the chart parts they name (workbook.outline: every worksheet in workbook order). Embedded objects (word/embeddings/,xl/embeddings/) are never opened. A package naming both a workbook and a document main part is read only as the part the op expects. - Typed cell JSON:
null(empty), string, number, boolean, or{"t": "date"|"datetime"|"time"|"duration"|"error", "v": "<text>"}. Strings are cut (an ellipsis marks the cut) to 500 chars in rows, 200 in headers, 100 in profiles.
Size bound
Every result is trimmed by the op to 40 KiB of compact UTF-8 JSON (RESULT_BUDGET_BYTES; the op sets
partial / next* when it trims), so the app's capability result fits CONTENT_MAX_BYTES (48 KiB) with
8 KiB to spare for its envelope. The analyser's hard response cap is 256 KiB; a response over it is replaced by
the error limit.
The G1 ops (workbook.outline, sheet.grid, sheet.structure) have a smaller budget, 16 KiB
(STRUCT_RESULT_BUDGET_BYTES), so a masked result stays far below CONTENT_MAX_BYTES; the app refuses a larger
one. Their other bounds (limits.py, SPEC §10 A):
sheet.grid: at most 400 cells per call, counted as the area returned (empty cells included), and a range at most 400 columns wide. It stops at the first whole row that would pass 400 cells or 16 KiB and reportstruncated {reason: cells|bytes, nextRange}; the next call asks fornextRange. Cell text is cut to 256 chars; when one row alone is over the budget its text is cut along 256 → 128 → 64 → 32 chars, then to the ellipsis alone (counted intruncatedCells); a row that still does not fit answerslimit(ask for fewer columns).sheet.structurelist caps: merges 2,000, formula groups 64 (≤ 8 rectangles each), tables 64 (≤ 64 columns), names 256, validations 128 (≤ 64 items of ≤ 128 chars), charts 32 (≤ 16 series). Each list reportspartial {shown, total};offsetpages one part.- Formulas are never evaluated. A formula is reported as an indicator (
fany formula,vvolatile:NOW,TODAY,RAND,RANDBETWEEN,RANDARRAY,OFFSET,INDIRECT,CELL,INFO;xexternal: an external-workbook reference,IMPORTRANGEand the other import functions,WEBSERVICE,RTD,CUBEVALUE,CUBEMEMBER, or the Google Sheets__xludf.DUMMYFUNCTIONwrapper) and, insheet.structure, as a shape: R1C1 relative to its cell, every non-empty string literal replaced by"…", external targets as[ext#<n>](formula text ≤ 2,048 chars and 512 tokens, elseunparsed). No link target, URL, file path or formula string literal is returned. External-link, pivot-cache and embedding parts are counted from relationships only, never parsed; chart caches are never read. workbook.outlinescans sheets in workbook order on one cell budget; when the 1,000,000-cell cap would be passed, that sheet and the later ones are listed withscanned: falseandcounts: null(not alimiterror).sheet.gridandsheet.structureon such a sheet answerlimit.hintsis the app's resolved masking header-hint list (configuration, never model input). With it,sheet.gridmarks each cell a hint covers withp: <kind>andsheet.structuremarks validations whose cells it covers; the app masks those values whole. A hint covers the cells below a matching header cell (all the columns a merged one spans) to the end of the used range, and the cells right of it when it is the leftmost non-empty cell of its row. Masking itself happens in the app; person names that no hint covers (table column names, chart titles, defined-name text, validation lists outside hinted columns) are not masked there (agent-file-structure SPEC §12). The rule fails safe and can over-mask: when a row's leftmost label is itself a hint (Name), the other labels of that row are covered, and a later block'sNamelabel under an earlier block's hinted column is covered too (pinned bytest_layoutsL4; values are unaffected).
Caps (SPEC §5 A, src/astram_file_analyser/limits.py)
| Cap | Value | Breach |
|---|---|---|
| Input bytes | ≤ 50 MiB (checked from the header, before reading the bytes) | limit |
| Wall clock | 10 s per op (SIGALRM in the worker; the server SIGKILLs a worker alive after read 10 s + op 10 s + write 5 s + 2 s) | limit (or a closed connection after a kill) |
| Memory | 512 MiB address space per worker (RLIMIT_AS; Linux) | limit |
| Cells scanned | ≤ 1,000,000 per call (an empty row counts as one); see below | limit |
| XML depth | ≤ 64; any DTD, entity declaration or external reference is refused | limit |
| Inflated bytes | ≤ 128 MiB per part, ≤ 256 MiB per call (docx main part ≤ 32 MiB) | limit |
| Response | ≤ 256 KiB | limit |
| Request header | ≤ 16 KiB | bad_request |
The cell cap counts every cell the sheet ops scan in one call, and every call scans from row 1 (a sheet
op re-reads the file each time; nothing is kept between calls). So it also applies to the first page: a
sheet with more than 1,000,000 cells answers limit even for sheet.read rows 1–200. This is by design
for D2a (one bounded scan per call); split such a file before uploading it.
A worker also runs with RLIMIT_FSIZE 0 (writes no file), RLIMIT_CORE 0, RLIMIT_NPROC 0 (Linux; starts
no process), RLIMIT_NOFILE 32 and a CPU-seconds backstop.
Process limits fail closed. A worker must set RLIMIT_AS (Linux), RLIMIT_FSIZE, RLIMIT_CPU and
RLIMIT_NPROC (Linux) before it reads a byte; when the sandbox refuses any of them (a seccomp profile that
blocks setrlimit / prlimit64, for example) the worker answers internal without reading the request,
so no op runs unconfined. The server probes the limits in a child at start and logs
{"event":"rlimits_missing","missing":[...]} once (limit names only); every refused call logs the same names
("refused":"rlimits"). RLIMIT_CORE and RLIMIT_NOFILE stay best effort.
Failure reasons are fixed: limit, malformed (not a well-formed file of the declared format, an encrypted
pdf, a macro-enabled workbook), encoding (a csv that is not UTF-8), bad_request (header or arguments),
not_found (no such readable sheet), internal (analyser defect, or a worker that could not set its process
limits). An error never carries a file name, a cell, text or a byte. Logs (stderr, one JSON line per call)
carry the request id, op, format, sizes, duration and outcome only.
The call line is written by the server (or, in run mode, the parent process), not by the worker: a worker
runs with RLIMIT_FSIZE 0, which makes any write to a regular file fail, so a worker writing to a stderr
redirected to a file would lose its line. The worker sends its entry over a pipe (not a file, so the limit
does not apply) before it closes the connection; the server keeps only the known fields and logs it when it
reaps the worker. stderr may therefore be the journal, a Docker log pipe or a regular file.
Wire format
The same framing on the unix socket and on stdin/stdout. Every frame is a 4-byte big-endian unsigned length followed by that many bytes.
Request: one header frame, then exactly size raw file bytes (no length prefix of their own); the
capabilities probe is the header frame alone (below).
[u32 BE n][n bytes: UTF-8 JSON header][size bytes: the file]
header = {"v": 1, "op": "sheet.read", "format": "xlsx", "size": 12345,
"args": {"rowStart": 1, "rowCount": 200}, "id": "optional-request-id"}schemas/v1/request.schema.json is the header contract (unknown keys, unknown args, an op/format mismatch
or an out-of-range value ⇒ bad_request; id matches ^[A-Za-z0-9_-]{1,64}$ and is only logged).
The capabilities probe is the header alone, with no format, size, args or bytes:
[u32 BE n][n bytes: {"v": 1, "op": "capabilities"}]
→ {"v": 1, "ok": true, "op": "capabilities", "result": {"v": 1, "package": "0.3.0", "ops": [...]}}Any format, size, argument or other key on it ⇒ bad_request. It reads no bytes and spends no cell budget,
and it runs in a worker with the same process limits as every other call.
Version skew
The wire stays v: 1; new ops are additive. An analyser older than the app answers bad_request to an op it
does not know, which the app reports as analyser_failed. Upgrade the analyser image together with
@astram/agent. The app (AgentModule.forRoot({ files: { enabled: true } })) sends capabilities once at
boot: an analyser that is reachable but lacks an op the app needs, answers bad_request to the probe, or
reports a package below the app's minimum analyser version stops the boot (analyser_version_skew). An
analyser that is not reachable yet only logs a warning; then every file call probes first until a probe
succeeds, and no file is read or sent to an analyser whose probe has not succeeded.
Response: one frame, then the analyser closes the connection.
[u32 BE m][m bytes: UTF-8 JSON]
{"v": 1, "ok": true, "op": "sheet.read", "result": {...}} # result: schemas/v1/<op>.schema.json
{"v": 1, "ok": false, "error": "limit"} # schemas/v1/response.schema.jsonA client should: connect; write the header frame and the bytes; half-close (optional); read 4 bytes, then
exactly that many (refuse m > 262144); validate against response.schema.json and the op schema; treat a
closed connection with no complete frame, a timeout, an oversize or a schema mismatch as a failure.
Run modes
1. Container (default)
docker build -t astram-file-analyser:0.3.0 node_modules/@astram/file-analyser
docker run -d --name astram-file-analyser \
--read-only --network none --cap-drop ALL --security-opt no-new-privileges \
--memory 1g --memory-swap 1g --cpus 1 --pids-limit 64 \
--mount type=volume,src=astram-analyser-sock,dst=/run/astram-analyser \
astram-file-analyser:0.3.0Required flags: --read-only (read-only root filesystem), --network none, --cap-drop ALL,
--security-opt no-new-privileges, memory / CPU / pids limits; Docker's default seccomp profile stays on
(never --security-opt seccomp=unconfined). The image runs as uid/gid 10001 and creates
/run/astram-analyser with mode 0700, so a new named volume mounted there inherits that owner and mode. The
app container mounts the same volume and runs as uid 10001 (or the socket is unreachable); set
AGENT_FILE_ANALYSER_SOCKET=/run/astram-analyser/analyser.sock in the app. The server refuses to start when
the directory is wider than 0700. --max-workers (default 4) caps concurrent calls; keep --pids-limit
above it.
2. systemd (hosts without a container runtime)
deploy/astram-file-analyser.service runs the same server as its own system user with PrivateNetwork=yes,
RestrictAddressFamilies=AF_UNIX, ProtectSystem=strict, ProtectHome=yes, PrivateTmp=yes,
NoNewPrivileges=yes, an empty CapabilityBoundingSet=, SystemCallFilter=@system-service (seccomp),
MemoryMax, CPUQuota, TasksMax, and RuntimeDirectory=astram-analyser. Install steps are in the unit
file's header. The seccomp filter keeps setrlimit (@resources) and prlimit64 (@default) allowed, both
part of @system-service; ~@privileged removes neither (systemd 252). Do not add a deny group that holds
them: the workers would then refuse every call (see "Process limits fail closed"). The app reaches the socket through a shared group: the directory is 0750 (owner analyser,
group = the app's group, set Group=), the socket 0660, both via serve --group-access; nothing else on the
host can enter the directory.
3. User mode (managed Linux hosts: no root, no container runtime, no system systemd)
serve --isolation user (agent-file-analyser-user-mode SPEC v3) is a reduced-isolation mode, for hosts
where neither mode above is possible. If rootless Podman or Docker is available, use container mode instead.
deploy/pm2.ecosystem.example.cjs shows a PM2 entry. Requirements:
- Linux x86_64 or aarch64 with Landlock enabled (
cat /sys/kernel/security/lsmlistslandlock) at ABI ≥ 6 (kernel ≥ 6.12). Python 3.12 or 3.13 with the same hash-lockedrequirements.lock. ASTRAM_ANALYSER_ACK_REDUCED_ISOLATION=1in the analyser's env. Without it, below ABI 6, on another platform or with--group-access, it refuses to start (exit 2, one{"event":"refused"}line).- In the APP's env:
AGENT_FILE_ANALYSER_ACK_REDUCED_ISOLATION=1. Otherwise the app refuses the analyser (boot error, or everyfiles.*call unavailable if the analyser came up after the app). With a bootedclient_dataprofile the app also needsAGENT_FILE_ANALYSER_ACK_REDUCED_ISOLATION_CLIENT_DATA=1, a decision for the operator's owner, not a default.
What it does:
- Server: it binds the socket, then imports every module it can need (
preload.py). It then setsno_new_privsand enters a Landlock domain that handles every filesystem right, TCP bind/connect and the abstract-unix and signal scopes, with no rule. From then on it cannot open, list, create or remove any path, use TCP, reach an abstract socket, or signal a process outside its domain. It logs one{"event":"isolation"}line with the kernel, Landlock ABI,lostandenforced. It does not remove the socket at shutdown (Landlock refuses it); the next start does. - Each worker: it points fds 0-2 at /dev/null (it can write no log line; its call line goes over the
report pipe), sets the rlimits, adds its own nested Landlock domain, then installs a seccomp allowlist
(
seccomp_allowlist.py: the traced syscalls plus harmless glibc variants; the default isEPERM; a foreign architecture or an x32 syscall kills the process). Only then does it read the request, with plainread/writeon the connection it already holds. A failure at any of these steps answersinternalwithout reading. - The
capabilitiesop reportsisolation: "user",sandbox: "landlock+seccomp"andlandlockAbi.
What a compromised parser still reaches: its own request and response, its own report pipe and its own
memory within the CPU and wall-clock limits. It cannot reach the app's files (.env, secrets KEK/DEK, code),
any network, other processes or other requests (each request gets a fresh worker).
What is lost compared with modes 1 and 2:
- a separate uid (largely made up for by Landlock);
- host-level memory and pids caps (only the rlimits and
--max-workersremain); - namespaces.
The self-report is a misconfiguration guard, not a security boundary: a compromised analyser could report
anything. The app caches a successful probe for its process lifetime, so restart the app after switching
the analyser between modes. Otherwise the new mode is not judged (or audited) until the next app start. Test evidence records the kernel of every run (SPEC v3 §11). Before enabling it, run
tests/test_sandbox_linux.py on the host itself.
One-shot
python -m astram_file_analyser run serves one request from stdin to stdout in a forked worker (same caps,
limits and framing; the parent writes the call line). Used by tests and for diagnosis.
Socket path length
A unix socket path is limited by sockaddr_un: 108 bytes on Linux, 104 bytes on macOS (including the
terminating NUL). serve --socket fails to bind a longer path. The default /run/astram-analyser/analyser.sock
is far below it; on macOS keep a development socket under a short directory such as /tmp/afa-xxxx/a.sock
(the macOS per-user $TMPDIR alone can use most of the 104 bytes).
Dependencies
Runtime (pinned exactly, hash-locked in requirements.lock, installed with
pip install --require-hashes --no-deps -r requirements.lock): openpyxl, pypdf, defusedxml, and
openpyxl's et-xmlfile. Nothing else. Test and CI tools (pytest, pip-audit) are in
requirements-dev.lock and never in the image. The base image is pinned by digest in the Dockerfile.
Python 3.12 and 3.13 are supported with the same lock: all four runtime dependencies are pure Python. On
2026-11-28 the full suite passed on 3.13.18 (python:3.13-slim) and on Debian 13's 3.13.5, and CI runs both
3.12 and 3.13.
Regenerate after changing a pin in pyproject.toml (then run pip-audit):
uv pip compile pyproject.toml --python-version 3.12 --generate-hashes -o requirements.lock
uv pip compile requirements-dev.in -c requirements.lock --python-version 3.12 --generate-hashes -o requirements-dev.lock
pip-audit --require-hashes --disable-pip -r requirements.lockTests
From this directory, in a virtualenv outside the repo:
python3.12 -m venv <scratch>/venv
<scratch>/venv/bin/pip install --require-hashes --no-deps -r requirements.lock
<scratch>/venv/bin/pip install --require-hashes -r requirements-dev.lock
<scratch>/venv/bin/python -m pytestFixtures are generated at test time by fixtures/generate.py (synthetic data only, never committed); a guard
fails the run if any test opens an xlsx/csv/pdf/docx the generator did not write. Tests marked docker build
the image and prove the sandbox (--network none, read-only root filesystem, non-root, memory cap); they skip
when no Docker engine answers.
