pack-python-untrusted-input
Skill166 starsChanged 6 days agoApache-2.0View on GitHub
Checklist and measured gotchas for Python code that loads YAML or JSON from an untrusted or semi-trusted source (duplicate keys, aliases and anchors, merge keys, nesting depth, size caps), calls HTTP or GraphQL APIs (redirect credential carry, bounded backoff and pagination, never replaying a non-idempotent call after an ambiguous outcome), opens files by path (confinement, symlinks, FIFOs), or guards network access. Load when writing or reviewing config loaders, API clients, file transports, or hostile-input tests. Not for general style or typing questions.
In this repository63 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- templates/copilot-instructions.mdCopilot instructions
- pack-ad-disclosureSkill
- pack-asset-productionSkill
- pack-audience-data-privacySkill
- pack-awsSkill
- pack-clip-deskSkill
- pack-copy-reviewSkill
- pack-cyber-tier-reviewSkill
- pack-delivery-business-mgmtSkill
- pack-digitaloceanSkill
- pack-front-doorSkill
- pack-gha-security-dastSkill
- pack-grc-controlsSkill
- pack-implementer-self-checkSkill
- pack-linux-platformSkill
- pack-local-llm-routingSkill
- pack-marketing-grcSkill
- pack-media-dispatchSkill
- pack-media-kit-claimsSkill
- pack-opentofu-spaceliftSkill
- pack-org-dispatchSkill
- pack-org-operating-modelSkill
- pack-platform-data-termsSkill
- pack-python-untrusted-inputSkill
- pack-review-protocolSkill
- pack-rf-emcommSkill
- pack-safe-liveSkill
- pack-stage-crewSkill
- pack-threat-detectionSkill
- pack-threat-modelSkill
- pack-twingate-dopplerSkill
- pack-web-qualitySkill
- pack-ad-disclosureSkill
- pack-asset-productionSkill
- pack-audience-data-privacySkill
- pack-awsSkill
- pack-clip-deskSkill
- pack-copy-reviewSkill
- pack-cyber-tier-reviewSkill
- pack-delivery-business-mgmtSkill
- pack-digitaloceanSkill
- pack-front-doorSkill
- pack-gha-security-dastSkill
- pack-grc-controlsSkill
- pack-implementer-self-checkSkill
- pack-linux-platformSkill
- pack-local-llm-routingSkill
- pack-marketing-grcSkill
- pack-media-dispatchSkill
- pack-media-kit-claimsSkill
- pack-opentofu-spaceliftSkill
- pack-org-dispatchSkill
- pack-org-operating-modelSkill
- pack-platform-data-termsSkill
- pack-review-protocolSkill
- pack-rf-emcommSkill
- pack-safe-liveSkill
- pack-stage-crewSkill
- pack-threat-detectionSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 21
Validation is a security control: Every validation rule needs a test that goes red when that rule is deleted.
- Very specific: line 48
Regexes on untrusted text: Check patterns for exponential backtracking when you load them, run every match under a time limit, and cap the …
- Very specific: line 59
Killable worker: Start the child in its own session (start_new_session=True) and kill the whole process group on a timeout, an error or an …
- Very specific: line 61
Bounded output: Read stdout and stderr through a cap and kill the group when it is exceeded.
- Very specific: line 63
Isolated interpreter flags: Run a Python child as python3 -I (isolated: no user site, no PYTHON* variables, no current directory on the …
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
<!-- Generated by scripts/generate.py (release 0.4.0) from packs/python-untrusted-input/PACK.md, updated 2026-10-29. sha256:93b564407a0b5eeb995404eaf394a9b8adf6b0eaf1f98a802863a0f592debb0a. Do not edit; run the generator. -->Pack: Python untrusted-input and API-client hardening
Status: pilot pack, written 2026-10-08 from findings of 2026-10-07; refreshed 2026-10-29 (issue #69) with this repository's own review lessons (issues #43, #47 and the installer state work) and generic lessons from the SAFO guard and approval reviews (2026-10). UNVERIFIED items were not reproduced.
Untrusted means any bytes you did not write: config files, API responses, downloaded catalogs, directory entries. Most defects below were found by a reviewer who ran a hostile input; none were found by the author's tests.
Checklist: loading YAML and JSON
- Safe loader only.
yaml.safe_loador an explicitSafeLoadersubclass. Audit greps must also catchfull_load,unsafe_load,load(withoutLoader=, andyaml.load_all. A grep that only checksyaml.load(missesfull_load(measured 2026-10-07). - Duplicate keys. PyYAML silently takes the last. Detect them at compose time (override
construct_mapping, or walk the composed node tree) and reject. - Aliases, anchors, merge keys (
<<). Reject or cap them. Alias expansion can multiply memory (the billion-laughs shape). Detect at the event or node level, before construction. - Depth. Limit nesting at compose time, before building Python objects. For JSON,
RecursionErrorandValueErrorfrom deep nesting must be caught and mapped to your own error type, never leaked. - Size cap before parsing. Cap bytes read (read at most N+1 and reject if over). Cap number of nodes if the format allows large flat inputs.
- Validation is a security control. Every validation rule needs a test that goes red when that rule is deleted. Run a mutation sweep: delete each validation in turn, run the suite, and list survivors (14 surviving deletions were found in one loader, 2026-10-07).
- Agree on defaults. A fix that tightens one code path can make two readers of the same file disagree; check that every consumer applies the same defaults.
- Own error type. Parsers must raise one documented exception type for every malformed input; a raw
OSError,UnicodeDecodeError,RecursionErrororKeyErrorescaping is a finding.
Checklist: HTTP and GraphQL clients
- No credential carry across redirects.
urllib's default opener follows 301/302/303 and forwards theAuthorizationheader to the redirect host (reproduced 2026-10-07). Install a redirect handler that refuses redirects, or strips credentials when host, port, or scheme changes. Prove it with two loopback servers on different ports: the second must never see the header. - Non-idempotent calls are never replayed after an ambiguous outcome. After a request is sent, a timeout, 5xx, closed connection, or in-body retryable error is UNKNOWN, not failed. Mutations (GraphQL
mutation, POST that creates) are not retried; surface "outcome unknown" as a distinct state the caller must reconcile. Retry only idempotent reads, or calls with an idempotency key. - GraphQL errors can accompany partial data. Handle
errorsalongsidedata: do not drop partial data silently, do not retry a mutation because the body saysRATE_LIMITED, and treat a malformed body andINSUFFICIENT_SCOPESas distinct, reported outcomes. - Bounded backoff. Cap attempts and total sleep. Parse
Retry-Afterdefensively: rejectnan,inf, negative, and absurdly large values; honor an upper bound. - Bounded pagination. Cap pages. Handle
hasNextPage: truewith a null or repeated cursor (stop, do not loop). - Timeouts everywhere, including connect and read. Cap response size.
- Secrets come from the environment or the secret manager, never argv, logs, or error messages; redact before logging a request.
- A three-fix pattern was observed: each fix closed the reported symptom and left a sibling hole. After a fix, enumerate the sibling cases (see the table) before declaring it done.
Checklist: paths, files, sockets
- Path confinement. Resolve and compare against the root using path components, not string prefix. Open with
O_NOFOLLOWand a directory fd (dir_fd) where the platform supports it; reject symlinks and... An unsafe path is a typed error, not a rawOSError. - FIFOs and special files. Opening a FIFO can hang forever; use
O_NONBLOCKfor the open and checkS_ISREGon the fd (os.fstat). - Atomic writes. Temp file in the same directory,
fsync, rename,fsyncthe directory;flockfor single-writer state. UNVERIFIED on exotic filesystems. - Network guard completeness. A test fixture that forbids sockets must cover the whole surface:
connect,connect_ex,sendto(2 and 3 argument forms),sendmsg,gethostbyname,gethostbyname_ex,getaddrinfo. The 3-argumentsendto(data, flags, address)survived one fix round (2026-10-07).
Checklist: types, text and regexes
- Exact types first. Check every field, key, list member and container with
type(x) is str(notisinstance: a subclass can override__eq__or__hash__, andboolis anint) before any comparison, membership test, regex or hashing. A hostile__eq__that raised escaped a validator as aRuntimeError(DoIA state store review). - Never call
str(),repr()orformat()on a foreign object, including in an error message. Render only an exactstrorintand show?otherwise; a__str__that raisedSystemExitescaped a handler (same review). - Text identity. Compare names after NFC normalization and
casefold(); two distinct names can collide on a case-insensitive or normalizing filesystem. Reject invisible, default-ignorable and control characters and non-ASCII spaces in identifiers and text fields (benchmark corpus review, #47). - Regexes on untrusted text. Check patterns for exponential backtracking when you load them, run every match under a time limit, and cap the input length first. Duplicate JSON keys are an error too (
object_pairs_hook).
Checklist: archives and output caps
- Extract archives by hand. No
TarFile.extractorextractall: write each regular member through a confined path, refuse links, devices and special members, and cap member count, member size, expanded size and nesting depth (#47). - Bounded output everywhere. Cap what you read from a file, a socket, a subprocess pipe and a git stream; over the cap is an error, not a truncation that parses.
- Resource bounds are tested with an input one byte over the cap and a negative case that proves the cap test bites.
Checklist: subprocesses
- Argv list, never
shell=True. Pass the program and arguments as a list; no string built from untrusted text reaches a shell. Use--before untrusted operands. - Killable worker. Start the child in its own session (
start_new_session=True) and kill the whole process group on a timeout, an error or an interrupt; killing only the child leaves grandchildren running (#43, #47). Test it with a grandchild that would write a marker file after the timeout. - The worker limits itself and dies with its parent. In the child set
RLIMIT_CPU(and address-space or file-size limits where they fit) before running untrusted work, and usePR_SET_PDEATHSIG(or a supervisor that reaps) so it dies with its parent. A wall-clock timeout alone does not stop a busy loop from burning CPU until the kill lands. - Bounded output. Read stdout and stderr through a cap and kill the group when it is exceeded; never
communicate()on an unbounded child. - No inherited secrets. Build the environment from an allowlist (a fresh
PATH, an emptyHOMEinside a scratch directory); never passos.environthrough. Tool config (git, pip) from the user's home is also an input: switch it off. - Isolated interpreter flags. Run a Python child as
python3 -I(isolated: no user site, noPYTHON*variables, no current directory on the path) and keep scripts and untrusted files in different directories. - A timeout kills and reports. A signal death is a crash, never a red test result; do not map it to an ordinary exit code.
Checklist: guards, parsers and logs
Measured in the SAFO guard and approval reviews (2026-10); one line each, no bypass detail.
- A guard and the real parser share one definition. If a guard decides what a command, path, term or file means with its own scanner, it will disagree with the real parser on some input. Call the same function, or test them against one shared corpus.
- Fail closed on timeout and on anything unscannable. A scan that ran out of time, depth or input is a refusal with its own reason, never an allow; a marker or override is not honored after it.
- Regex and term shape limits. Cap length, count and character set of user-supplied terms and patterns, and reject shapes the guard cannot judge. A shape limit keeps a check short; it does not prove the content safe, so say so.
- Append-only logs are tamper-evident, not tamper-proof. Hash-chain each record, append under a lock with
fsync, and say plainly that someone who rewrites the whole file and its head can still forge it. - Test-only seams are not reachable from the CLI. An injectable clock, path or transport must not be settable by an option or environment variable; keep it in the test module, and test that the CLI refuses it.
- Hand verification inputs to a checker through sealed or immutable descriptors, not by pathname. A path can be swapped between check and use. Pass a sealed in-memory file (
memfdwith seals) or an already-opened descriptor, and compare what the checker reports it verified against what you looked up. Where sealing is unavailable, refuse rather than fall back to a path. Measured in SAFOsrc/safo/geminisign.py(merged to main, 2026-10): the allowed-signers line and the signature are written tomemfdfiles, sealed against change, and reachssh-keygenas/dev/fdpaths; the output is matched against one exact pattern, its namespace and label are compared with the ones looked up, and the key fingerprint it names is returned for the caller to compare; with nomemfdsupport the call is refused.
How to verify (commands)
- Hostile YAML files in the scratch directory: duplicate keys,
&a/*achains,<<: *a, 10,000-deep nesting, a 100 MB file, a tab/BOM/encoding oddity; run the loader on each and confirm one typed error each. - Loader audit:
grep -rnE 'yaml\.(load|full_load|unsafe_load|load_all)\b' src | grep -v safe_load. - Redirect leak: start two
http.serverinstances on loopback ports, have server A answer 302 to server B, call the client with a token, print B's received headers. - Mutation replay: stub the transport to time out after sending a mutation; assert exactly one send.
- Mutation sweep: for each validation, delete it in a scratch copy and run the suite; any green run is a survivor.
- Revert check: undo the fix, run the new test, expect red; restore, expect green.
- Checks: run the targeted tests for the touched code with the exit code captured (
> log 2>&1; echo "exit=$?"). - Foreign-object probe: pass a subclass whose
__eq__,__hash__and__str__raise; the loader must return its own error type. - Subprocess probe: a child that forks a grandchild writing a marker after the timeout, and one that spins on the CPU; assert the marker never appears and the group is gone.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

