Private analysis sandbox adapter
Private analysis execution is unavailable by default. The repository contains an OpenSandbox SDK adapter and a bounded output quarantine. It does not contain an enabled analysis worker, an approved guest image, a sandbox deployment, or trusted conformance and termination authorities. Installing the optional SDK does not enable execution. Existing report execution is unchanged.
The adapter uses shared operator-managed OpenSandbox infrastructure and creates a disposable sandbox for each fenced attempt. It does not allocate permanent machines per user, reuse interpreters, implement a scheduler/controller, or use the SDK's pool service. There is no fallback to the report executor, host processes, ordinary Docker/runc, or a cloud service.
Optional SDK and upstream API
requirements-analysis.txt pins the published opensandbox==1.2.1,
httpx-sse==0.4.3, and opentelemetry-api==1.45.1. Resolve this optional worker
set with -c constraints.txt; it does not change the ordinary portal/framework
requirements. It requires Python 3.10 or newer. The published OpenSandbox wheel
SHA-256 inspected for this adapter is
67c9210a06cc2c18e621b34b6b21ce143e04226b6773ea17924783b379a75585.
The package APIs were inspected in that wheel, independently of the upstream
server source inspected at 4ae99691ff0a62594614df90a86ecbee07add966.
Neither pin identifies a deployed or verified server.
| Adapter operation | Published SDK operation |
|---|---|
| Create | Sandbox.create, immutable image, fixed idle entrypoint, finite lifetime, CPU/memory/writable-layer limits, exact metadata |
| Upload | sandbox.files.write_files, bounded authorized bytes and fixed guest input root |
| Execute | sandbox.commands.run, fixed argv, background command, finite timeout, non-root UID/GID |
| Poll | get_command_status, get_background_command_logs, byte-bounded cursor |
| Collect | get_file_info, read_bytes_stream_detailed, byte-only quarantine |
| Cancel | sandbox.commands.interrupt, one submission |
| Destroy | sandbox.destroy; restored clients use SandboxManager.kill_sandbox by saved ID |
| Reconcile | SandboxManager.list_sandbox_infos(SandboxFilter(metadata=..., page=..., page_size=25)), exact identity validation |
Context-manager exit and close() only close local resources. They do not
terminate the sandbox. destroy() acknowledges deletion; cleanup may continue.
The SDK also attempts deletion when creation succeeds but readiness fails. The
adapter records that cleanup submission before dispatch as well.
The adapter currently accepts only HTTPS server-proxy routes on the configured
origin and exact sandbox/port prefix. This upstream route is in maintenance mode
(security fixes remain supported); arbitrary direct endpoints and ingress
routing are not implemented here. Redirects, returned routing headers, changed
origins, unexpected routes and compressed responses are rejected before any
credentialed forwarding. SDK retries, wake retries, metrics and tracing are
disabled. Environment proxy configuration is not used by the HTTP transport.
SDK diagnostics are suppressed in this adapter's execution context because
upstream errors can include file content, URLs and response bodies. Callers get
fixed analysis_* error codes, never raw backend errors.
OpenSandbox and OpenTelemetry API are optional dependencies under Apache-2.0; httpx-sse is MIT. Their upstream copyrights and packaged notices continue to apply; no upstream source is vendored. See the published OpenSandbox package, OpenTelemetry API package, httpx-sse package, and OpenSandbox licence.
Request, identity and durable integration
apps/runner/analysis_backend.py defines frozen AnalysisRequest, Identity,
Profile, Receipt, Status, LogCursor, and evidence records. An identity
contains execution UUID, attempt UUID and positive lease fence. A request pins
its immutable input revision, manifest/content hash, image digest, profile ID,
operation, input byte manifest and output allowlist. Its SHA-256 also binds the
output names/types. There are no caller-controlled URLs, commands, images outside
the approved profile, host paths, mounts, environment dictionaries or network
options. Source files are data until executed in the remote guest.
OpenSandboxAttempt handles one attempt. Its methods are prepare, create,
upload, execute, poll, collect, cancel, destroy, reconcile,
confirm_termination, and close. Cleanup can consult the independent termination
observer even if a sandbox lookup or deletion fails. A 404 alone never releases
capacity, and an externally confirmed stop does not invent a DELETE submission.
availability() reports a safe unavailable
code when configuration, the exact SDK, or conformance evidence is missing.
These modules do not import Django models or run host processes.
The durable caller must:
- Recheck current permissions, snapshot lineage and data-disclosure scope; admit and reserve capacity transactionally under a fresh, unexpired lease.
- Construct the request only from authorized per-run bytes. Never include Git, portal, warehouse, provider, encryption or service credentials. Construct backend configuration and evidence authorities from trusted operator code, outside request/model fields.
- Supply
persist(receipt), which atomically compares the current durable fence/owner and saves the receipt before each remote mutation. Persist the PREPARED receipt before dispatch and preserve all mutation intents, identities, deadlines, log cursors and subsequent results. Separate workers must not be allowed to dispatch the same prepared receipt concurrently. - Restore only the saved receipt after a crash. Submitted create, upload, execute, interrupt and destroy operations are never automatically replayed. Unknown outcomes remain UNCONFIRMED and retain their reservation. Exact metadata discovery supplies a cleanup identity, never permission to execute again. Zero, duplicate, truncated or inconsistent results prove neither nonexistence nor termination. Recovery examines at most four pages by default.
- Poll and collect within the original deadline. The default total budget is 300 seconds and each SDK operation has a maximum 10-second call budget; smaller deadlines win. Cleanup/reconciliation remain possible after expiry, with separate finite call budgets. Cooperative async cancellation stops local I/O; it cannot establish the remote outcome.
- Collect candidate bytes while the remote file API is alive; explicitly
request destruction; obtain separate trusted termination evidence for the
exact attempt, sandbox, request and profile.
TERMINATEDis only recorded after that observation. A command exit, interrupt success, deletion response, disconnected client, 404 or elapsed lifetime alone is insufficient. - Before committing any output, atomically recheck the current unexpired lease, authorization, input lineage and evidence validity. Match the quarantine's request/sandbox identity and exact hashes to the receipt and termination report. Commit only those captured bytes. Receipt state alone does not grant publication permission. Never expose a quarantine before these checks.
The internal durable integration is apps.assistant.analysis_controller.
AnalysisController() has no configured backend or evidence authority and returns
analysis_unavailable. No HTTP route, assistant tool, queue consumer or global
schedule invokes it. Ordinary assistant and provider behavior is unchanged.
Trusted worker code may construct AnalysisController(config, conformance=...,
termination=...) and call run_once(run, studio=..., actor=..., session=...,
source_query_ids=...). Both authorities must be independently trusted worker
dependencies; no settings JSON, enabled flag or model assertion creates them.
Availability is checked before claiming the run. Call the controller in autocommit,
never inside another transaction. All remote calls and observer calls occur
outside database transactions and advisory locks.
This increment uses the adapter's fixed Python entrypoint /analysis/input/analysis.py
and accepts only a result.json output. It does not install dependencies or accept
arbitrary commands, destinations, mounts or environment variables. Inputs are the
original authorized source revision and successful governed query snapshots in
snapshots/<query-uuid>.json, selected by trusted orchestration. At most sixteen
snapshots and 256 KiB of snapshot JSON are admitted. All inherited query evidence
is mounted and rechecked; generated output cannot declare its own provenance.
The request hash binds the exact input byte manifest and approved image/profile.
Credentials and raw warehouse connections are not supplied to the guest.
AnalysisExecutionReceipt stores content-free identity independently of content
foreign keys. Attempt UUID equals the claim's lease UUID; fence 1 denotes the
single claim permitted by run admission. Receipt saves compare the expected
version, owner, exact identity, original revision/source hash, immutable request,
profile and deadline, plus the current run/reservation lease. They recheck current
user/source authority and the work head before mutation intent can commit. A
second worker restoring the same prepared receipt cannot dispatch it. Renewal
never extends the original execution deadline.
recover(after=...) performs one keyset batch of at most 100 stop requests and
returns scanned, confirmed and the next after UUID. Call again with that UUID;
restart at None after exhaustion. Expired leases are fenced first. Recovery uses
OpenSandboxCleanup(saved_receipt, original_config, persist=..., termination=...),
which has no prepare, create, upload, execute or collect methods and needs no
source bytes, user, transcript or current conformance authority. Before cleanup deletion, management metadata and the image must still match the
original receipt; lookup failure cannot authorize deletion. Original trusted
configuration must still match the exact profile/deployment/endpoint; changed
configuration cannot redirect cleanup. Each call retains the adapter's finite
cleanup timeout. Unknown mutations are never replayed, including destruction.
Only exact trusted termination observation releases started capacity. Empty lookup, deletion acceptance, 404, TTL and command exit do not. A crash before a receipt is saved leaves a started reservation occupied; this increment has no automatic no-receipt release or unsafe retry path. Revoked permissions, intervening edits, cancellation and expiry prevent output admission. Unconfirmed runs remain cleanup work even if their account, chat, studio or organization has been erased. Receipt history is removed when content and its reservation are both gone.
After exact termination, finish_run(candidate_output=...) atomically rechecks
authority, lineage, the current unexpired lease and original work head, then stores
only the captured, hash-matched bytes as encrypted AnalysisCandidate content.
Candidates record the exact input/source and manifest hashes, request, actual
query-policy lineage, quarantine hash and termination-report hash. They use the
shared rotating encryption keys and transactional per-chat/organization storage
quotas together with source revisions; each candidate bundle also consumes one
record in the revision-count ceiling. Work retention, Keep and deliberate erasure
apply through the originating work. list_candidates returns SQL-paginated,
25-row identifier/count/state metadata without loading manifests or blobs.
Every candidate remains candidate_unservable. There is no content-read or
browser route, safe-preview assertion, automatic source append, publication or
sharing. Native report preview validation is a separate prerequisite. Neither
candidate storage nor the fake-HTTP tests establish runtime containment.
Activation requirements: currently unverified
Profile identifies the deployment, backend revision, exact image, matching
Trellum version, endpoint fingerprint and effective worker-configuration hash.
It includes CPU, memory, writable-byte, inode, guest-process, UID/GID and transport
budgets. Only the explicit runsc runtime and an externally enforced isolated
worker network with default deny are supported by this adapter. VM profiles need
a separately reviewed mapping. A runtime string or a client/model verified
flag cannot enable execution.
A separately trusted, locally loaded ConformanceAuthority must authenticate
fresh, non-revoked evidence for the exact profile. Every required Control
must have PROVEN status and an immutable report hash. Missing observations stay
UNVERIFIED. There is no production authority implementation in this change.
Configuration drift, changed image/runtime/network or evidence expiry must revoke
start eligibility. The authority must not perform unbounded network work in its
synchronous lookup. A separate trusted TerminationAuthority must observe
runtime cleanup for each actual sandbox; there is no implementation of that
observer here either.
The effective deployment must demonstrate all of the following before either authority can be integrated:
- Explicit runsc isolation; pinned guest image and execution-service binaries;
the same Trellum package version as the portal. The image must provide
/opt/trellum/bin/python, protected root-owned/analysis/inputand a fresh guest-writable/analysis/output, with no inherited secrets or host mounts. Python runs/analysis/input/analysis.py. Report builds run the ordinarypython -I -m trellum.run /analysis/input/report --no-serve --output /analysis/output. No guest image or alternate report implementation is built here. - An isolated worker network denying IPv4/IPv6 egress, DNS leakage, host, metadata, control plane, service endpoints, other sandboxes and other tenants. Verify that execution-service access cannot become a secret-exfiltration channel, and that the selected proxy strips trusted credentials before guest forwarding. Authentication and TLS must be effective on all trusted routes.
- CPU, memory, wall-time and guest-process enforcement; non-root execution, dropped capabilities and no-new-privileges. A container PID limit alone does not prove a guest-process bound under gVisor.
- Bounds on all writable storage and inodes, including execution-service logs and temporary/mounted storage. Docker writable-layer size alone does not establish these bounds. Protected input files and their parent directories must resist replacement by the guest.
- A file service/collection boundary that rejects links and special entries,
including hardlinks and parent-directory symlinks. OpenSandbox
EntryInfodoes not expose link counts, and a metadata/read race is not proof of a safe remote filesystem snapshot. These gaps must remain unverified until addressed by trusted enforcement and real probes; the adapter's byte quarantine is not attestation of remote filesystem safety. - Exact termination of all descendants and execution-service work, removal of writable storage, durable identity correlation and fenced recovery after worker failure, disconnect, cancellation and ambiguous deletion.
OpenSandbox's default host network is unsuitable. Its gVisor profile rejects
networkPolicy/egress-sidecar combinations; this adapter supplies no such policy
and relies on independently proven worker networking. No daemon, firewall,
runtime, storage or deployment settings are installed or changed by this adapter.
See the pinned upstream server configuration
and secure runtime guide.
Hostile output boundary and verification
Uploads preserve validated relative POSIX names within /analysis/input.
Absolute paths, drives, traversal, aliases, NUL, backslashes, reserved Git and
credential names, excessive depth, duplicate/case-alias paths and file/directory
collisions are rejected. Default budgets are 64 files, eight path components,
2 MiB per file, 8 MiB total and 64 KiB of logs per attempt. Transport caps apply
before SDK buffering, including chunked downloads and command SSE responses.
Log cursor and cumulative byte counts survive saved-receipt recovery. A log page
that exceeds the remaining budget or cannot be read stops log capture for that
attempt and persists an incomplete flag. Command status polling continues
independently, so excessive or unavailable logs cannot hide command completion.
analysis_artifacts.py accepts only explicitly allowlisted JSON, CSV, text and
PNG names/types. Text must be UTF-8 without NUL; PNG requires its signature but
is not decoded. Content remains untrusted: JSON/CSV are not parsed into trusted
objects, and strings are not safe HTML. No Python, HTML or archive output is
imported, executed, extracted or rendered. Remote file metadata is advisory and
cannot authorize any host path. Quarantine consists of fresh immutable in-memory
bytes with SHA-256 hashes; there is no local filesystem importer or renderer.
The internal candidate store preserves the hashes and completion fence for its
JSON-only contract. Any later serving/import path needs its own validation.
Focused tests use the published SDK over a fake HTTP transport. They cover fail-closed profiles, missing SDK, immutable identity, persisted intent, unknown mutations, cancellation, explicit deletion, exact metadata recovery, destination pinning, bounded responses/logs/downloads, path/type rejection and byte hashes. An opt-in heavy timing test checks local deadline cancellation only. None is runtime containment evidence.
Real conformance probes have not run. On an isolated test worker, record the exact deployment/image/config hashes and effective runtime/OCI/network/storage state, then use synthetic data to probe the controls listed above. Include IPv4/IPv6/DNS and service-route exfiltration attempts; CPU/memory/process and byte/inode exhaustion during execution; protected-input replacement, symlink, hardlink and special-file outputs; descendants surviving main-command exit; and disconnect/crash/cancel/delete races. Verify all-process termination and unchanged fenced outputs through trusted worker observations. These are required checks for a future conformance implementation, not results claimed here.