Code Executor API runs untrusted code inside hardened, ephemeral Podman containers (no capabilities, read-only root, resource limits) and exposes the result over HTTP. Callers manage a persistent session (a server-side working directory) so files can be created, read, and deleted across multiple executions without re-uploading a whole directory snapshot each time.
Linux only: the sandbox depends on rootless Podman, and the per-session limits on XFS project quotas.
Requirements · Sandbox images · Setup · Run API · Configuration · API · Tests · Hardening · Project Layout · Dependencies
aiohttpAPI with session management (/sessions), per-file access and directory listing (/sessions/{id}/files/{path}), code execution (/executeand/sessions/{id}/execute), and/health- Sandboxed execution via
podman runwith CPU/memory/pid/ulimit caps and a hard wall-clock timeout - Supports python, bash, javascript, typescript, c, c++, java, c#, rust
- Sessions persist a working directory across executions, guarded by a per-session lock; idle sessions expire automatically
executereports what changed: created/modified files (returned as multipart attachments, capped atMAX_RESULT_ATTACHMENTSwith the remainder named inomitted_files) and deleted files- Per-session byte and inode limits enforced by the kernel via XFS project quotas, so runaway file creation fails inside the sandbox rather than breaking the API
- Python 3.12+
- Podman (the
podmanCLI must be on the API process'sPATH) - The sandbox images must be built before starting the API, as the user that runs the API -
executor_images/build.shbuilds every image in parallelThe API runs withexecutor_images/build.sh # every environment executor_images/build.sh rust gcc # only these (the base images are always rebuilt, which is a cache hit if unchanged)
--pull=never, so an image that was never built fails its executions straight away instead of sending Podman to look for the name in a registry.
The API shells out to podman run as the user running the service, so that user needs a working Podman setup, and the API requires that setup to be rootless (with lingering enabled if the service is not started from a login session). Rootful Podman is not supported: podman unshare, which runs the file helper below, refuses to run as root, so a rootful deployment fails at startup - and without a user namespace, container uid 4000 would be the real host uid 4000. Notes:
- Session working directories are bind-mounted into the container, which runs with Podman's default rootless user namespace: container uid
0is the service account, and container uids from1up map onto the service account's subordinate range from/etc/subuid. The code runs asappuserbecause the executor passes--user=<CONTAINER_USER_ID>:<CONTAINER_USER_ID>- the images set noUSER, so they build as root throughout - and on the host that uid is a subordinate one (103999with a range starting at100000) that owns nothing outside the session directories. Because images run with the storage's own mapping, a never-run image starts as fast as any other: there is no per-image re-chown. The id is pinned to4000in bothexecutor_images/base/ContainerfileandCONTAINER_USER_ID; keep them in sync. It is deliberately not1000, so that if the user namespace is ever missing the container's uid does not land on a real host account. - Session files therefore have two owners: the service account owns the session root, and
CONTAINER_USER_IDowns each session's directory and everything in it. The API bridges the two with a file helper (code_executor_api/fs_helper.py) it starts underpodman unshare, where it holdsCAP_CHOWN,CAP_DAC_OVERRIDEandCAP_FOWNERover the subordinate ids. The helper creates each session directory (mode0700) still owned by the service account, so the session's XFS quota can be applied to it, and only then hands it over toCONTAINER_USER_ID. It creates uploads owned byCONTAINER_USER_ID, lists, opens, deletes and removes what executed code creates, and passes open file descriptors back to the API over a socket pair. It is confined toSESSION_ROOT_DIRECTORYand walks every path one component at a time without following symlinks. The API starts it at startup - if it cannot, the server does not start - and restarts it if it dies.podman unshareneeds nothing beyond the working rootless setuppodman runalready does. - Rootless additionally requires
/etc/subuidand/etc/subgidranges for the service account that are wider thanCONTAINER_USER_ID, since container ids from1up map into that range in order,CONTAINER_USER_IDincluded. The conventional 65536-wide allocation is ample; a hand-trimmed range is not. - On SELinux-enforcing hosts, bind mounts need a relabel: append
:Zto the--volumeargument incode_executor_api/executor/podman_executor.py.
Each environment has its own image, so a language only ever runs next to its own toolchain. They are tagged <PODMAN_IMAGE_PREFIX>-<environment>, and code_executor_api/languages.py decides which one each language runs in:
| Environment | Built from | Adds | Languages |
|---|---|---|---|
bash |
base/ on python:3.15.2-trixie |
the shared setup, on top of Python | bash |
python |
python/ on <prefix>-bash |
the pip packages | python |
node |
node/ on <prefix>-base |
Node.js 26, tsx |
javascript, typescript |
gcc |
gcc/ on <prefix>-base |
gcc, g++ |
c, cpp |
java |
java/ on <prefix>-base |
OpenJDK 25 | java |
dotnet |
dotnet/ on <prefix>-base |
.NET SDK 10 | csharp |
rust |
rust/ on <prefix>-base |
the minimal rustup profile, plus gcc as rustc's linker |
rust |
<prefix>-base is base/ on debian:trixie: the shared setup with nothing else, which no language runs in directly. The shared setup itself - the utilities (curl, git, ping, dig, nmap, ...) and the pinned appuser - lives only in base/Containerfile, which build.sh builds twice with a different FROM_IMAGE. Every other image takes its parent as the BASE_IMAGE build argument. Adding a language to an existing environment only takes an entry in languages.py; a new environment also needs a directory under executor_images/ and an entry in build.sh's environments list.
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtDefault host/port (from env or defaults):
python app.pyOverride host/port from CLI:
python app.py --host 127.0.0.1 --port 40003Startup fails with a missing-variable error when SESSION_QUOTA_MOUNTPOINT is not set, since nothing else enforces MAX_SESSION_SIZE/MAX_SESSION_ENTRIES. Pass --no-session-quota to start anyway - a development convenience that logs a warning and leaves both limits unenforced:
python app.py --no-session-quotaRead from the environment at import (see code_executor_api/config.py). A malformed value fails startup rather than surfacing later as a 500, and nothing re-reads the environment afterwards, so changing one means restarting the server.
| Variable | Default | Notes |
|---|---|---|
HOST |
127.0.0.1 |
Loopback, because the API is unauthenticated and executed code can route back to the host. See Hardening before binding wider |
PORT |
40003 |
|
EXECUTION_TIMEOUT |
20 |
Seconds of wall clock per execution |
MAX_MEMORY |
256M |
|
MAX_CPU_CORES |
1 |
|
MAX_OUTPUT_SIZE |
10485760 |
Bytes; output past this is truncated, not failed |
MAX_CODE_LENGTH |
65536 |
Bytes; must stay under the kernel's MAX_ARG_STRLEN (128 KiB), since code is passed as one podman run argv entry |
MAX_SESSION_SIZE |
104857600 |
Bytes per session, enforced only by the XFS quota - see Enforcing MAX_SESSION_SIZE |
MAX_SESSION_ENTRIES |
32768 |
Inodes per session (files, directories and symlinks alike), enforced the same way. Keep it well clear of what a real workload installs - a scientific Python stack is roughly 15000 |
MAX_RESULT_ATTACHMENTS |
256 |
Changed files returned as /execute parts; the rest are named in omitted_files, and execution is never failed over it |
MAX_SESSIONS |
64 |
Once reached, creating a session evicts the least-recently-used idle one - see SESSION_EVICTION_MIN_IDLE_SECONDS |
MAX_CONCURRENT_EXECUTIONS |
4 |
|
CONTAINER_PIDS_LIMIT |
128 |
|
CONTAINER_USER_ID |
4000 |
uid and gid of appuser inside every sandbox image: executed code runs as it, and the file helper gives session files to it. Must match executor_images/base/Containerfile and fall inside the service account's /etc/subuid and /etc/subgid ranges |
CONTAINER_ULIMIT_NOFILE |
1024 |
|
CONTAINER_ULIMIT_FSIZE |
268435456 |
Bytes, per individual file |
CONTAINER_RELATIVE_NICENESS |
5 |
Added to the API process's own niceness |
CONTAINER_TMPFS_SIZE |
64m |
Size of the container's /tmp |
CONTAINER_NETWORK |
bridge |
Podman network for executed code, i.e. what /execute selects when internet_access is true or omitted. The default reaches the host - see Hardening. Must be one that gets its own namespace: host makes podman run fail outright, because the container is also given --sysctl net.ipv4.ping_group_range (see ping needs no capability) |
PODMAN_IMAGE_PREFIX |
code_executor |
Each language runs in <prefix>-<environment> (see Sandbox images); must match the prefix executor_images/build.sh was run with |
PODMAN_CHECK_TIMEOUT_SECONDS |
5 |
|
SESSION_INACTIVITY_TIMEOUT_SECONDS |
7200 |
Seconds before an idle session is deleted |
SESSION_SWEEP_INTERVAL_SECONDS |
60 |
Seconds between expiry sweeps |
SESSION_EVICTION_MIN_IDLE_SECONDS |
300 |
Seconds a session must have been idle before a new one can evict it at MAX_SESSIONS. Busy sessions are never evicted; when no session qualifies, creation returns 503. 0 evicts any idle session; a value at or above SESSION_INACTIVITY_TIMEOUT_SECONDS only evicts expired sessions the sweep has not reached yet |
SESSION_LOCK_WAIT_TIMEOUT_SECONDS |
30 |
Seconds a request waits for a session lock or an execution slot before returning 409/503 |
SESSION_ROOT_DIRECTORY |
system temp dir | Base directory for session working directories |
SESSION_QUOTA_MOUNTPOINT |
unset | XFS mount point containing SESSION_ROOT_DIRECTORY. Unset leaves both session limits unenforced, which the server refuses to start under without --no-session-quota - see Enforcing MAX_SESSION_SIZE |
SESSION_QUOTA_COMMAND |
xfs_quota |
argv prefix for xfs_quota, split like a shell command line but exec'd directly. Set it to sudo -n /usr/sbin/xfs_quota to delegate CAP_SYS_ADMIN to that one command - see Enforcing MAX_SESSION_SIZE |
Running a second (e.g. test) deployment means pointing a separate process at a separate PORT/PODMAN_IMAGE_PREFIX via its own environment, with the images built under that prefix (PODMAN_IMAGE_PREFIX=code_executor_test executor_images/build.sh).
curl http://127.0.0.1:40003/healthRequests to /health are excluded from the access log.
Create a session (optionally seeding files via multipart, filename = relative sub_path):
curl -X POST http://127.0.0.1:40003/sessionsResponse: {"session_id": "..."}
Delete a session immediately:
curl -X DELETE http://127.0.0.1:40003/sessions/{session_id}curl http://127.0.0.1:40003/sessions/{session_id}/files/some/path.txt
curl http://127.0.0.1:40003/sessions/{session_id}/files/
curl -X PUT --data-binary @localfile.txt http://127.0.0.1:40003/sessions/{session_id}/files/some/path.txt
curl -X DELETE http://127.0.0.1:40003/sessions/{session_id}/files/some/path.txtGET/PUT/DELETEon a file return404if the session or file doesn't exist.PUTcreates or overwrites the file (parent directories are created as needed); the request body is the raw file bytes.PUT(like seeded files and/executeattachments) returns413when the write is refused by the session's XFS quota or exceeds the per-fileCONTAINER_ULIMIT_FSIZEcap. The body is streamed to a temporary file first, so a rejected write never leaves a truncated file behind. WithoutSESSION_QUOTA_MOUNTPOINTonly the per-file cap applies, and a session's total size is unbounded.GETon a directory returns a JSON listing of that one level instead of file bytes; an empty path lists the session root. Unlike execution results the listing hides nothing - hidden directories and symlinks are included - so it is the way to discover files that/executeexcluded or omitted. Symlinks are reported, never followed.
{"path": "some", "entries": [
{"name": "path.txt", "type": "file", "size": 12, "modified_at": 1757684400.123},
{"name": "nested", "type": "directory", "size": 4096, "modified_at": 1757684400.5}
]}type is one of file, directory, symlink or other.
POST /execute or POST /sessions/{session_id}/execute as multipart/form-data:
session_id(path segment, only for/sessions/{session_id}/execute) - must reference a live session (404otherwise); if you instead callPOST /execute, a throwaway session is created and destroyed for this call onlylanguage(text field) - one ofpython,bash,javascript,typescript,c,cpp,java,csharp,rustjavascriptaccepts both CommonJS and ES module syntax (Node resolves the module type from the code itself) and supports top-levelawaittypescriptis transpiled bytsx, which strips types without checking them, so a type error surfaces as a runtime failure rather than blocking the run; it executes as CommonJS, acceptingrequire,import,enumandnamespace, but not top-levelawait- both resolve relative paths and module specifiers against the session directory, so code can read and import files already in the session
code(text field)attachments(optional file parts, filename = sub_path) - created/overwritten in the session before executioninternet_access(optional text field,trueorfalse, defaulttrue) -falseruns the container with--net=none, so executed code gets a loopback interface and nothing else: it cannot resolve names, reach the internet, or route back to the host, the API or the other sessions sharingCONTAINER_NETWORK. Worth asking for when the code has no use for the network. Anything other thantrue/falseis a400
Response is multipart/mixed: the first part is application/json -
{"output": "...", "return_code": 0, "execution_time": 0.42, "timed_out": false, "deleted_files": [], "omitted_files": []}- followed by one file part per file created or modified during the run, capped at
MAX_RESULT_ATTACHMENTS.
Each attachment part carries its session sub_path in the RFC 5987 extended parameter, with a flattened ASCII filename for clients that only understand that one:
Content-Disposition: attachment; name="attachments"; filename="out_file.txt"; filename*=UTF-8''out%2Ffile.txt
Read filename* (aiohttp's part.filename already prefers it) to get the exact sub_path, matching the raw sub_paths in deleted_files and omitted_files. A plain filename cannot carry one: RFC 6266 has recipients strip directory components, and percent-escapes have no defined meaning there. filename* also keeps names containing quotes, newlines or non-ASCII characters - all of which executed code can create - from altering the header.
Notes on what counts as changed:
omitted_filesnames the changed files that did not fit underMAX_RESULT_ATTACHMENTS(or that could not be read back, including filenames not representable as UTF-8). The run still succeeded. Readable files in a live persistent session can be fetched individually withGET /sessions/{id}/files/{path}; a throwaway/executesession is destroyed after the call, so its omitted files cannot be fetched later.deleted_filesis never truncated.- Change detection compares
(inode, size, mtime, ctime)rather than hashing contents, so rewriting a file with byte-identical content counts as a modification and comes back as an attachment. - Hidden directories are excluded at every depth. The session directory is also the container's
$HOME, so.cache,.local,.npmand the like would otherwise flood the response with package-manager noise. They still occupy the session's byte and inode quotas, and are still visible through the files API.
Error statuses: 400 invalid input (bad language, invalid path), 404 missing session, 409 session lock timeout, 413 request/session limit, 503 unavailable capacity (for session creation: every session is busy or used within SESSION_EVICTION_MIN_IDLE_SECONDS, so none could be evicted), 500 unexpected error fallback (including a failure to apply the session's XFS quota, when SESSION_QUOTA_MOUNTPOINT is configured).
python -m pytest
python -m pytest --api-url http://127.0.0.1:40003
python -m pytest --collect-only -q
python -m pytest -m results --skip-heavy
python -m pytest -k awkward_result_filenames --tb=longtests/ drives a running server over HTTP and asserts the behaviour this README documents. Nothing there imports the API: every test talks to the server as a client does, which is what lets it cover what only exists once podman, the bind mount and the XFS quota are real - a symlink escape, an OOM kill, a quota refusal. Install the development dependencies with pip install -r requirements-dev.txt, which is the API's own requirements plus pytest and pytest-asyncio.
Each test is named for the behaviour it covers, so --collect-only -q lists the whole suite without a server, and --markers lists the groups with what each one needs. -k takes a test name, -m a group name. A run executes every selected test even after one fails, with pytest's summary and exit code; -x stops at the first failure, --lf re-runs just the ones that failed, and --skip-heavy drops the tests that stress the host (fork bombs, large allocations, multi-megabyte transfers).
Each test is handed its own freshly created session, and its own is deleted afterwards whatever the test did, so tests neither depend on nor disturb one another and any one of them can be run alone. A failing cleanup DELETE only warns - turning it into a failure would blame the wrong test.
| Group | What it covers |
|---|---|
core |
Session and file lifecycle, PUT/GET/DELETE including nested parents, directories, symlinks and zero-byte bodies, directory listings, sub_path containment, that an interrupted PUT leaves the original file intact with no staging debris, and that files cross the two owners both ways: executed code can append to an upload, and the API attaches, lists, reads and deletes a 0600 file code made in a 0700 directory |
languages |
All nine languages: module styles for javascript, type syntax for typescript (and that it is CommonJS, so top-level await fails), and for each compiled language a hello world, a compile error with diagnostics, and the requirement that nothing is left in the session directory |
sandbox |
Read-only root filesystem, symlink containment, that the container uid is a subordinate one rather than the service account, RLIMIT_NOFILE, and (heavy) that MAX_MEMORY kills rather than hangs, CONTAINER_PIDS_LIMIT bounds process creation without breaking the session, and MAX_OUTPUT_SIZE truncates without failing the run |
results |
Change detection including cases a naive (size, mtime) stamp would miss, the MAX_RESULT_ATTACHMENTS cap and its omitted_files, that deleted_files is never truncated, that a non-UTF-8 filename is omitted rather than fatal, and that awkward filenames (quotes, newlines, spaces, non-ASCII, nested paths) survive Content-Disposition exactly |
errors |
The documented status codes for malformed /execute and /sessions requests, and that a rejected request leaves neither attachments nor session slots behind |
network |
That the sandbox has the outbound access CONTAINER_NETWORK intends, that internet_access=false takes it away without breaking the run, and that executed code cannot reach the API that is running it |
The network group needs outbound access from the container; deselect it with -m "not network" where there is none. test_internet_access_disabled is the exception - it only asserts that the network is absent, so it runs anywhere on its own.
test_api_unreachable_from_sandboxis worth reading the failure message of. The sandbox has a routable path back to the host, so a server bound beyond loopback is reachable from the code it executes - which can then exhaustMAX_SESSIONSand start further executions of its own, sidestepping the per-container limits. It cannot read other callers' files: session ids are not discoverable from inside.HOSTdefaults to127.0.0.1so this passes out of the box; if you bind wider, isolateCONTAINER_NETWORKinstead. See Hardening.
Each needs the server configured differently from production defaults, so each has its own flag and is skipped (loudly, with its requirement) otherwise. Start a second server with the tuned environment on its own port and point the suite at it. The value flags exist because nothing tells the suite what the server is configured to; if they disagree, the assertion messages say so.
| Flag | Server configuration | Value flags |
|---|---|---|
--check-timeout |
EXECUTION_TIMEOUT=8 |
--execution-timeout 8 |
--check-capacity |
MAX_SESSIONS=4 MAX_CONCURRENT_EXECUTIONS=2 SESSION_EVICTION_MIN_IDLE_SECONDS=2 |
--max-sessions 4 --max-concurrent-executions 2 --eviction-min-idle 2 |
--check-lock |
SESSION_LOCK_WAIT_TIMEOUT_SECONDS=2 |
--lock-wait-timeout 2 |
--check-sweep |
SESSION_INACTIVITY_TIMEOUT_SECONDS=5 SESSION_SWEEP_INTERVAL_SECONDS=2 |
--inactivity-timeout 5 --sweep-interval 2 |
--check-fsize |
CONTAINER_ULIMIT_FSIZE=1048576 |
--max-file-size 1048576 |
--check-quota |
SESSION_QUOTA_MOUNTPOINT on an XFS prjquota mount |
--max-session-size / --max-session-entries |
--check-host |
none, but the suite must run on the API host | --session-root <SESSION_ROOT_DIRECTORY> |
EXECUTION_TIMEOUT=8 SESSION_LOCK_WAIT_TIMEOUT_SECONDS=2 python app.py --no-session-quota --port 40010
python -m pytest --api-url http://127.0.0.1:40010 -m "timeout or lock" \
--check-timeout --check-lock --execution-timeout 8 --lock-wait-timeout 2-k and -m narrow what runs but never open a gate: an opt-in group runs only when its --check-<group> flag is passed, so a single one of its tests is python -m pytest --check-quota -k project_id_reuse. --check-all turns on every opt-in group, but no single server configuration satisfies all of them at once - capacity wants limits the other groups need headroom under, and fsize wants a per-file cap too small for csharp to build under - so it is for a purpose-built server, and it says so when used.
--check-capacity in particular should be run on its own. It works by saturating MAX_SESSIONS, and every other test creates a session of its own.
The host group shells out to podman and looks at SESSION_ROOT_DIRECTORY directly, because what it covers is not visible over HTTP: that no container outlives the request that started it, that throwaway sessions leave no directories behind, and that DELETE really removes a session's directory even when executed code left something awkward in it.
--check-quota needs a real XFS filesystem with project quotas enabled, which a loopback image provides without a spare disk:
apt install xfsprogs
truncate -s 2G /var/tmp/code_executor_quota.img
mkfs.xfs /var/tmp/code_executor_quota.img
mkdir -p /var/lib/code_executor
mount -o loop,prjquota /var/tmp/code_executor_quota.img /var/lib/code_executor
mkdir -p /var/lib/code_executor/sessions
chown "$SERVICE_USER" /var/lib/code_executor/sessions
xfs_quota -x -c 'state' /var/lib/code_executor # Project quota state: ON, Enforcement: ONThen start the server with SESSION_ROOT_DIRECTORY=/var/lib/code_executor/sessions and SESSION_QUOTA_MOUNTPOINT=/var/lib/code_executor, and run python -m pytest --check-quota. The mount does not survive a reboot, which is the point - it is a test fixture, not the deployment recipe in Enforcing MAX_SESSION_SIZE.
.github/workflows/tests.yml runs the whole suite on every push, against a real deployment: .github/scripts/provision-host.sh builds one on the runner - rootless Podman under a dedicated codeexec account, an XFS prjquota loop mount for the sessions, the sandbox images pulled from GHCR. It follows the deployment above rather than a simplified one, because what it covers only exists once Podman, the bind mount and the project quota are real.
No single server configuration satisfies every group - capacity wants limits the other groups need headroom under, and fsize wants a per-file cap too small for csharp to build under - so the suite runs as four passes (.github/scripts/run-suite.sh), each with its own API process, port and session root:
| Pass | Groups | Server configuration | Suite flags |
|---|---|---|---|
main |
core, languages, sandbox, results, errors, network, host, quota |
production defaults | --check-host --check-quota |
tuned |
timeout, lock, sweep |
EXECUTION_TIMEOUT=8, SESSION_LOCK_WAIT_TIMEOUT_SECONDS=2, SESSION_INACTIVITY_TIMEOUT_SECONDS=5, SESSION_SWEEP_INTERVAL_SECONDS=2 |
--check-timeout --check-lock --check-sweep --execution-timeout 8 --lock-wait-timeout 2 --inactivity-timeout 5 --sweep-interval 2 |
fsize |
fsize |
CONTAINER_ULIMIT_FSIZE=1048576 |
--check-fsize --max-file-size 1048576 |
capacity |
capacity |
MAX_SESSIONS=4, MAX_CONCURRENT_EXECUTIONS=2, SESSION_EVICTION_MIN_IDLE_SECONDS=2 |
--check-capacity --max-sessions 4 --max-concurrent-executions 2 --eviction-min-idle 2 |
--check-all is never used, and --skip-heavy never is either: the heavy tests only mean anything against a real deployment. A group added to tests/conftest.py fails the run until a pass claims it - run-suite.sh checks the four selections against GROUPS before starting a server.
.github/workflows/images.yml builds and publishes the images to ghcr.io/kevin-ovi/code-executor-<environment> whenever executor_images/ changes, tagged latest and sha-<7>; the workflow derives the owner from github.repository_owner and lowercases it, because OCI repository names have to be lowercase and a fork then publishes under its own account. The test job pulls the sha tag of its own commit, and falls back to latest with a warning when there is none - so a branch whose images were never built still runs, against whatever main last published. The packages are public, so pulling needs no credentials; the GITHUB_TOKEN the job passes anyway is what a private package would need.
Containers run with --net=$CONTAINER_NETWORK, which defaults to podman's bridge. That gives executed code a routable path to the host - host.containers.internal, host.docker.internal and the bridge gateway address all resolve from inside - so anything the host listens on with a non-loopback binding is reachable from the code being executed. That includes this API.
This is not derivable from the flag list, and it is the assumption the per-container limits are implicitly making: --pids-limit, --memory and --cpus bound one container, but code that can reach the API does not have to defeat any of them. It calls POST /execute and gets another container with a fresh budget. MAX_CONCURRENT_EXECUTIONS still caps the total, so there is a ceiling; what changes is that a single submission's resource envelope is no longer the per-container limits.
What it allows, stated precisely:
- Denial of service and session eviction.
POST /sessionsuntilMAX_SESSIONSis exhausted. From then on, each further creation evicts the least-recently-used session idle for at leastSESSION_EVICTION_MIN_IDLE_SECONDS, so a flood deletes other callers' idle sessions along with their files, and they get404on their next request. Once every session is the flood's own and recent, or busy, legitimate callers get503, and re-creating sessions keeps it that way.SESSION_EVICTION_MIN_IDLE_SECONDSis the trade-off: raising it protects idle sessions longer, at the cost of more503s when the server is full of abandoned sessions.MAX_CONCURRENT_EXECUTIONScan be saturated the same way. On disk that isMAX_SESSIONS×MAX_SESSION_SIZE, or unbounded whenSESSION_QUOTA_MOUNTPOINTis unset. - Resource amplification, as above.
What it does not allow is cross-session data access. There is no enumeration endpoint - every session-scoped route carries {session_id} in its path and nothing lists sessions. Session ids are 128 bits from a CSPRNG, so they are neither brute-forceable nor predictable from an id the caller legitimately owns. The id never reaches the container either: the working directory is an independently random mkdtemp name, so although /proc/self/mountinfo exposes the host path of the bind mount, the name it reveals is unrelated to the session id, and nothing passes the id in as an environment variable or argument. Reading another caller's files requires an id obtained some other way - a client leaking one, not the API disclosing it.
Note that none of this is sandbox-specific. An unauthenticated API bound to 0.0.0.0 answers anything that can route to the host - other containers, the LAN - and sandboxed code is simply one of those callers, not a privileged one.
Two independent controls. Neither depends on the other, and applying both is the intended production posture. A third, per-request control is available to callers.
1. Keep the API on loopback. HOST defaults to 127.0.0.1, so the default configuration is already closed. If you need remote callers, put a reverse proxy that terminates authentication in front of it rather than binding the API itself wider.
2. Isolate the container network. This is what covers the case where the API must bind beyond loopback, and it is worth doing regardless. Create a dedicated network:
podman network create code_executor_sandbox
podman network inspect code_executor_sandbox --format '{{range .Subnets}}{{.Subnet}}{{end}}'Drop traffic from that subnet to the API's port (substitute the subnet printed above and your PORT):
sudo nft add table inet code_executor
sudo nft 'add chain inet code_executor input { type filter hook input priority 0; }'
sudo nft add rule inet code_executor input ip saddr 10.89.0.0/24 tcp dport 40003 dropThen point the API at it:
export CONTAINER_NETWORK=code_executor_sandboxThis blocks only the API's port. The images' tooling (dnsutils everywhere, requests and yt-dlp in the python image) keeps its outbound access, which test_outbound_network asserts.
Verify both with the suite - test_api_unreachable_from_sandbox probes the host aliases on the API's own port from inside a container:
python -m pytest -k "api_unreachable_from_sandbox or outbound_network"3. Ask for no network per execution. The two controls above are deployment-wide. A caller that has no use for the network can close this path for its own runs instead, by sending internet_access=false on /execute: the container then starts with --net=none and never joins CONTAINER_NETWORK at all, so it has no route to the host, the API or any other session. It stays a request-level decision - the default is still true - so it complements controls 1 and 2 rather than replacing either. test_internet_access_disabled asserts it, and needs no outbound access to do so:
python -m pytest -k internet_access_disabledExecuted code runs as CONTAINER_USER_ID inside Podman's default rootless user namespace, which on the host is a subordinate uid of the service account (103999 with a /etc/subuid range starting at 100000), not the service account itself. That uid owns nothing on the host but the session directories: the API's code, its virtualenv and the Podman image storage all belong to the service account, which code escaping the container does not become. It does own every session's directory, so what keeps an escape out of other sessions is the session root: keep SESSION_ROOT_DIRECTORY owned by the service account with mode 0700, and that uid cannot traverse it to reach them. The file helper and Podman are unaffected, since both work as the namespace's root, which maps to the service account. Left unset, SESSION_ROOT_DIRECTORY falls back to the system temp directory, which anyone can traverse, so other sessions' directories are reachable there.
On a systemd host, Podman's default log_driver is journald: conmon copies everything a container writes to stdout and stderr into the host journal. Here that output is produced by user-submitted code, so it would let any caller of /execute write arbitrary content into journalctl - forged log lines, terminal escape sequences, or enough volume to rotate genuine entries out.
podman_executor.py therefore passes --log-driver=none. Nothing depends on container logs: the output is read back over the pty the container is attached to, and --rm leaves nothing for podman logs to read. Because the flag is on the command line, it also wins over any log_driver set in the service account's containers.conf. Do not remove it.
Containers run with --cap-drop=ALL, and ping is the one shipped utility that looks like a casualty of it. Its own error message says so:
ping: socktype: SOCK_RAW
ping: socket: Operation not permitted
ping: => missing cap_net_raw+p capability or setuid?
That message points at the wrong fix. iputils' ping opens an ICMP datagram socket first and only falls back to a raw socket when the kernel refuses it, and what refuses it here is podman's default net.ipv4.ping_group_range of 0 0 - root's gid only - meeting a container that runs as CONTAINER_USER_ID. Nothing about the capability set is involved. Widening the range to exactly that one gid is therefore the whole fix, and podman_executor.py passes it unconditionally:
--sysctl net.ipv4.ping_group_range=4000 4000
--cap-add=NET_RAW would also make ping work, which is what makes this worth writing down. Podman adds capabilities as ambient ones, so the grant is not scoped to /bin/ping: every process the executed code spawns holds CAP_NET_RAW effective, and with it AF_PACKET sockets. That is packet capture, ARP poisoning and source-address spoofing on a bridge shared with up to MAX_CONCURRENT_EXECUTIONS other sessions - so it would break the cross-session isolation claimed above, which rests on session ids being unguessable rather than on anything at the network layer. It would also make the nftables rule above (which matches on ip saddr) stop being a boundary, since forged frames can carry a source outside the sandbox subnet.
Note that --security-opt=no-new-privileges rules out the other obvious route as well: with NO_NEW_PRIVS set the kernel ignores file capabilities on execve, so setcap cap_net_raw+ep /bin/ping in executor_images/base/Containerfile would not work either.
test_ping_without_net_raw asserts both halves - that ping works and that every capability set is still empty - because either one alone passes under the wrong fix:
python -m pytest -k ping_without_net_rawUtilities that genuinely do stay unavailable under --cap-drop=ALL: nmap's privileged scan types (-sS, -sU, -O, --traceroute; note that --cap-add would not help, as nmap gates those on geteuid() == 0 rather than on capabilities - -sT, its non-root default, works), binding ports below 1024, chown to another uid, mount, dmesg, and raising ulimits. Everything else the images ship - dig, netstat, arp, telnet, git, curl, wget, the toolchains and the Python stack - is unaffected.
Without SESSION_QUOTA_MOUNTPOINT, MAX_SESSION_SIZE is not enforced at all - neither against files written through the API nor against what executed code writes directly into the session's mounted working directory - which is why the server refuses to start unless --no-session-quota says that is intended. The quota is the only mechanism that enforces it, so put SESSION_ROOT_DIRECTORY on an XFS filesystem with project quotas enabled:
apt install xfsprogs
mkfs.xfs /dev/vdb # a dedicated disk/partition
mkdir -p /var/lib/code_executor/sessions/etc/fstab:
/dev/vdb /var/lib/code_executor xfs defaults,pquota 0 2
mount -a
xfs_quota -x -c 'state' /var/lib/code_executor # confirm "Project quota state: ON"Then configure the service:
SESSION_ROOT_DIRECTORY=/var/lib/code_executor/sessions
SESSION_QUOTA_MOUNTPOINT=/var/lib/code_executor
SESSION_QUOTA_MOUNTPOINT must be the XFS mount point, spelled exactly as it appears in /proc/mounts - not the session directory, and not any other directory on that filesystem. xfs_quota addresses a filesystem, so pointing it at a plain directory fails, and session creation returns 500. The two variables are independent: mounting the filesystem directly at the session directory is equally valid, in which case they are the same path.
# filesystem mounted at the session directory itself
# /dev/loop0 /var/lib/code_executor/sessions xfs rw,...,prjquota 0 0
SESSION_ROOT_DIRECTORY=/var/lib/code_executor/sessions
SESSION_QUOTA_MOUNTPOINT=/var/lib/code_executor/sessions
Confirm the value is right before starting the service - xfs_quota -x -c 'state' "$SESSION_QUOTA_MOUNTPOINT" should report Project quota state: ON and, under Accounting/Enforcement, ON rather than the accounting-only state that pqnoenforce produces.
On session creation, SessionManager allocates a project id and runs xfs_quota -x -c 'project -s -p <dir> <id>' -c 'limit -p bhard=<MAX_SESSION_SIZE in KiB>k ihard=<MAX_SESSION_ENTRIES> <id>' <mountpoint>, tagging the session's directory so any write exceeding either quota - from the API or from code running in the container - fails with ENOSPC (surfaced as a 413 from the API, or as a normal write error inside the container). XFS reports project quotas as ENOSPC rather than EDQUOT, and does so for both limits, so exhausting the inode allowance is indistinguishable from filling the byte allowance without consulting xfs_quota report. The quota is applied right after the file helper creates the session directory, while the service account still owns it, and only then does the helper hand the directory over to CONTAINER_USER_ID - so xfs_quota never has to open a directory owned by the container user, and executed code never gets a directory without its quota. This requires the API process to be able to run xfs_quota -x, which needs CAP_SYS_ADMIN. The API itself runs unprivileged - rootless Podman requires it - and quota setup is the only thing that wants privilege, so it should get no more than that one call: the service parses untrusted multipart input and handles filenames chosen by executed code, and any wider grant would turn an API bug into a privilege escalation.
Delegate just that call, with a sudoers rule scoped to the binary:
codeexec ALL=(root) NOPASSWD: /usr/sbin/xfs_quota -x -c *
then point the service at it:
SESSION_QUOTA_COMMAND="sudo -n /usr/sbin/xfs_quota"
SESSION_QUOTA_COMMAND is an argv prefix, split with shlex and exec'd directly, so no shell is involved. -n makes sudo fail immediately rather than blocking on a password prompt. The residual grant is real but bounded: the service account can administer quotas on that filesystem, and nothing else.
Prefer this over setcap cap_sys_admin+ep /usr/sbin/xfs_quota. File capabilities need no SESSION_QUOTA_COMMAND change, but they attach to the binary for every local user, handing CAP_SYS_ADMIN to anyone with a shell on the box - a much wider grant than the sudoers rule for the same benefit.
Both hard limits are verified after they are set, because limit can exit 0 without registering anything (notably when the filesystem is mounted pqnoenforce instead of prjquota - in that case quotas are accounted and reported but never enforced, which no amount of verification can detect; check /proc/mounts).
app.py- CLI entrypoint and server startuptests/- pytest acceptance suite: drives a running server over HTTP (see Tests);tests/client.pyholds the HTTP helpers andtests/conftest.pythe mirrored server limits, the opt-in gates and the fixturescode_executor_api/app_factory.py- app wiring, startup, and cleanup hookscode_executor_api/config.py- environment-backed constantscode_executor_api/languages.py- the supported languages: which image each runs in, and with which commandcode_executor_api/validation.py- sub_path normalization, language/null-byte validationcode_executor_api/file_helpers.py- streaming reads/writes (bounded per file) shared by sessions and file uploadscode_executor_api/sessions.py-Session/SessionManager: locking, creation/deletion, expiry sweep, and (whenSESSION_QUOTA_MOUNTPOINTis set) per-session XFS project quota setupcode_executor_api/executor/podman_executor.py- Podman container invocation and file-diffingcode_executor_api/routes/-/sessions,/sessions/{id}/files/{path},/execute(and/sessions/{id}/execute),/healthhandlersexecutor_images/- one directory per sandbox image, each with itsContainerfileand, for the compiled languages, theexecutors/*.shscripts that compile and run them;build.shbuilds them all (see Sandbox images)
From requirements.txt:
aiohttpaiofiles
The suite adds pytest and pytest-asyncio, from requirements-dev.txt.