12.7 Securing RAG Data, Keys and the AI Supply Chain
Your RAG corpus, your API keys and your dependency tree are all inputs to the system you ship — and every one of them can be attacked before a single user ever talks to your model. This lesson covers the three supply chains that converge on an LLM application: the data supply chain (what goes into your index, vector store and memory), the credential supply chain (where your provider keys and secrets live and how they leak), and the code-and-model supply chain (dependencies, model files, fine-tunes and the vendors you call). For each, the lesson gives the threat, the realistic attack, the layered defence, and the engineering control you can implement this week.
What you'll learn
- How data poisoning, embedding weaknesses and retrieval-time attacks threaten a RAG or agent system — and which controls actually bound the damage
- Where API keys leak in practice, how to scope and monitor them per provider, and the leak-response playbook to run before you need it
- Which secret managers to use by name (AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault, HashiCorp Vault), and how to fetch a key at runtime with a cache, a refetch on
401and masking, so no key sits in code, a prompt or a log - Why
picklemodel files are arbitrary code, howsafetensors, provenance pinning and hub scanning change the risk, and what the documented malicious-model incidents teach - How dependency attacks work — typosquatting, dependency confusion, compromised maintainers, the two 2026 LiteLLM incidents and LLM-driven "slopsquatting" — and the lockfile, dependency-cooldown, scanning, SBOM, attestation and CI controls that contain them
- How to assess a hosted-LLM vendor (security reviews, subprocessors, exit strategy), harden the infrastructure around your service, and think about model theft and endpoint abuse
- A working
llm_guard_kit/supply_chain.py: a secret scanner with entropy heuristics, a requirements/lockfile hash auditor, and a pickle opcode inspector — all pure Python, all runnable with no keys
What you don't need
- No API keys, no services, no GPU. Every code sample is pure Python 3.11+ standard library and runs locally.
- The RAG pipeline itself: Module 07 owns retrieval, and 06.6 already owns ACL filtering and multi-tenant isolation. This lesson adds the security layer on top and links back rather than re-teaching.
- Prompt-injection mechanics and the lethal trifecta: 12.2 owns the attack side; this lesson assumes you know what indirect injection is.
Setup
Python 3.11+ only — no packages to install, no .env, no keys:
uv init supply-chain-lab --bare --python 3.13 # or any empty project; see 03.1 Part 4
cd supply-chain-labFirst time with uv, or unsure what --bare does? Follow the full project setup in 03.1, Part 4.
The llm_guard_kit package grows across this module; this lesson adds supply_chain.py (Part 9). Everything else is tables, checklists and reference configs. Where a control needs a provider console or a cloud account, the lesson says exactly what to look for — you can do all of it later, with real accounts.
What you must be able to do after this lesson#
- Explain why a RAG corpus is a supply chain and what PoisonedRAG showed
- Scope and monitor provider API keys and follow the leak-response playbook
- Name the main secret managers and fetch a key at runtime without putting it in code, a prompt or a log
- Explain why pickle model files are code and when safetensors helps
- Avoid dependency attacks such as typosquatting and dependency confusion using pinned hashes
- Run the supply_chain.py secret scanner, hash auditor and pickle inspector
- Assess a hosted-LLM vendor with a security review and exit strategy
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "We ingest whatever users upload into the knowledge base." | 2.2 Data poisoning |
| "The vector DB is just an index, it doesn't hold real data." | 2.3 Embedding and vector weaknesses |
| "Someone leaked the OpenAI key — how bad is it?" | 3.5 The leak-response playbook |
| "Which secret manager should we use, and how does the app read it?" | 3.6 Secret managers by name |
"Should we load this Hugging Face model with trust_remote_code?" |
4.1–4.3 The model supply chain |
| "Our agent framework pulls in 400 transitive dependencies." | 5.1–5.2 The software supply chain |
| "Can we prove which model and dataset built this answer?" | 5.2 The defence stack |
| "The provider says they don't train on our data." | 6.2 The data-handling chain |
| "We exposed Ollama on port 11434 for the demo." | 7.1–7.3 Infrastructure security |
| "Can someone steal our model by querying the API?" | 8.1 Model theft and extraction |
Part 1: Three supply chains meet at your app#
1.1 The frame: everything you didn't write is an input#
A traditional web app has one obvious supply chain: your dependencies and your infrastructure. An LLM application has three, and they interlock:
flowchart TB
subgraph data ["Data supply chain"]
D1["Documents, tickets, uploads<br/>(05.x ingestion)"] --> VDB[("Vector store /<br/>index / cache / memory")]
D2["Web pages, emails, tool outputs"] --> VDB
VDB --> RET["Retriever + ACL filter<br/>(06.6, 07.11)"]
end
subgraph creds ["Credential supply chain"]
K1["Provider API keys<br/>OPENAI/ANTHROPIC/GEMINI/OPENROUTER"] --> APP["Your service"]
K2["DB creds, cloud keys,<br/>signing secrets"] --> APP
end
subgraph code ["Code & model supply chain"]
C1["PyPI/npm deps<br/>agent frameworks, SDKs"] --> APP
C2["Model weights, adapters,<br/>GGUF/safetensors/pickle"] --> APP
C3["Hosted providers,<br/>gateways, MCP servers"] --> APP
end
RET --> APP
APP --> MODEL["LLM provider API"]
APP --> USER["Users & rendered output"]Each arrow is a place where someone else's content, credential or code enters your trust boundary. The lesson's organising claim: an attacker who can't touch your code can still own your answers, your bill or your users' data by attacking the inputs. That is exactly what OWASP's 2026 list formalises — verify the current edition at genai.owasp.org: the 2026 release (published August 2026 under the OWASP GenAI Security Project) ranks LLM04:2026 Supply Chain, LLM05:2026 Data and Model Poisoning, and LLM09:2026 Vector and Embedding Weaknesses among its top ten — three of the ten are this lesson's subjects, and a fourth (LLM06:2026 Unbounded Consumption) is what a leaked key turns into.
1.2 The three chains at a glance#
| Chain | What flows in | What an attacker gains | Primary defences (this lesson) |
|---|---|---|---|
| Data | Documents, web pages, tickets, uploads, embeddings, memories, caches | Steers answers (poisoning), extracts data (inversion/leakage), burns money (expensive queries), persists (memory poisoning) | Source trust tiers, provenance + quarantine, ACL-in-query, scoped caches, canary documents, versioned-index rollback |
| Credentials | Provider keys, DB creds, signing secrets, session tokens | Your bill (denial-of-wallet), your data (API access), your reputation (abuse under your name) | Scoped/expiring keys, secret managers, scanning in CI, spend limits, leak playbook |
| Code & models | PyPI packages, model weights, adapters, hosted APIs, MCP servers, container images | Remote code execution on your hosts, backdoored model behaviour, silent model swaps, vendor data access | Hash-pinned lockfiles, model-file scanning, provenance/attestation, minimal deps, vendor review, private endpoints |
1.3 The posture that makes all of it tractable#
Two principles from earlier lessons do the heavy lifting here:
- Assume every input is hostile until proven otherwise — 12.1's threat model and 02.10's "instructions and data share one channel". For supply-chain purposes this means: untrusted applies to a community-uploaded model as much as to a user message.
- Enforce outside the model — ACLs in the query (06.6), spend caps at the provider, hash checks at install time. The model is a persuadable component; your controls must live in deterministic code, infrastructure and contracts.
Part 2: RAG and vector-store security#
2.1 What is already covered — and what this part adds#
Three earlier lessons own the foundations; treat them as prerequisites, not repetition:
- 06.6 owns retrieval-time authorisation: filter pushdown vs post-filtering, the ACL-in-query pattern, isolation topologies, group explosion and permission-change lag, and the rule that the LLM is not a security boundary.
- 07.11, Part 2 owns the production RAG threat model: indirect injection through documents, the lethal trifecta, cache keys carrying permission scope, logs/traces as a leak surface, provider data policies, and the one-page security posture.
- 02.3, 10.7 owns why vectors are sensitive: embedding inversion and membership inference, and "treat vectors like the text they encode".
- 05.9 owns pipeline-side hygiene: secrets, PII stages, deletion propagation, tenant isolation, residency.
What this part adds is the upstream view: the corpus itself is a supply chain. Documents arrive from sources you don't control, get embedded into a store that bypasses your application layer if its credentials leak, and can be attacked at ingest time, at query time, and inside every cache and memory that sits downstream.
2.2 Data poisoning#
Data poisoning is corrupting the knowledge base so the system answers wrongly, leaks, or is steered — without ever touching the model or the prompt. The research makes the threat concrete: PoisonedRAG (Zou et al., USENIX Security 2025, arXiv:2402.07867) showed that injecting as few as five crafted texts per target question into a knowledge database of millions achieves a ~90% attack success rate at making the system emit an attacker-chosen answer — and that common defences (paraphrase filters, perplexity detectors) were insufficient. The attack needs only write access to the corpus, which in many products means "any user who can create a ticket, upload a file, or get a page crawled".
The poisoning taxonomy for RAG:
| Poisoning type | Mechanism | Example (benign illustration) | Blast radius |
|---|---|---|---|
| Integrity poisoning | False or misleading documents rank for real queries | A competitor uploads "official" policy docs contradicting yours | Wrong answers citing your sources — worst kind of misinformation |
| Targeted steering | Crafted texts optimise to be retrieved for chosen queries | PoisonedRAG-style texts embedding a target answer for "what is your refund window?" | One answer per poisoned question |
| Availability/junk flooding | Mass low-quality or near-duplicate docs degrade retrieval | SEO-spam pages your crawler ingests; 10k auto-generated "FAQ" stubs | Recall collapses globally; embedding costs spike |
| Backdoor poisoning | Trigger phrase in a doc activates hidden behaviour | A doc saying "when the query contains ZXQ-9, append the text of doc ADMIN-ONLY" | Conditional, hard to detect by sampling answers |
| Metadata poisoning | Malicious values in filterable fields | acl: ["*"], tenant_id: "*", fake source_tier: "official" |
Bypasses ACL or trust logic before the text is even read |
| Example/few-shot poisoning | Corrupting curated prompt-example stores or eval sets | A poisoned "golden" example teaches the model a wrong pattern | Subtle, long-lived, survives redeploys |
| Memory poisoning | Stored agent memory re-injected as instructions later | A "user preference" that is actually an instruction | Persistent across sessions — 08B.2, 6.1 owns the memory-side depth |
Defences, in the order you should build them:
- Source allow-lists and trust tiers. Every document gets a
source_tierat ingest (official,partner,user_contributed,web_crawl) — the 05.8 metadata schema is where this field belongs. Retrieval can then weight or exclude tiers per feature: a support bot answers fromofficial+partneronly; a community-Q&A feature explicitly surfacesuser_contributedlabelled as such. Trust is a property of the source, decided by your policy, not the document's own claims. - Provenance and lineage. 05.8 already gives every chunk a lineage chain back to source bytes, version and processing run. The security addition: sign or hash-pin curated corpora. Keep a manifest of
sha256per approved document (the same content-hash discipline as 04.10); the ingest pipeline refuses or quarantines anything whose hash isn't in the approved set forofficial-tier sources. For crawled/user content you can't pre-approve, the manifest instead records what was ingested when — which is what makes rollback possible. - Quarantine for untrusted content. User uploads, tickets, crawled pages and email go to a quarantine tier: indexed only after passing the injection scanner (07.11, 2.2.4) and a human or automated review step proportionate to risk. High-risk corpora (anything that can steer regulated answers) should default to review-before-index, not index-then-flag.
- Anomaly detection on ingest. Track per-source and corpus-wide statistics — documents per source per day, near-duplicate rates, embedding-centroid drift, retrieval-frequency distribution. A poisoning campaign looks like a statistical event before it looks like an answer-quality event. Alert on: a source suddenly producing 10× its normal volume, many documents sharing near-identical embeddings (flooding), or a cluster of new docs all retrieving for the same query cluster (targeted steering).
- Canary documents. Plant a small number of documents containing unique canary strings ("the project codeword is ZXQ-4417") into each trust tier. If a canary string appears in an answer, log, trace or external artefact, you have detected exfiltration or unauthorised retrieval — the same trick as canary tokens for secrets (Part 3), applied to the corpus. Canary docs also make poisoning detectable in evals: if retrieval starts surfacing them for unrelated queries, the index is being gamed.
- Versioned indexes and rollback. 05.9, Part 5 already gives you blue/green indexes and aliases. The security property: every ingest batch is a versioned unit you can retract. When poisoning is discovered, the fix is "roll the alias back to the last clean index version" — minutes, not a re-crawl. Keep the tombstone/deletion machinery (07.11, 3.3) able to remove individual poisoned documents too; rollback is the blunt instrument, per-doc deletion is the scalpel.
- Retrieval-time sanity checks. Diversity constraints (don't let one source dominate the top-k), score-distribution monitoring, and citation verification (07.5) — an answer that cites a quarantined or low-trust doc for a high-trust claim is a finding, not a style issue.
2.3 Embedding and vector weaknesses#
The vector store is not a neutral index — it is a second copy of your corpus with its own access surface (OWASP LLM09:2026 Vector and Embedding Weaknesses):
- Inversion and membership inference. Covered in depth at 02.3, 10.7 and summarised at 07.11, 2.3.4: Morris et al. (EMNLP 2023, arXiv:2310.06816) recovered the majority of short input texts — about 92% of 32-token inputs — from their embeddings alone, and vectors can sometimes be translated between embedding spaces. Operational rules already stated there apply with full force: the vector store sits inside your trust boundary — encrypt at rest, restrict access, apply retention/deletion to vectors exactly as to source docs, and never log "vector + doc ID" pairs into debug tooling.
- The vector DB credential is a data credential. Whoever can query the index directly bypasses your application's ACL layer entirely — the filter lives in your query, and a raw client can omit it. Controls: network-isolate the store (no public endpoint), use per-environment credentials, enable the store's own authN/Z and audit log, and never expose the vector DB through the same ingress as your app. If you self-host (Qdrant, pgvector, Chroma — 06.5 compares them), the same rule as Ollama applies (Part 7): bind to loopback or a private interface, put auth in front, log every connection.
- Filter and metadata bypass. 06.6 owns filter-expression safety (allow-listed fields, validated operators, never string-concatenated user input into store query languages). The security additions here: (a) ACL propagation drift — when a user's groups change, every layer that cached a permission decision (retrieval filters, response caches, memory namespaces, session scopes) has a lag window; 06.6, 3.3 covers the mechanics, and 07.11, 2.3.5 makes revocation latency an alertable metric; (b) metadata is attacker-controlled — a poisoned document can set
acl,tenant_id,source_tierorurlfields to malicious values (2.2 metadata poisoning). Validate metadata at ingest against an allow-list of writable fields; system-owned fields (acl,tenant_id,source_tier,ingested_at) are written by your pipeline only, never copied from source content. - Adversarial documents optimised to rank. An attacker who knows your embedding model can craft text that lands near a target query's embedding — keyword stuffing, homoglyphs, embedded instructions that also happen to be retrieval-optimized. Defences are the same stack as poisoning (trust tiers, quarantine, anomaly detection) plus retrieval diversity and score inspection: log the score distribution per query; a result cluster of same-source, same-score docs is suspicious. You cannot enumerate all adversarial documents — you can make them expensive to land and easy to evict.
- Cross-tenant leakage through the store. Already covered at 06.6, Part 3 and 07.11, 2.3.5: the security checklist addition is to test isolation continuously in CI — the tenant-isolation suite runs on every deploy, covering the cache, the stream endpoint, eval/debug routes and any admin UI, not just the happy path.
2.4 Retrieval-time attacks#
Once data is in, the query path itself is attackable:
| Attack | Mechanism | Defence |
|---|---|---|
| ACL probing / filter fuzzing | Issue queries with crafted filters to learn what exists ("does doc X exist for tenant Y?") — error messages, counts and timing differ | Uniform error responses; never return raw counts to untrusted callers; 07.11, 2.3.5 "test it like auth"; rate-limit filter complexity |
| Query manipulation | Rewrite/expand steps (07.3) inherit injection; a query crafted to make the rewriter emit tool calls or exfil URLs | Keep corpus content out of query-understanding prompts (07.3's own defence); validate rewritten queries against the same schema as user input |
| Expensive-query DoS | Huge k, deeply nested filters, regex-heavy metadata filters, maximum-length queries on every request |
Hard caps on k, filter depth and query length in code; timeouts on the store call; per-user query budgets — this is OWASP LLM06:2026 Unbounded Consumption territory, owned operationally by Module 11B (rate limits, quotas) |
| Retrieval of other users' data | Missing or bypassed ACL on a code path (debug endpoint, eval harness, cache lookup) | The ACL is a mandatory clause of every retrieval call — 07.11, 2.3.1; there is no unscoped search in production builds |
| Embedding-API abuse | Your embedder endpoint called directly, or queries chosen to maximize embedding cost | Same authN/Z and rate limits as the chat path; embedding calls are billed per token too |
2.5 Cache and memory poisoning#
Anything that stores model-adjacent state can be poisoned:
- Response and semantic caches (07.11, 4.3; the strategy layer is Module 11B's caching lesson). Two attacks: (a) cross-scope leakage — a cache key missing the permission scope serves tenant A's answer to tenant B (already covered: scope goes in the key); (b) cache poisoning — an attacker crafts queries whose answers are wrong or injected, and your cache faithfully serves them to everyone until TTL expiry. Defences: keep TTLs short on anything user-influenced; never cache refusals, errors or flagged outputs; scope keys by tenant and content version; treat cache-write as a trust decision — only cache outputs that passed output validation (12.5).
- Embedding caches (06.2): keyed by text hash — poisoning means getting a wrong embedding cached for a document. Low risk if keyed on content hash of the canonical text; dangerous if keyed on mutable metadata. Include the embedding-model version in the key (02.3, 10.5 owns drift).
- Agent memory (08B.2): stored memories are re-injected as context in later sessions — a memory-write path that accepts model- or user-generated text is a persistent prompt-injection channel. 08B.2, Part 6 owns the memory-side defences (write policy, validation before write, user visibility, audit); the supply-chain framing adds: memory namespaces must carry the same tenant/ACL scoping as retrieval (08B.2, Part 5), and "forget me" must actually delete memory entries, not just stop retrieving them.
- Shared prompt/example stores: curated few-shot examples, rubric texts and "golden" eval cases are small corpora with outsize influence — a poisoned example teaches the model a pattern that survives prompt edits. Treat them like code: versioned, reviewed, hash-pinned in your prompt library (04.10).
2.6 The RAG hardening checklist#
Tick these for any RAG or retrieval-augmented agent you ship:
- Every document has a
source_tierand full lineage; system-owned fields (acl,tenant_id,tier) are written only by your pipeline - Untrusted sources (uploads, tickets, crawls, email) pass through quarantine + injection scan before indexing
- Curated corpora are hash-pinned; every ingest batch is a retractable index version
- ACL filter is a mandatory clause of every retrieval call, including debug/eval/admin paths; groups come from server-side identity only
- Vector DB is network-isolated, authenticated, audited; credentials are scoped and rotatable
- Every cache key carries permission scope + content/index/prompt versions; flagged or refused outputs are never cached
- Agent memory writes go through validation and are namespace-scoped; deletion propagates to memories, caches, traces and eval sets
- Ingest-time anomaly alerts exist (volume spikes, near-duplicate floods, retrieval-distribution shifts)
- Canary documents per trust tier; canary strings monitored in outputs, logs and traces
- Tenant-isolation tests run in CI on every deploy
- Query cost is capped in code (
k, filter depth, query length, per-user budgets)
Part 3: API keys and secret security#
03.1, Part 3 covered the basics: .env files, python-dotenv, .gitignore, one key per environment, rotation, and the first hour after a leak. This part goes deeper on the two questions that decide real-world outcomes: where do keys actually leak? and what does each provider let you control once a key exists?
3.1 The threat model for keys#
A provider API key is a bearer credential: whoever holds it spends your money, reads your usage, and can often call every model and endpoint your project allows. The leak channels, roughly in order of frequency:
| Leak channel | How it happens | Detection difficulty |
|---|---|---|
| Git history | Key committed once, "removed" in a later commit — history keeps it forever | Easy if you scan history; invisible to working-tree scans |
| Logs and traces | Key printed in a debug log, captured in an HTTP trace, echoed in an error message, sent to an observability vendor | Hard — the key left your boundary weeks ago |
| Prompts and model context | Key pasted into a chat "to debug", stored in a prompt template, retrieved by RAG | Very hard — it's now in a corpus, caches, vector stores |
| Client bundles | Key shipped in browser JS or a mobile app — readable by anyone | Trivial for attackers; total loss |
| CI logs and artifacts | Key echoed by a build step, baked into a container layer, written to a build artifact | Medium — logs have retention; layers persist in registries |
| Screenshots and support tickets | .env visible in a screen share, terminal recording, bug report |
High — leaves your systems entirely |
| Notebooks and scratch files | .ipynb checkpoints, notes.txt, scratch dirs committed or synced |
Medium |
| Dependency or plugin config | A tool stores the key in a config file that gets committed, synced to a dotfiles repo, or backed up unencrypted | Medium |
| Core dumps and process memory | Env vars captured in a crash dump, /proc/<pid>/environ, a debugger session |
Rare but real — Part 7 covers memory hygiene |
The consequence ladder, cheapest to worst:
- Denial-of-wallet — a leaked key with no spend cap can drain your balance and any auto top-up. OpenRouter's own docs warn: "a leaked key or a runaway agent [can] spend your entire balance, including any auto top-ups" (openrouter.ai/docs/api_reference/authentication). This is OWASP LLM06:2026 Unbounded Consumption fuelled by LLM04.
- Quota and rate-limit theft — your key's rate limits are shared; an abuser can throttle your production traffic or run up usage-tier penalties.
- Data exposure — for providers with stored state (files, vector stores, fine-tunes, conversations with
store=true), a leaked project credential can reach more than completions. - Reputational abuse — the key is used for policy-violating traffic; enforcement actions (suspension, legal) land on your account.
3.2 Prevention: the controls that actually hold#
Ordered by leverage:
- Never let the key exist where it can leak. The strongest control is architectural: the secret lives in a secret manager or cloud secret store (03.1, 3.8), injected into the process environment at deploy time, never written to disk in the image, never passed through CI variables you can echo, never in a prompt, log or trace. For CI/CD specifically, OIDC workload-identity federation removes the stored secret entirely: GitHub Actions can mint a short-lived token that AWS, GCP or Azure exchanges for temporary credentials — no long-lived cloud key exists to leak (GitHub's OIDC guide; each cloud has its own setup: AWS IAM OIDC providers, Azure federated credentials, GCP Workload Identity Federation). Anthropic now prefers "identity-backed keys or Workload Identity Federation" over legacy workspace keys for the same reason (platform.claude.com/docs/en/manage-claude/authentication).
- Scope every key to the smallest thing that needs it. One key per environment and per service (03.1, 3.6), project-scoped where the provider offers it (Part 3.3), read-only or restricted permissions where the workload allows, and short expiry where supported. A leaked staging key should not be able to touch production data or spend production budget.
- Set spend limits and alerts at the provider — this is the control that caps the blast radius. Every major provider offers some form of budget cap (details in 3.3). Treat "no spend limit configured" as a launch blocker for anything with a real bill.
- Scan for secrets in three places, not one: (a) pre-commit —
gitleaks(gitleaks.io; v8.30.x as of November 2026) ordetect-secrets(PyPI, Yelp, v1.5.0) as a git hook so the key never enters history; (b) CI on every push and PR — including history scans, because deleting a key in a later commit does not remove it (git log -p,gitleaks git/trufflehog git, or GitHub's own secret scanning which scans full history on public repos for free — docs.github.com secret scanning); (c) periodic full-history sweeps —trufflehog(github.com/trufflesecurity/trufflehog, v3.99.x as of November 2026) scans git history and filesystems, Docker images, S3 buckets and more, and can verify whether a found credential is live — with the caveat that verification means the secret is sent to the provider's API to test it, so run it in a controlled environment (trufflehog docs).detect-secretsbuilds an audited baseline file in the repo — good for keyword-style catches (password = "...") that pure regex tools miss, but it scans files not history and its last release was May 2024; pair it with a history scanner rather than relying on it alone. - GitHub-side protections where you host there: enable secret scanning and push protection — push protection blocks the push when it contains a supported secret pattern, partner-pattern or custom regex (docs.github.com push protection); free for public repositories since May 2023, and available for private repos via GitHub Secret Protection. OpenRouter is a GitHub secret-scanning partner and emails you if it detects your key leaked publicly (openrouter.ai/docs/api_reference/authentication).
.gitignoreand.dockerignoreare hygiene, not security — they stop accidental commits of.env; they do nothing againstgit add -f, a force-added file, or a secret in a different filename. Layer them under scanning, never instead of it.- Never ship a key to a client. Browser and mobile apps get a backend proxy or short-lived scoped tokens instead — 03.1, 3.5 and 09.7's ephemeral tokens cover the pattern. If a key must reach a browser (realtime voice sessions), it is an ephemeral, single-session, narrowly-scoped token minted server-side — never the account key.
3.3 What each provider lets you control (as of November 2026)#
The single most useful table in this part — check each provider's console for the current state of these controls:
| Control | OpenAI | Anthropic | Google Gemini | OpenRouter |
|---|---|---|---|---|
| Key scoping | Keys live inside projects; user-owned keys carry a permission level of All / Restricted (per-resource Read/Write/None) / Read Only (assign key permissions; check the level names in your own console, since that help page is the only place they are listed); service accounts are the non-human identity that owns keys, and a key's scopes can narrow but never exceed its owner's effective permissions (api keys guide, roles and permissions) | Workspace-scoped keys; every request runs in exactly one workspace; "identity-backed keys" and Workload Identity Federation preferred over legacy workspace keys (workspaces, authentication) | Unrestricted standard keys are rejected; restrict by API (Generative Language API only) and by application (websites/IPs/apps) in the Cloud console. Since 28 May 2026, all new AI Studio keys are auth keys bound to a service account (restricted to the Gemini API by default); long-dormant unrestricted keys were blocked from 7 May 2026 (API key doc, Cloud API keys, which lists the API and application restriction types) | Per-key credit limits (limit, limit_reset of daily/weekly/monthly, include_byok_in_limit) and an optional expires_at; OpenRouter recommends a limit on every key; Management API keys for programmatic provisioning — account-level, unscoped, admin-only, cannot call completions (authentication, create key, management keys) |
| Spend/budget caps | Hard spend limits (monthly) at org and project level → 429 with organization_spend_limit_exceeded / project_spend_limit_exceeded; spend alerts without enforcement; an OpenAI-assigned monthly usage limit per tier (organization_usage_limit_exceeded); rate limits defined at org and project level (spend limits, rate limits) |
Workspace spend limits (monthly cap, lower than org) + alerts; org-level tier caps (Start $500 / Build $1,000 / Scale $200,000 monthly, per the rate-limits doc); Rate Limits API to read/set limits programmatically (workspaces, rate limits) | An experimental per-project monthly spend cap in AI Studio (Spend page; billing data lags about 10 minutes, so overshoot is possible), plus a usage-tier cap per billing account that pauses all linked projects when reached (Tier 1 $250, Tier 2 $2,000, Tier 3 $20,000 and up); Cloud Billing budgets and alerts remain the alerting layer (billing, Cloud API keys) | Guardrails per workspace: USD budget limits (daily/weekly/monthly reset; include_byok_in_budgets to count BYOK spend), model + provider allowlists, ZDR enforcement per model group, data-region restrictions (allowed_data_regions: global, europe, us; Business or Enterprise plan); assignable to the workspace default, members or individual keys, and multiple guardrails combine by intersection (guardrails) |
| Key expiry | Keys can be issued with scopes and an expiration where org/project policy allows; rotate by issuing a replacement, updating the workload, verifying, then revoking the old key (api keys guide) | Expiration presets at creation: 3 hours / 1 day / 7 days / 30 days / custom / Never (if org policy allows); expiry cannot be changed after creation (authentication) | No expiry policy is documented for Gemini keys; you can disable or delete keys, and dormant unrestricted keys are blocked (API key doc); rotate by creating a new key, deploying it, then disabling the old one | Keys accept expires_at (ISO 8601 UTC) at creation; keys created during onboarding expire after 180 days. Management key expiry is chosen in the dashboard and fixed at creation; an expired key returns 401 "API key expired". No rotation endpoint is documented: create a new key via the keys API and delete the old one (authentication, management keys) |
| Network restriction | Azure Private Link for OpenAI API (regional *.privatelink.api.openai.com endpoints; not self-service; incompatible with IP allowlist and mTLS — private link) |
IP allowlisting restricts where a key works (docs, linked from the authentication page); no private-link offering documented, so combine it with workspace scoping + ZDR agreements | Vertex AI offers Private Service Connect / Private Google Access / VPC Service Controls; the AI Studio Gemini API is public SaaS | Public SaaS; data-region routing (eu.openrouter.ai, us.openrouter.ai; enforced through the allowed_data_regions guardrail setting, which rejects requests arriving on other domains) restricts which region handles requests (guardrails) |
| Leak notification | OpenAI is a GitHub secret-scanning partner (since 2021): keys found in public-repo commits are forwarded to OpenAI, which deactivates them and alerts the owner (GitHub changelog); do not rely on it, since it covers only public commits; usage dashboards and alerts; abuse monitoring per 02.9, Part 9 | Policy-violation notifications; trust-and-safety retention flags | Cloud audit logs; fast-acting leaked-key enforcement for auth keys (leaked keys Google detects are stopped quickly) (API key doc) | GitHub secret scanning partner — emails you on detected leaks; per-key usage visible in dashboard |
Two cross-provider rules fall out:
- The free/dev tier is not the production tier. Gemini's unpaid tier trains on your data (per 02.9, 9.2 and 07.11, 2.6); OpenAI's free usage tier has a $100/month cap. Development keys and production keys should be different keys in different projects with different limits — which is also why per-environment keys (03.1, 3.6) matter for security, not just tidiness.
- Spend caps are per-provider, per-project/workspace, per-key — layer them. A project cap catches runaway internal code; a key limit catches a leaked credential; an org cap catches the apocalypse. Configure all three where offered.
3.4 Detection: knowing a key leaked before the bill arrives#
- Provider dashboards and alerts. Every provider shows usage; configure spend alerts below the hard cap so you get warning, not just the 429. Anthropic's spend-limit notifications and OpenAI's spend alerts are the pattern to copy everywhere.
- Usage anomaly alerts — the metrics side is Module 11A's observability lesson (cost per request, token anomalies); the security-specific signals: requests from unexpected regions/user-agents, calls at 3am from a key that "should" only serve EU traffic, sudden model-mix changes (a leaked key used for the most expensive model), and traffic volume an order of magnitude above baseline.
- Canary keys (honeytokens). Plant a real-format but fake credential — a "decoy" key in a
.env.example, a documentation page, a public gist you control, or a canary token from a service like Thinkst Canarytokens (verify the current free offering at canarytokens.org) — anywhere an attacker might find credentials. Any use of the canary is unambiguous proof of scanning or theft, with none of the false-positive noise of generic secret scanning. Use them in your own repos and docs; never plant them in third-party systems. - Public leak scanning. GitHub secret scanning covers your repos; for the open web, services like GitHub's public monitoring, trufflehog's
--results=verifiedmode against your org's known key formats, and provider-specific leak programmes (OpenRouter's GitHub partnership is documented above) close the loop. You cannot scan the whole internet — you can scan everywhere your keys plausibly appear: your repos, your docs site, your public examples, your CI logs' retention window. - Your own scanner. Part 9's
scan_secretsis the in-house version: run it over logs before export, over prompt/context stores, over eval datasets built from production traces, and in CI as a custom check. A secret that reaches your observability pipeline is a leak even if the provider never sees it.
3.5 The leak-response playbook#
When a key leaks — suspected or confirmed — the order matters. 03.1, 3.7 gives the first-hour version; this is the full playbook:
- Revoke or rotate first, investigate second. A leaked key is assumed compromised the moment it's exposed — every minute it stays live is billable risk. Rotate at the provider before you finish scoping the damage; most providers make rotation a one-click operation and a leaked key's remaining lifetime is pure downside. Where the provider supports it, disable the key immediately (faster than rotating, since rotation requires redeploying the new key everywhere) — Anthropic keys can be disabled/deleted in the Console; OpenAI keys can be deleted per project; OpenRouter keys can be deleted from the dashboard; Management API keys can be revoked programmatically.
- Scope the damage window. Pull usage logs for the key from first-exposure estimate to revocation: which endpoints, which models, which token volumes, which source IPs/countries, which timestamps. Map the window against your deploy history to find when the leak happened (a commit, a CI run, a screenshot). If the key had project/workspace scope, enumerate what else in that scope could have been reached (stored files, vector stores, fine-tunes — OpenAI's ZDR-eligible endpoint list is a reminder that some features store state, per 02.9, 9.2).
- Check for data exposure, not just spend. A leaked completions-only key costs money; a leaked key with file/vector-store/fine-tune access may have exposed data. Review stored-object listings, conversation histories with
store=true, and any eval/dataset features the key could reach. - Purge what you can. Delete the leaked key's artefacts where the provider allows (stored responses, files, batches). Where it doesn't, document the exposure window for your records and your users.
- Notify. Internal: security channel + incident ticket (12.10 owns incident response). External: your users if their data was reachable; your provider's abuse channel if the key was used for policy violations (some providers notify you first — OpenRouter's email, policy-violation notices); regulators only if personal data was exposed, per your legal obligations — awareness, not legal advice (12.9 covers the compliance frame).
- Post-incident. Convert the leak into permanent controls: the scanner rule that would have caught it, the CI gate, the spend limit that would have capped it, the key-scoping change that would have bounded it, and a regression test in your red-team suite (12.8) that asserts "a leaked-format key in a log line is caught". Then rotate every key that shared the blast radius — if the leaked
.envheld four keys, all four rotate.
3.6 Secret managers by name, and fetching a key at runtime#
Part 3.2 says "use a secret manager". Here are the names, what each one gives you, and a pattern for using one so the key never sits in your code, your prompt or your logs. Product names and call shapes below were checked against each vendor's documentation on 2 December 2026.
| Store | What the app calls (Python) | How the app proves who it is | Worth knowing |
|---|---|---|---|
| AWS Secrets Manager | boto3.client("secretsmanager").get_secret_value(SecretId=name)["SecretString"] |
The IAM role of the workload; the role needs the secretsmanager:GetSecretValue permission |
AWS recommends client-side caching of secret values "to improve speed and reduce costs" (it ships a Python caching component) |
| Google Cloud Secret Manager | SecretManagerServiceClient().access_secret_version(request={"name": "projects/P/secrets/S/versions/latest"}), then response.payload.data.decode("UTF-8") |
The service account or workload identity of the process | The version part of the name can be a number or the alias latest |
| Azure Key Vault | SecretClient(vault_url=..., credential=DefaultAzureCredential()).get_secret(name).value |
A managed identity when deployed (the same DefaultAzureCredential code uses your az login identity on a laptop) |
Access is controlled with Azure role-based access control; Microsoft's quickstart creates the vault with RBAC and purge protection on |
| HashiCorp Vault | hvac.Client(url=..., token=...).secrets.kv.read_secret_version(path=...)["data"]["data"] |
A Vault token obtained through one of Vault's auth methods (for example Kubernetes or cloud IAM), never a token pasted into code | The KV version 2 HTTP path is /v1/secret/data/<path>; Vault's dev server (and its dev token) is for local practice only |
All four log who read which secret, support versions and rotation, and let you grant access per workload. That audit trail is what lets you answer "who could have read this key?" after a leak (3.5).
Inject at deploy, or fetch at runtime? Both keep the key out of code. Injecting at deploy puts the value in an environment variable when the container starts, and rotation means rolling the replicas (11C.1, 4.2 and 4.3). Fetching at runtime means the process reads the store itself and can pick up a rotated key without a restart, at the price of one more dependency on the request path. A good middle path: fetch at start-up and again, once, when the provider returns 401.
Rules for the runtime fetch:
- Pass the secret's name, never its value. Config, prompts, tool arguments and traces carry
prod/llm/api-key, not the key. When an agent tool needs a credential, your code looks it up at call time; the model never sees it (12.1, 7.5). - Cache with a short lifetime, and refetch on
401. A cache stops you hitting the store on every request (and its rate limits and bill). A refetch on401handles rotation without a deploy. - Mask by default. Wrap the value in a type whose
reprandstrprint stars, so an accidentalprint(key)orlog.info(config)cannot leak it. Unwrap only at the call. - Read-only, per-service access. The service gets permission to read its own secret, not to list or write the store. A leaked process then exposes one key, not the vault.
- Scan what leaves the process. Logs, traces and eval datasets still get the scanner from Part 9 (9,
scan_secrets).
Try it: a fake secret store, runtime fetch, rotation and a leak check. This module (standard library only, no key, no network) shows the pattern end to end. FakeSecretStore stands in for any of the four stores above: it keeps versions and an audit log. CachedSecret fetches once, caches, and refetches on demand. FakeProvider accepts exactly one valid key, so we can rotate it under the app. The two keys are demo strings built inside the script; no real credential is involved.
# fetch_secret_at_runtime.py (stdlib only, no keys, no network)
"""Fetch a provider key from a secret store at call time. No key in code, prompt or logs.
FakeSecretStore stands in for AWS Secrets Manager, Google Cloud Secret Manager,
Azure Key Vault or HashiCorp Vault. Swap it for a real client with the same get() shape.
"""
import time
class Secret:
"""Holds a secret value; printing or logging it shows only stars."""
__slots__ = ("_v",)
def __init__(self, value: str):
self._v = value
def reveal(self) -> str: # call this only at the point of use
return self._v
def __repr__(self):
return "Secret(***)"
__str__ = __repr__
class FakeSecretStore:
"""In-memory store with versions and an access log (what a real store's audit log gives you)."""
def __init__(self):
self._versions: dict[str, list[str]] = {}
self.audit: list[str] = []
def put(self, name: str, value: str) -> int:
self._versions.setdefault(name, []).append(value)
return len(self._versions[name])
def get(self, name: str, version: str = "latest") -> Secret:
versions = self._versions[name] # KeyError = not found, like a real store
value = versions[-1] if version == "latest" else versions[int(version) - 1]
self.audit.append(f"GET {name} version={len(versions) if version == 'latest' else version}")
return Secret(value)
class CachedSecret:
"""Fetch on first use, cache for ttl seconds, refetch on demand (rotation)."""
def __init__(self, store, name: str, ttl: float = 300.0, clock=time.monotonic):
self.store, self.name, self.ttl, self.clock = store, name, ttl, clock
self._secret, self._at = None, 0.0
def get(self) -> Secret:
if self._secret is None or self.clock() - self._at > self.ttl:
self.refresh()
return self._secret
def refresh(self) -> None:
self._secret, self._at = self.store.get(self.name), self.clock()
class FakeProvider:
"""Pretends to be an LLM API that accepts exactly one current key."""
def __init__(self, valid_key: str):
self.valid_key = valid_key
self.seen_prompts: list[str] = []
def chat(self, headers: dict, prompt: str) -> tuple[int, str]:
self.seen_prompts.append(prompt)
if headers.get("Authorization") != f"Bearer {self.valid_key}":
return 401, "invalid api key"
return 200, "ok"
def call_model(secret: CachedSecret, provider: FakeProvider, prompt: str, log: list) -> tuple[int, str]:
"""The key is read here, at the point of use, and never stored in a variable that outlives the call."""
for attempt in (1, 2):
headers = {"Authorization": f"Bearer {secret.get().reveal()}"}
status, body = provider.chat(headers, prompt)
log.append(f"attempt={attempt} status={status} key={secret.get()!r}") # log the masked form
if status != 401:
return status, body
secret.refresh() # key rotated under us: fetch the new version once, retry once
return status, body
if __name__ == "__main__":
OLD, NEW = "sk-demo-OLD-3f9a71c2", "sk-demo-NEW-b84e02d6" # fake keys, built here for the demo only
store = FakeSecretStore()
store.put("prod/llm/api-key", OLD) # an operator does this, not the app
provider = FakeProvider(OLD)
key = CachedSecret(store, "prod/llm/api-key", ttl=300)
log: list[str] = []
prompt = "You are the Acme Bikes assistant. Summarise this order." # no key in the prompt
print("1. normal call:", call_model(key, provider, prompt, log))
print("2. cached call:", call_model(key, provider, prompt, log), "| store reads so far:", len(store.audit))
store.put("prod/llm/api-key", NEW) # rotation: new version in the store
provider.valid_key = NEW # provider revokes the old key
print("3. after rotation:", call_model(key, provider, prompt, log))
print("\nlog lines:")
for line in log:
print(" ", line)
print("store audit log:")
for line in store.audit:
print(" ", line)
everything = "\n".join(log + store.audit + provider.seen_prompts + [repr(key.get()), str(key.get())])
leaked = [k for k in (OLD, NEW) if k in everything]
print("\nkey text found in logs, audit log or prompts:", leaked or "none")
assert not leakedRun it:
python3 fetch_secret_at_runtime.pyReal output:
1. normal call: (200, 'ok')
2. cached call: (200, 'ok') | store reads so far: 1
3. after rotation: (200, 'ok')
log lines:
attempt=1 status=200 key=Secret(***)
attempt=1 status=200 key=Secret(***)
attempt=1 status=401 key=Secret(***)
attempt=2 status=200 key=Secret(***)
store audit log:
GET prod/llm/api-key version=1
GET prod/llm/api-key version=2
key text found in logs, audit log or prompts: noneRead it line by line: the second call reads from the cache (one store read so far); after the rotation the first attempt gets 401, the code refetches version 2 and the retry succeeds; the log shows Secret(***) every time; and the final check finds neither key anywhere it should not be.
What the real SDK calls look like (illustrative, not run: they need a cloud account, an identity and a stored secret). Swap one of these in for FakeSecretStore.get. Install the package names without version pins: boto3, google-cloud-secret-manager, azure-identity with azure-keyvault-secrets, or hvac.
# AWS Secrets Manager (needs secretsmanager:GetSecretValue on the secret)
import boto3
value = boto3.client("secretsmanager").get_secret_value(SecretId="prod/llm/api-key")["SecretString"]
# Google Cloud Secret Manager (needs the Secret Manager Secret Accessor role)
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
name = "projects/my-project/secrets/llm-api-key/versions/latest"
value = client.access_secret_version(request={"name": name}).payload.data.decode("UTF-8")
# Azure Key Vault (needs a role such as Key Vault Secrets User on the vault)
import os
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
vault = SecretClient(vault_url=f"https://{os.environ['KEY_VAULT_NAME']}.vault.azure.net",
credential=DefaultAzureCredential())
value = vault.get_secret("llm-api-key").value
# HashiCorp Vault, KV version 2 (token comes from a Vault auth method, not from code)
import hvac
vault = hvac.Client(url=os.environ["VAULT_ADDR"]) # plus an auth step such as Kubernetes auth
value = vault.secrets.kv.read_secret_version(path="llm/api-key")["data"]["data"]["api_key"]The permission names in the comments (Secret Manager Secret Accessor, Key Vault Secrets User) are the built-in roles' usual names; confirm them in your cloud's console before relying on them (unverified as of 2026-12-02). Whatever you choose, the application code after the fetch is identical: OpenAI(api_key=value) or Anthropic(api_key=value), with value unwrapped at the last moment. The provider-side controls (scoping, expiry, spend limits) are 3.3.
Part 4: The model supply chain#
So far the chains were data and credentials. The third is the model itself: weights, adapters, tokenizers, model cards, hosted endpoints and the hub you download them from. Unlike a PyPI package, a model file is not just code — it is a program in a data format, and the format determines whether "loading it" means "reading numbers" or "executing arbitrary Python".
4.1 File formats decide your risk#
| Format | What loading it does | Risk profile |
|---|---|---|
safetensors |
Memory-maps tensors; the format was designed specifically to prevent arbitrary code execution (HF security docs) | Data only — the safe default. Still verify provenance; a safetensors file can contain a backdoored model, just not code |
Pickle-based weights (pytorch_model.bin, .pkl, Keras .h5 Lambda layers) |
pickle.load executes embedded __reduce__ calls — arbitrary Python at load time (HF pickle-scanning docs) |
Code execution on your host the moment you load it. Python's own docs warn about this; the ML community ignored it for years |
| GGUF / quantized formats (llama.cpp, Ollama) | Custom binary parsers; no Python pickle, but parser bugs are memory-corruption surface | Lower than pickle, not zero — pin versions, prefer reputable quantizers |
| ONNX | Graph + weights; onnxruntime executes operators, custom ops can load external code |
Middle — audit custom ops, pin runtime version |
| Adapter weights (LoRA, PEFT, delta files) | Usually safetensors/npz — safe formats — but merged into a base model they change behaviour | Low format risk; the behavioural risk is a backdoored adapter — same provenance problem as full weights |
Remote code (trust_remote_code=True, auto_map, custom architectures) |
Downloads and executes Python from the repo — model code you never reviewed | Highest — treat as "running a stranger's package with your credentials in env" |
The Hugging Face transformers library makes the safe path explicit: it "heavily recommends" safetensors and provides use_safetensors=True, which errors if no safetensors file is present rather than silently falling back to pickle. For trust_remote_code, its security policy says to "always verify the content of the model's Python files" and "set a revision" so repo updates can't swap the code under you (github.com/huggingface/transformers/security). Text Generation Inference went further: since TGI 2.0, pickle-based models are not auto-converted unless --trust-remote-code/TRUST_REMOTE_CODE=true is set — the flag doubles as "I accept this model's code runs" (HF TGI safety docs).
4.2 Provenance: knowing what you downloaded#
"A model from Hugging Face" is not a provenance statement — the Hub hosts millions of public repos, most unvetted. The controls that turn a download into a decision:
- Pin a revision. HF repos are git repos;
revision="<commit-sha>"(or a tag) freezes exactly what you got. An unpinned"username/model"silently tracksmain— the author can push new weights tomorrow and your "same" model changes behaviour (transformers security policy recommends pinning fortrust_remote_code; the same discipline applies to weights). - Record content hashes. Hash every file you download (
sha256) into your model manifest alongside name, revision, source URL, licence and scan verdict — the same content-hash discipline as 04.10 and 05.8 lineage. If a "new version" appears with different weights, the hash tells you before the eval does. - Verify signatures where a publisher offers them — they answer a different question than hashes. A hash proves integrity: the artefact is byte-identical to what you recorded. A signature proves origin: a specific identity produced it, and it still holds if you obtained the file through a mirror or a re-upload. The ecosystem is converging on this: OpenSSF Model Signing (OMS) is an implementation-agnostic spec that signs a whole model bundle — weights, config, tokenizer — as one manifest of file hashes under a single signature, carried in the Sigstore bundle format (OpenSSF OMS introduction); Sigstore's
model-signingtooling implements it with keyless signing (model_signing sign/model_signing verify, developed with OpenSSF, NVIDIA and HiddenLayer — sigstore/model-transparency); and signed-model registries exist (NVIDIA NGC ships OMS-signed models — NVIDIA technical blog). The honest caveat: most public Hub repos are unsigned today — signature verification is a real control for the growing set of publishers that sign, not a universal one. Where it is offered, verify the signature in addition to the hash: a self-computed hash only proves the file hasn't changed since you hashed it; a signature tells you who hashed it. - Prefer verified sources. HF verified organisations, official vendor repos (
meta-llama,mistralai,google), and mirrors you control. Azure's Foundry/ML eligibility rules are a good template for your own policy: safetensors format required,trust_remote_code/custom_codedisallowed unless explicitly verified, mandatory malware scanning (ClamAV + Protect AI + JFrog) before import (HF Azure security docs). - Check the licence as a security property. A model card's licence determines whether you can self-host, fine-tune, serve to customers, or must delete on request — 02.9, Part 9 covers the landscape; the supply-chain view adds: licence terms are part of the provenance record, reviewed at adoption, not discovered at audit time.
- Model cards are claims, not audits. A card says what the author claims — benchmarks, intended use, training data hints. It is marketing until independently evaluated. Module 10A owns evaluation; the security rule is "no model enters production on a card alone" — minimum bar: your own smoke eval + the safety evals from 12.8.
4.3 Malicious models are a documented, recurring incident class#
This is not theoretical. The public record as of November 2026:
- JFrog found ~100 malicious models on Hugging Face (research published 27 February 2024 — JFrog's own write-up — with press coverage in March 2024: BleepingComputer, Dark Reading, Ars Technica): PyTorch/Keras files embedding
pickle.__reduce__payloads — arbitrary code execution on load, reverse shells, credential theft. A useful calibration detail: of the ~100 flagged submissions, JFrog judged only about 10 truly malicious — most of the rest appeared to be benign proofs of concept from researchers probing the same risks. "Flagged by a scanner" means capable of harm, not necessarily intending it — which is exactly why your own scanning plus provenance review, not the hub's flag alone, is the control. - ReversingLabs' "nullifAI" (February 2025, press release): corrupt pickle files engineered to evade Hugging Face's own detection while still executing — proof that hub scanning is necessary but not sufficient.
- HiddenLayer's "Silent Sabotage" demonstrated a supply-chain attack on the ecosystem tooling: compromise the safetensors-conversion space/bot and you can ship malicious pull requests impersonating Hugging Face's own conversion bot to any repo — including stealing the victim's HF token (hiddenlayer.com/research/silent-sabotage). Lesson: the tools you use to harden the pipeline are themselves supply-chain surface.
- Hub-side defences exist and are improving: HF runs pickle scanning on uploads (the "vetting" list of imports on model pages), partners with JFrog for model scanning (security-jfrog docs), and displays dangerous-opcode findings — but it does not block uploads, so the burden still lands on the downloader.
The defensive stack for model adoption:
- Never
pickle.load/torch.loaduntrusted weights.torch.loadhas defaulted toweights_only=Truesince PyTorch 2.6 — a safe mode that refuses arbitrary classes — but code that explicitly passesweights_only=False, or reaches forpickle.loaddirectly, still executes on load; when in doubt, convert via safetensors. In untrusted contexts, treat any pickle-family file as hostile input, exactly like a document in your RAG corpus. - Scan before load.
modelscan(PyPI, ProtectAI, Apache-2.0, v0.8.8) scans model files across formats (H5, pickle, ONNX, TensorFlow, etc.);picklescan(PyPI, v1.0.5) specialises in pickle opcodes and can scan HF repos directly (picklescan --huggingface org/model); HF's own hub scanning gives a first-pass vetting view. Run scanners in CI on every model added to your registry — Part 9'sinspect_pickleis the minimal local version. - Load in isolation. Model files that must use pickle (legacy weights, exotic formats) get loaded in a sandboxed worker — no credentials in env, no network egress, read-only filesystem, resource limits — the same sandboxing discipline as untrusted code execution in 08A.15. The model produces tensors; it does not need your secrets.
trust_remote_codeis a policy decision, not a flag. DefaultFalse. WhenTrueis genuinely required (a new architecture), require: verified author org, pinned revision, code review of theauto_mapconfiguration and the custom-architecture Python files it points to (they are plain Python — read them), and the isolated-load treatment anyway. Count how many production models you actually need it for — the honest answer is usually zero.- Watch the conversion/serving path. The HiddenLayer attack targeted the conversion service, not the weights. If you run conversion, quantisation or serving tooling (llama.cpp, TGI, vLLM, Ollama, text-generation-webui), pin versions, scan the tooling itself, and treat auto-updating model-serving daemons as supply-chain surface — an Ollama
ollama pullof a poisoned GGUF is the same risk class.
4.4 Weights can be backdoored without any code at all#
Even a perfectly safe format can carry a backdoored model: weights trained or fine-tuned to behave differently on trigger inputs. The canonical research demonstration is Anthropic's "Sleeper Agents" (Hubinger et al., January 2024, arXiv:2401.05566): models trained to write secure code normally but insert vulnerabilities when a trigger condition holds — and the deception persisted through supervised fine-tuning, RL and adversarial training, was more persistent in larger models and chain-of-thought models, and adversarial training could teach the model to hide the trigger better rather than remove it.
What this means operationally:
- Backdoor risk scales with provenance distance. A model you trained yourself on data you control: low. A fine-tune from a community adapter on a base model you vetted: moderate. A random Hub checkpoint: unquantified. There is no scanner that reliably detects weight-level backdoors — your defences are provenance, isolation and behavioural testing.
- Behavioural evals are the backdoor detector. 12.8 owns red-teaming; the model-supply-chain rule is: any third-party model gets a behavioural smoke suite before production — canary prompts, refusal checks, instruction-hierarchy probes, output-distribution sanity. A backdoor that fires on a trigger you didn't test survives; one that fires on common inputs gets caught by ordinary evals.
- Dataset provenance propagates to weights. A model fine-tuned on poisoned data inherits the poison — which loops back to Part 2: your RAG corpus and your training corpora are the same threat class. Data-poisoning defences (trust tiers, quarantine, provenance) apply to training data with higher stakes, because a poisoned weight is far harder to roll back than a poisoned document.
- Sleeper-agent persistence is a warning about your own safety claims. If deception can survive safety training in research models, "the provider safety-tuned it" is a claim to verify behaviourally, not assume. This is why 12.8 exists.
Part 5: The software supply chain#
Deep-dive
Your pyproject.toml is a list of strangers' code that will run inside your process, often with your secrets in os.environ. The AI stack makes this worse than a typical web app: agent frameworks pull MCP-server ecosystems, model-serving libraries pull native binaries, and LLM-generated code recommends packages that don't exist — which attackers then register. This part covers the attack taxonomy and the controls that bound it.
5.1 The attack taxonomy#
| Attack | Mechanism | AI-specific twist |
|---|---|---|
| Typosquatting | Register reqeusts, openai-python lookalikes on PyPI/npm |
Same as classic — but LLMs generate the typo'd name in code suggestions, giving the squatter free distribution |
| Dependency confusion | Publish a public package whose name matches your private/internal package; resolvers prefer the public one | Private ML tooling names (acme-llm-utils) leak via lockfiles, docs, job posts |
| Compromised maintainer / account takeover | Hijack a maintainer's PyPI/npm account or CI, ship a malicious release | The LiteLLM incident (below) is the canonical 2026 case |
| Malicious release / protestware | Legitimate maintainer ships a wiper or data-stealer in a routine update | Auto-updating bots (Renovate/Dependabot auto-merge) turn "release" into "production" in minutes |
| Transitive dependency risk | You depend on langchain → 200 sub-deps; one is compromised |
Agent frameworks have the deepest trees in the ecosystem |
| Slopsquatting / package hallucination | LLM invents a plausible package name (import vectorstore-utils); attacker registers it on PyPI before your CI does |
The AI-native attack — see below |
| Model/prompt/config supply chain | Poisoned requirements, hijacked model repos, tampered prompt libraries, malicious MCP servers/plugins |
Covered in Parts 4 and 12.6 |
| CI/CD compromise | Poisoned GitHub Action tag, stolen GITHUB_TOKEN, pull_request_target abuse, OIDC misconfiguration |
Your pipeline is production — see 5.3 |
The LiteLLM incident (March 2026) is the reference case for "trusted AI library turns malicious": versions 1.82.7 and 1.82.8 of the litellm PyPI package carried the same credential stealer — but delivered two different ways. 1.82.8 added a litellm_init.pth file that executed at every Python interpreter start; 1.82.7 embedded the identical payload as a base64 blob inside litellm/proxy/proxy_server.py, so it ran when the proxy module was imported or the proxy server started (StepSecurity's analysis; LiteLLM security update; 03.11, 13.2 and 13B.2 cover the full timeline and the rotate-everything aftermath). How long the packages were live is reported inconsistently: an early LiteLLM advisory said about 40 minutes, while Snyk's reconstruction from publish timestamps puts 1.82.7 at 10:39 UTC and 1.82.8 at 10:52 UTC on 24 March, with PyPI quarantine at about 13:38 UTC — roughly three hours (Snyk). Plan around the longer window: anyone who installed or rebuilt in it should assume exposure. 1.82.6 was the last clean release and 1.83.0 the first verified clean. Three lessons generalise: (a) .pth files, module-level payloads and install-time hooks mean "installing — or even just importing — the package" can be the payload; (b) the blast radius is every env var — which is why scoped, short-lived credentials (Part 3) limit damage; (c) version pinning + hashes would have contained it to whoever installed in that window — unpinned litellm>=1.82.6 auto-resolved into the malicious release.
How the March release was reached, and why it matters for your pipeline. Snyk's analysis reports that the attacker did not break PyPI: the PYPI_PUBLISH token was read out of LiteLLM's own CI runner by a compromised copy of the Trivy security-scanner GitHub Action, which the build installed without a pinned version (Snyk). The Trivy compromise itself is separately documented — Aqua Security disclosed on 20 March 2026 that a misconfigured workflow let an attacker steal CI secrets and rewrite trusted tags (tracked as CVE-2026-33634; see Wiz's write-up); the link from Trivy to LiteLLM's publishing credential is a belief rather than a proven chain: LiteLLM's own security update says "We believe that the compromise originated from the Trivy dependency used in our CI/CD security scanning workflow" (and that stolen credentials were "reportedly" used on its publishing pipeline), while Snyk's reconstruction names the PYPI_PUBLISH token specifically, which LiteLLM's post does not (page read 9 November 2026). LiteLLM's post also says the packages were live for "about 40 minutes" while its impact guidance uses a wider 10:39 to 16:00 UTC window. Either way, the pattern is the lesson: a security tool in your CI is itself a dependency with access to your secrets, so pin it by commit SHA and give the job that runs it no publish credentials (Part 5.3).
LiteLLM again (October 2026): provenance is not trust. On 21 October 2026 litellm 1.107.0 was published to PyPI and to Docker Hub and GHCR (tags v1.107.0, latest, main-latest, main-stable) with a credential stealer delivered through a cook.pth file — again a .pth, so it runs on every Python start whether or not LiteLLM is imported. Exposure was short but not zero: The Hacker News quotes LiteLLM's window as 11:39 to 13:23 UTC on PyPI (about 1 hour 44 minutes) and 11:46 to 14:20 UTC for the Docker tags (about 2 hours 34 minutes), Datadog gives PyPI quarantine at 13:20 UTC and Docker removal at 13:53 UTC and calls it "approximately two hours", and LiteLLM says the release was removed within 3 hours (compare March's roughly three hours, above). Datadog names 1.106.2 as the last safe release; the later 1.106.x and 1.108.x releases on PyPI are separate builds, not named as affected in either report (Datadog Security Labs; The Hacker News). LiteLLM's account of the root cause: stolen developer GitHub CLI tokens were used to run the project's legitimate release workflow against a lookalike repository, so the resulting artefacts carried genuine-looking build provenance that pointed at the wrong source. Researchers noted no established link to the March incident. Two lessons that the March case did not teach: (a) a signature or provenance attestation answers "which pipeline built this, from which source?" — it does not answer "is that source one I trust?", so verify the expected repository and workflow identity, not merely that an attestation exists; (b) developer CLI tokens (gh, cloud CLIs, and anything an AI coding agent can read) are high-value secrets and belong under the same scoping and rotation rules as production keys (Part 3.2). Cleanup advice from the reports is to delete the stray .pth and sitecustomize.py files, because uninstalling the package alone does not remove them, and to rotate every credential reachable from the host. Both incidents are the same class: install-time code execution through a trusted package name. The same class reaches developer machines through the npm ecosystem too — 12.6 §6.1 covers the August 2025 Nx "s1ngularity" compromise, whose post-install script went after credentials and AI coding tools.
Slopsquatting is the attack that only exists because of LLMs. Spracklen et al. (USENIX Security 2025, arXiv:2406.10279) generated 576,000 code samples across 16 code-generating models and found 19.7% of recommended packages were hallucinated — names that don't exist on PyPI/npm — including 205,474 unique hallucinated names. The attack: register the hallucinated name first; the next developer who pastes the LLM's pip install bogus-vector-db gets your malware. The 2026 follow-up (arXiv:2605.17062) found frontier models dropped to ~4.6–6.1% but still invent names — and 127 package names that all five tested models hallucinate identically, 53 of which remained registrable after disclosure. Defences: never paste-install an LLM's package suggestion without checking it exists and is maintained; prefer packages already in your approved list; treat "the model suggested it" as zero trust evidence.
5.2 The defence stack#
Ordered from "do this today" to "mature programme":
-
Minimal dependency surface. 03.11, 13.2 already teaches this for SDK wrappers — it applies tenfold to agent frameworks. Every dependency is attack surface and supply-chain exposure: prefer stdlib and well-maintained libs, vendor small utilities rather than depend on them, and delete unused deps. If you don't need LangChain, don't carry its tree.
-
Lockfiles with hashes — non-negotiable. Pin exact versions and verify content hashes at install:
uv:uv.lockrecords a SHA-256 for every distribution's sdist and wheels by default and verifies them at install;uv pip compile --generate-hashesproduces a hashedrequirements.txt;uv pip install --require-hashesrefuses unhashed requirements;uv export --lockedemits the locked set for deployment (uv locking docs, uv lockfile internals).pip-tools:pip-compile --generate-hashes requirements.in→ install withpip install --require-hashes -r requirements.txt. Hashes detect tampering — a re-published package under the same version fails the hash check even if the version number didn't change.- Hash pinning does not prove a package is safe — it proves it's the same artefact you vetted. A compromised release gets hashed too; that's what scanning + review cadence are for.
-
Dependency cooldown — don't be the first to install a release. Both LiteLLM compromises were live for hours, and most malicious uploads are pulled quickly once someone notices. A cooldown (a "minimum release age") tells your resolver to ignore any release newer than N days, so a fresh malicious version has time to be found and yanked before you can resolve to it. The knobs, as of November 2026: uv —
exclude-newer = "1 week"under[tool.uv]inpyproject.toml(friendly or ISO 8601 durations such as"7 days"orP7D; months and years are rejected;exclude-newer-package = { setuptools = "30 days" }overrides one package; the calculated timestamp is written intouv.lock) (uv resolution docs); pip —--uploaded-prior-towith an ISO datetime orP3D-style days (PIP_UPLOADED_PRIOR_TO; needs an index that publishes upload times) (pip install docs); Dependabot —cooldownwithdefault-daysand per-semver-level days (version updates wait three days by default; security updates are not delayed) (options reference); Renovate —minimumReleaseAge(docs). A week is the commonly suggested starting point; use shorter for security patches (exempt that one package) and longer for production images. Limits, so you don't oversell it: it identifies nothing malicious (it only buys time for others to), an exact pin bypasses it, it does nothing about a package you already run, and it depends on the index exposing upload timestamps (pydevtools: what is a dependency cooldown). Pair it with hashes: the cooldown narrows which version you take, the hash proves you got that artefact. -
Vulnerability scanning in CI.
pip-audit(PyPI, v2.10.1) audits environments and requirements against the PyPA advisory DB + OSV, supports--fix, emits CycloneDX SBOMs;osv-scanner(github.com/google/osv-scanner, v2.7.0) scans lockfiles, SBOMs and container images against OSV.dev. Run both on every PR that touches dependencies; Dependabot/Renovate alerts + security-update PRs keep the cadence honest. Alerts are findings, not noise — an unpatched CVE in a transitive dep is a decision to make explicitly, not discover in an incident. -
Dependency review. For every new/changed dependency: who maintains it, when was the last release, how many downloads, does it need native builds, what does its install do (
pip installrunssetup.py— arbitrary code at install time). GitHub's dependency-review action and Dependabot alerts automate part of this; the human check is "would I bet my infra on this maintainer's next release?" -
SBOM — know what you ship. A Software Bill of Materials inventories every component so you can answer "are we affected?" when the next LiteLLM happens. Generate CycloneDX or SPDX SBOMs in CI (
pip-auditemits CycloneDX;syft/trivyfor images). For AI systems specifically, the BOM concept extends to models and datasets: CycloneDX ML-BOM represents models asmachine-learning-modelcomponents with amodelCard(parameters, datasets, metrics, considerations) and data components (cyclonedx.org/capabilities/mlbom); SPDX 3.0 adds formal AI and Dataset profiles withAIPackage/DatasetPackageclasses covering model type, training info, limitations, bias, data provenance (spdxai.github.io/profiles). CycloneDX 1.7 (October 2025) is also standardised as Ecma-424, and the SPDX 3.0.1 AI profile is the richer of the two on AI-specific fields (explainability, energy, safety-risk) while CycloneDX has the stronger tooling today, per a May 2026 NIST presentation (NIST CSRC, The evolving BOM ecosystem; CycloneDX 1.7 announcement). Pick whichever matches the SBOM pipeline you already run rather than running both. You don't need to produce an AI-BOM on day one — but know the formats exist and what they capture, because customers and regulators increasingly ask. -
Container and image scanning + signing. Scan images for OS + library CVEs (
trivy,grype) in CI; sign images with Sigstore/cosign (docs.sigstore.dev) so deploys can verify provenance —cosign verifychecks the signature and the identity that signed it. GitHub Artifact Attestations give you signed SLSA build provenance (and signed SBOM attestations) for anything built in Actions: public repositories use the Sigstore public-good instance and a public transparency log, private repositories use GitHub's own Sigstore instance without one, and consumers check them withgh attestation verify(GitHub docs; Sigstore blog on attestations). GitHub's own caveat applies: attestations on their own meet SLSA v1.0 Build Level 2, and they link an artefact to its source and build instructions — they do not prove it is secure, and (as the October 2026 LiteLLM case showed) they are only as trustworthy as the repository you decide to accept. Write a verification policy (expected repository, workflow and branch), not just "has an attestation". Deploy only signed, scanned images that match that policy. -
Reproducible-ish builds. Pin base images by digest (
image@sha256:...), pin GitHub Actions to full commit SHAs (not mutable tags), and prefer lockfile-driven builds over "latest" resolution. On the publishing side, PyPI Trusted Publishing (short-lived OIDC identity instead of a long-lived upload token — the kind of long-lived upload token reportedly stolen in the March incident) and digital attestations (PEP 740) let a project prove which CI workflow published a release; PyPI supports GitHub Actions, GitLab CI/CD and Google Cloud as Trusted Publishers (PyPI attestations docs). If you publish your own package, use it; if you consume packages, treat a present attestation as a positive signal about where a file was built, never as a verdict on safety. SLSA (Supply-chain Levels for Software Artifacts, OpenSSF, v1.2) formalises this into levels — build provenance, hermetic builds, verified source — worth knowing as the vocabulary buyers and auditors use (SLSA overview; NIST's SSDF SP 800-218 v1.1 is the complementary practice framework, and SP 800-218A is its GenAI community profile — NIST CSRC). -
MCP servers, plugins and agent frameworks get the same review as packages. An MCP server is a dependency that also exposes tools — 12.6 owns the agent-facing threat model; the supply-chain rule is: vet the server's package provenance, pin its version, check its permissions and its code before installing. A typosquatted MCP server is a remote-code-execution package with a friendly name.
-
The "would a lockfile have helped?" test. For every dependency incident you read about, ask: did they pin? hash? scan? The LiteLLM victims who ran
litellm==1.82.6or had hash verification lost nothing; the ones onlitellm>=1.82.6unpinned absorbed the stealer. Your controls are the difference between "an incident" and "a headline".
5.3 CI/CD is part of the supply chain#
Your pipeline produces the artefact everyone runs — compromise it and every defence downstream is moot:
- Pin GitHub Actions to full commit SHAs, not tags — tags are mutable; a hijacked action tag is a supply-chain attack on everyone using it (GitHub security hardening). Add a comment with the version for humans.
- Least-privilege
permissionsat job level, not workflow level — each job declares only what it needs; new jobs default to no permissions rather than inherited write access (GitHub Actions security). pull_request_targetandworkflow_runare dangerous-by-default: they run with base-repo secrets and write tokens — never check out untrusted PR code in them. GitHub will begin enforcing a default policy blockingpull_request_targetevents in public repositories on 2 December 2026 (private and internal repositories and GitHub Enterprise Server are not affected). The change was announced on 2 November 2026, after enforcement had earlier been scheduled for 2 November; the rule runs in evaluate mode until then, with two two-hour brownout windows (9 and 16 November 2026, 16:00–18:00 UTC) in which blocked runs fail with an error annotation, and Insights shows which of your runs it would block (GitHub changelog; securely using pull_request_target) — a sign the risk is now recognised as systemic (the Trivy compromise behind the March LiteLLM chain began with apull_request_target"pwn request", per Snyk). If a workflow genuinely needs the trigger, you can allow it explicitly through an Actions event policy; the safer design is to split it into an unprivilegedpull_requestjob that builds and a separate privileged job that only consumes its output as data.- OIDC instead of stored cloud secrets — Part 3.2 covers the mechanism; in CI specifically it means the pipeline holds no long-lived AWS/GCP/Azure key to steal.
- Separate build from deploy, and gate deploys on scan results — a red
pip-auditor image scan should fail the pipeline, not annotate it. 11C.2, 4.3 has the full release-workflow pattern this plugs into. - Protect your own repo: branch protection, required reviews, signed commits awareness, Dependabot security updates enabled, secret scanning + push protection (Part 3.2).
Part 6: Vendor risk for hosted providers#
Deep-dive
Every hosted LLM call is a supply-chain dependency: you are consuming their model, their infrastructure and their data-handling practices. 02.9, Part 9 covers the privacy/compliance landscape and 07.11, 2.6 the "what providers do with your data" table — this part is the vendor-risk-management frame: how to evaluate, contract and de-risk a provider relationship.
6.1 The vendor security review checklist#
Before sending production data to any provider (or gateway — 03.11, 1.4 covers the gateway adds-a-party problem):
- Security certifications: SOC 2 Type II, ISO 27001, and for AI specifically ISO/IEC 42001 (AI management systems) — ask for the report, not the badge. Recency matters; a 2022 SOC 2 says little about 2026 controls.
- Data handling terms in writing: retention period, training-use policy per tier (free vs paid vs enterprise/ZDR), subprocessors list, data-residency options, deletion semantics on account close. 07.11, 2.6 has the per-provider defaults table; verify against current terms — they change.
- Incident history and transparency: have they had breaches? Do they publish security bulletins? A provider with a public incident postmortem practice is easier to trust than one with a spotless-but-unverifiable record.
- Bug bounty / disclosure programme: exists? scope? payout history? Signals security maturity.
- Abuse and enforcement track record: how do they handle policy violations — do they notify you, suspend you, or silently filter? Relevant both for your compliance and for understanding what your users experience.
- API security posture: scoped keys (Part 3.3), spend controls, audit logs you can actually pull, SSO/RBAC for your org, IP allowlisting where offered, mTLS where offered.
- Exit cost: how portable is your integration? Can you swap providers without rewriting prompts, retrievers and evals? (This is 03.11's whole argument — the abstraction is also your exit strategy.)
6.2 The data-handling chain#
Your data touches more parties than the provider's name suggests:
your app → [gateway?] → provider API → provider's subprocessors
↓ ↓
logging/telemetry model training? (per tier)
vendors human review? (per policy)Each arrow is a data-flow decision:
- Gateways and routers add a party. OpenRouter, LiteLLM proxy, Portkey, Helicone etc. sit in the request path — they see prompts and completions. That may be fine (that's what you pay for) but it must be a conscious decision: the gateway's own data policy, its subprocessors, its retention, and whether it offers ZDR passthrough. 03.11, 1.4 and 02.9, Part 9 cover this; the supply-chain rule: a gateway is a vendor too — review it like one.
- "We don't train on your data" has asterisks. Free tiers, abuse-monitoring retention, safety-review queues and ZDR-eligible-vs-default endpoints differ per provider and per endpoint — OpenAI's own docs list which endpoints are ZDR-eligible and which aren't. The contract you want is per-endpoint, in writing, for the exact API paths you call.
- Subprocessors are your subprocessors. Your vendor's subprocessors (cloud hosts, safety vendors, annotation workforces for training data) inherit your data. Ask for the list; check it against your own compliance obligations (12.9 owns the regulatory frame).
- Human review happens. Provider safety teams may review flagged traffic — know the policy, because "your data" includes whatever a reviewer sees. ZDR arrangements exist precisely to bound this.
6.3 API security beyond the key#
The key is one control; the API surface has more:
- TLS everywhere, always — and verify you're not silently downgraded by a misconfigured proxy. Certificate pinning is rarely worth it for API clients; correct CA validation is.
- Webhook/callback verification — if the provider calls you (batch jobs, fine-tune completion, realtime events), verify signatures exactly as you'd verify any webhook (standard practice); an unverified callback endpoint is an injection path.
- Per-key usage audit — pull the provider's usage logs periodically and reconcile against your own telemetry; unexplained usage is either a leak (Part 3) or a bug billing you twice.
- Region and data-residency controls — OpenRouter's
eu/us/globaldata-region routing (guardrails), Vertex's regional endpoints, Azure OpenAI's regional deployments — use them where residency is a requirement, and verify the fallback behaviour (does an EU request ever route globally?).
6.4 Exit strategy: the supply-chain hedge#
Vendor risk is ultimately concentration risk. The hedge is architectural, and 03.11 already builds it; 11C.3 owns the runtime mechanics — fallback chains, gateways and multi-provider failover:
- Abstract the provider behind your own client interface — the lesson's whole point. Prompts, retrieval, evals and guardrails stay provider-agnostic; only the thin SDK layer changes on a swap.
- Keep an approved-provider list, not a single provider. Two providers per critical workload means a breach, deprecation, price change or geopolitical event at one isn't an outage. OpenRouter exists partly to solve exactly this — one API, many providers, per-key guardrails.
- Export what you can. Conversation logs, fine-tune data, vector indexes, prompt libraries — your data in their formats is leverage you lose on exit. Export regularly; the exit plan is a runbook, not a hope.
- Contract the exit. Data export format, deletion certification, transition assistance — get it in the DPA/MSA before you need it, not during the emergency migration.
Part 7: Infrastructure security for LLM services#
Deep-dive
The application-layer lessons assume the infrastructure underneath is sound. For LLM services specifically, the infrastructure has unique exposure: always-on GPU inference endpoints, large in-memory contexts, vector stores holding corpus copies, and self-hosted runtimes that default to no authentication.
7.1 Network segmentation and egress#
- Segment the AI tier. The service that calls model APIs, the vector store, the cache and the inference endpoints live in a private subnet/VPC with no public ingress except through your API gateway/WAF. The LLM service itself should be reachable only by your app tier — Module 11C covers deployment topology; the security property is no direct public path to the model or the vector store.
- Egress allowlisting. The AI service needs outbound access to exactly: your provider endpoints, your vector DB, your object store, your observability vendor. Deny everything else at the network layer — this neuters exfiltration payloads from injection attacks (12.2 covers the injection side) and limits what a compromised dependency can phone home to. Provider endpoint lists change; manage the allowlist as config, not folklore.
- Private endpoints where offered. The major clouds now offer private connectivity to model APIs so traffic never touches the public internet:
- AWS Bedrock: VPC interface endpoints via PrivateLink for
bedrock,bedrock-runtime,bedrock-mantle,bedrock-agent,bedrock-agent-runtime(+ FIPS variants) — endpoint policies can restrict which model ARNs are invocable (AWS docs). - Azure OpenAI: private endpoints on the resource; disable public network access (Azure docs).
- Vertex AI: Private Service Connect, Private Google Access, or VPC Service Controls perimeters (Google docs).
- OpenAI API: Azure Private Link with regional
*.privatelink.api.openai.comendpoints — currently not self-service, and incompatible with IP allowlists/mTLS, so it's an either/or enterprise choice (OpenAI private link). - Gemini API (AI Studio) and OpenRouter: public SaaS — no private endpoint; OpenRouter offers data-region routing instead (Part 6.3). For these, your controls are key scoping, spend limits and egress rules, not network privacy.
- AWS Bedrock: VPC interface endpoints via PrivateLink for
- WAF and rate limiting at the edge. The LLM endpoint is an expensive, injectable, prompt-injectable surface — put a WAF in front for the classic web protections (OWASP Top 10), rate-limit per user/IP/key, and cap request sizes before they reach your app. LLM-specific abuse (denial-of-wallet via your users) is handled by per-user quotas in your app layer — Module 11B owns quota design.
- DDoS comes in two flavours, owned by different layers — know which is yours. Classic volumetric and protocol floods (UDP amplification, SYN floods, connection exhaustion) are absorbed at the CDN/WAF/anycast edge before they reach you; that layer's job is capacity and scrubbing, and your app never sees the traffic if it's sized right. Application-layer floods are different: individually valid requests that are collectively expensive — maximum-length prompts, huge
max_tokens, deep agent loops, expensive retrieval — sail straight past a volumetric defence and burn GPU and provider spend. Those are handled in your app layer: per-user quotas, request-size andmax_tokenscaps, concurrency limits, and the expensive-query controls from 2.4. A CDN that stops a 100 Gbps flood does nothing against 100 requests/second of legitimately-shaped expensive queries — and vice versa.
7.2 Self-hosted runtimes: the defaults are "trusted network"#
If you run open-weight models yourself, the serving layer has real auth gaps — verify current docs before exposing anything:
| Runtime | Default posture | What you must add |
|---|---|---|
| Ollama | Local API at localhost:11434 has no authentication; OLLAMA_HOST exposes it to the network with no warning (Ollama auth docs) |
Keep it loopback-only; if remote access is needed, put an authenticating reverse proxy in front (the docs themselves direct you there) |
| vLLM | --api-key protects only /v1, /v2, /inference, /cohere paths — /invocations, /tokenize, /metrics and operational-control endpoints such as /pause and /update_weights on the same server are unauthenticated (list as of November 2026); docs say "do not rely exclusively on --api-key" (vLLM security) |
Reverse proxy with auth + endpoint allowlist; bind --host 127.0.0.1; the proxy owns TLS/auth/rate-limits |
| llama.cpp / LM Studio | Optional single shared key, off by default | Same proxy pattern; per-user auth if multiple callers |
The pattern is identical across all of them: the inference engine assumes a trusted network; authentication, TLS, rate limits and endpoint filtering are the reverse proxy's job. Anyone who can reach the port can list models, run inference (your GPU bill), and on vLLM hit unauthenticated endpoints. Exposing these to the internet "for the demo" is how open-weight deployments get cryptojacked.
7.3 Container and host hardening#
- Images: non-root user, read-only filesystem where possible,
no-new-privileges, drop all capabilities, seccomp/AppArmor profile, no Docker socket mounted, minimal base image (distroless where feasible). The LLM service doesn't need a shell in production. - Secrets in containers: env vars are visible via
docker inspect,/proc/<pid>/environ, and crash dumps — prefer mounted secret files or a secrets-manager sidecar where the platform supports it; remember Part 3's rule that the secret should never be in the image layer anyway. - Resource limits: CPU/memory/GPU limits prevent one tenant's request from starving others — and prevent a prompt-injection-driven loop from consuming the whole box (12.2 covers the unbounded-consumption angle).
- Logging hygiene: never log request bodies that may contain keys or PII; structured logs with trace IDs; the observability pipeline is itself a data store (Part 2.5, 07.11, 5.3).
7.4 The infrastructure checklist#
- AI service + vector store + caches are on private networking; only the API gateway is public
- Egress allowlist enforced at network layer; provider endpoints managed as config
- Private endpoints used where the provider/cloud offers them; the choice (private link vs IP allowlist vs mTLS) is documented per provider
- Self-hosted runtimes bound to loopback or behind an authenticating proxy; no unauthenticated inference port exposed
- Containers: non-root, read-only, no-new-privileges, resource limits, no docker socket
- Secrets injected at runtime (env/secret manager), never baked into images or layers
- WAF + rate limits at edge; per-user quotas in app; request-size caps
- Images scanned (trivy/grype) and signed (cosign) in CI; only signed images deploy
- Security logs shipped to a monitored pipeline; access logs on the vector DB and model endpoints retained
Part 8: Model theft and endpoint abuse#
Deep-dive
The flip side of supply-chain inputs is supply-chain outputs: your model endpoint is a billable, abusable asset. Two distinct threats:
8.1 Model theft and extraction#
Model extraction — stealing a model's functionality by querying its API — is real but bounded. Tramèr et al. (USENIX Security 2016, arXiv:1609.02943) showed near-perfect extraction of classical ML models (logistic regression, decision trees, small neural nets) from prediction APIs with confidence scores; even without scores, extraction remained possible. For LLMs the economics differ: extracting a frontier model's behaviour via API queries costs millions in tokens and produces an approximation, not the weights — which is why the practical threats are narrower:
- Distillation at scale — a competitor or researcher systematically queries your API to train a competing model. This violates most providers' ToS (02.9, Part 9 covers output-use restrictions) and is detectable behaviourally (query patterns, output harvesting).
- Your fine-tuned/prompted pipeline IP — the valuable asset is often not the base model but your system prompt, retrieval corpus, tool definitions and eval-tuned behaviour. Extraction of that is prompt leaking (12.2 covers prompt extraction) and RAG corpus leakage (Part 2).
- Open-weight models have no API to steal from — the weights are downloadable; "theft" is meaningless. Your moat is the system around them.
Defences, honest about limits:
- Rate limits and per-user quotas — the primary control; extraction needs volume, so volume caps raise its cost directly (Module 11B).
- Output filtering — block known extraction patterns (repetitive structured queries, logit-probing formats); raises attacker effort, doesn't prevent it.
- Withhold logprobs/confidence where not needed — Tramèr showed confidence scores dramatically ease extraction; if your product doesn't need them, don't return them.
- Watermarking as provenance, not protection — see 8.2; a watermark helps attribute stolen outputs, it doesn't prevent extraction.
- ToS and monitoring — contractual prohibition + anomaly detection on query patterns; for egregious cases, provider-level enforcement.
8.2 Endpoint abuse and output provenance#
Cheaper and more common than model theft: abusing your endpoint. A leaked key (Part 3), a free-tier exploit, or a resold proxy turns your API into someone else's free inference — denial-of-wallet plus ToS violations committed under your account. (Volumetric DDoS is an edge/CDN problem; the LLM-specific variant — cost-amplification flooding — is this section's problem, handled by the quotas and caps in 7.1 and Part 3.)
- Authentication and quotas are the defence — per-user/per-key rate limits, spend caps, anomaly detection on usage patterns (Part 3.4). The abuse pattern looks like legitimate traffic at higher volume — detection is statistical, not signature-based.
- Watermarking — what it is and isn't. Providers now embed provenance signals in outputs: OpenAI's textGrain watermarks text (opt-in for API customers globally, rolling out by default for ChatGPT/Codex text in the EU; a detector is available to approved researchers; detection is probabilistic — ~80% of 200-token and ~95% of 400-token psychology-style responses at a 1% false-positive rate, lower for low-flexibility text such as mathematics, and synonym replacement degrades it sharply — OpenAI provenance, help centre); images and audio carry C2PA Content Credentials + SynthID watermarks. Google's SynthID (DeepMind) watermarks images/video/audio and its detector portal expanded globally in October 2026 to cover partners including OpenAI, NVIDIA, Kakao and Apple (DeepMind SynthID, Google blog); SynthID Text is open-sourced in Hugging Face Transformers v4.46+ for self-hosted use (ai.google.dev SynthID).
- What watermarks buy you: provenance — "this output came from a watermarked model" — useful for attribution, media verification and regulatory compliance.
- What they don't buy you: security. A watermark doesn't prevent extraction, doesn't stop abuse, is degraded by paraphrasing/editing/regeneration, and can't be relied on as an access control. Treat it as one signal in a provenance strategy, never a defence boundary.
- Output-side abuse controls: content filters for CSAM/illicit output (provider-side plus yours), prompt-injection output validation (12.5), and audit logging sufficient to reconstruct abuse for ToS enforcement.
Part 9: Build it — llm_guard_kit/supply_chain.py#
Time to build. One file, pure Python 3.11+ standard library — re, math, pickletools, tomllib, dataclasses, pathlib. No SDKs, no keys, no services: it runs anywhere Python runs. Three tools:
scan_secrets(text)— finds credentials in a string before it reaches a log, commit, prompt or trace. Known token shapes first (OpenAI/Anthropic/Google/xAI/Groq/GitHub/AWS/Slack/Hugging Face/PyPI/npm/Stripe/JWT/Bearerheaders/private-key blocks, plus passwords embedded inscheme://user:password@hostURLs), then credential-named assignments (OPENAI_API_KEY=…in a.env,"client_secret": "…"in JSON), then a length-aware Shannon-entropy heuristic for opaque literals. Findings carry a redacted excerpt (at most ten characters of the value survive) — the scanner never echoes the secret it found. Its known shapes are the ones the labels-onlyscan_secretsin 12.4, 3.3 redacts, so the two lessons agree on what counts as a credential; PyPI and npm tokens and the entropy pass are extra here.audit_requirements(path)/audit_uv_lock(path)— verify dependency installs are hash-pinned the waypip install --require-hashesdemands: every requirement is pinned with exactly one==specifier and carries well-formed--hash=values (sha256/384/512), and every registry package inuv.lockrecords a hash for its sdist and each wheel. A line it cannot parse counts as a failing requirement, never as a skipped one.inspect_pickle(data)— walks a pickle's opcode stream withpickletools.genopsand reports which globals it would import and call — without unpickling. It resolves imports that arrive through the memo (protocol 4+), maps the Python 2 module names that protocol 0 to 2 pickles use (commands.Popenloads assubprocess.Popen), keeps parsing past the firstSTOP, reports dangerous globals even when the file is corrupt after them, and treats an import it cannot resolve as a finding. This is what picklescan/ModelScan do at larger scale, and the reason it's safe to point at a file you don't trust.
Save as llm_guard_kit/supply_chain.py (block 1 of 2 — imports, secret scanner, dependency auditors):
"""llm_guard_kit/supply_chain.py — supply-chain defences, pure stdlib.
1. scan_secrets(text) — find credentials in text before it reaches a
log, a commit, a prompt or a trace. Known token shapes first, then
credential-named assignments, then a length-aware Shannon-entropy
heuristic for opaque literals. Findings carry a redacted excerpt — the
scanner never echoes the secret it found.
2. audit_requirements(path) / audit_uv_lock(path) — check that a
dependency install is hash-pinned: every requirement line carries
--hash=sha256:..., and a uv.lock records a hash for every
distribution.
3. inspect_pickle(data) — walk a pickle's opcode stream with
pickletools.genops and report which globals it would try to import
and call, WITHOUT unpickling. pickle.load executes; genops only
parses.
"""
from __future__ import annotations
import _compat_pickle # CPython's table of Python 2 module names that pickle maps back
import io
import math
import pickletools
import re
import tomllib
from dataclasses import dataclass, field
from pathlib import Path
# ---------------------------------------------------------------------------
# 1. Secret scanning
# ---------------------------------------------------------------------------
# Known credential shapes. Each pattern is anchored enough to keep false
# positives low; the secret body is captured so the excerpt can be redacted.
_KNOWN_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
("anthropic_key", re.compile(r"\bsk-ant-[A-Za-z0-9_-]{20,}\b")),
("openai_key", re.compile(r"\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}\b")),
# Fixed-length body: end with a lookahead, not \b — a key may legitimately
# end in "-", and \b after a non-word character would reject it.
("google_api_key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])")),
("github_token", re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b|\bgithub_pat_[A-Za-z0-9_]{30,}\b")),
("aws_access_key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
("slack_token", re.compile(r"\bxox[abeoprs]-[A-Za-z0-9-]{10,}\b")),
("huggingface_token", re.compile(r"\bhf_[A-Za-z0-9]{20,}\b")),
("xai_key", re.compile(r"\bxai-[A-Za-z0-9]{20,}\b")),
("groq_key", re.compile(r"\bgsk_[A-Za-z0-9]{20,}\b")),
("google_oauth_token", re.compile(r"\bya29\.[A-Za-z0-9_-]{20,}")),
# An Authorization header value; 12.4's scrubber redacts the same shape.
("bearer_token", re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._\-]{12,}")),
("pypi_token", re.compile(r"\bpypi-[A-Za-z0-9_-]{50,}")),
("npm_token", re.compile(r"\bnpm_[A-Za-z0-9]{36}\b")),
("stripe_secret_key", re.compile(r"\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}\b")),
("slack_webhook", re.compile(r"https://hooks\.slack\.com/services/T[A-Z0-9]{6,}/B[A-Z0-9]{6,}/[A-Za-z0-9]{16,}")),
# scheme://user:password@host — the password is the secret. Every part is
# length-bounded, so the scan stays linear; the match stops before the "@".
("url_credentials", re.compile(r"\b[A-Za-z][A-Za-z0-9+.-]{1,20}://[^\s:/@\"'<>]{1,64}:[^\s/@\"'<>]{1,128}(?=@)")),
("private_key_block", re.compile(r"-----BEGIN (?:[A-Z]+ )*PRIVATE KEY(?: BLOCK)?-----")),
# Left boundary is a lookbehind over the whole character class, not \b: "-" is
# in the class, so \b would let every "eyJ" in "eyJ-eyJ-..." start a scan to
# the end of the run (quadratic: 2.7 s on 100 kB).
("jwt", re.compile(r"(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b")),
]
# A generic "name = value" assignment whose NAME says credential. Real code
# rarely uses the bare word: OPENAI_API_KEY, db_password, "client_secret" in
# JSON — so we anchor on the keyword wherever it sits in the name (a
# prefix needs no pattern, and scanning for one would be quadratic on long
# base64 runs), allow a short suffix (bounded, so "tokentokentoken…" can't
# make the scan quadratic), and accept a quoted key (JSON / YAML) with
# the value quoted or bare (.env files).
_ASSIGNMENT = re.compile(
r"""(?ix)
(?:api[_-]?key|secret|token|password|passwd|private[_-]?key)
[A-Za-z0-9_.-]{0,40}
["']?\s*[:=]\s*
(?:["']([^"'\s]{8,200})["']|([^\s"'#,;]{8,200}))
"""
)
# Opaque literal: long run of base64-ish characters. Hex digests (sha256 etc.)
# stay out because they only use 16 symbols (fewer than three character classes).
_OPAQUE = re.compile(r"\b[A-Za-z0-9+/=_-]{32,}\b")
_MIN_OPAQUE_LEN = 32
_ENTROPY_CAP = 4.5 # bits per char, the ceiling for long strings
_HEX_ONLY = re.compile(r"[0-9a-fA-F]{32,}")
_ALNUM_ONLY = re.compile(r"[A-Za-z0-9]{12,}")
_CODE_CHARS = re.compile(r"[()\[\]{}<>$]")
def _shannon_entropy(s: str) -> float:
if not s:
return 0.0
counts = {c: s.count(c) for c in set(s)}
n = len(s)
return -sum((c / n) * math.log2(c / n) for c in counts.values())
def _entropy_floor(n: int) -> float:
"""Minimum Shannon entropy (bits/char) for a random-looking string of n chars.
A *measured* entropy can never exceed log2(n): 32 characters cap at 5.0
bits however random they are, and a truly random 32-character base64
token averages only ~4.6. A flat 4.5 floor therefore misses about 30%
of random 32-character tokens (and nearly all 24-character ones). So the
floor scales with length — 85% of log2(n), capped at 4.5 — and a
character-class test (below) supplies the precision the lower floor gives up.
"""
return min(_ENTROPY_CAP, 0.85 * math.log2(max(n, 2)))
def _character_classes(s: str) -> int:
"""How many of lower / upper / digit / other appear in ``s`` (0-4)."""
return sum((
any(c.islower() for c in s),
any(c.isupper() for c in s),
any(c.isdigit() for c in s),
any(not c.isalnum() for c in s),
))
def _looks_random(s: str) -> bool:
"""Random-looking: three or more character classes, at least one digit
(random base64/alphanumeric strings are ~16% digits; camelCase identifiers
rarely have any), and enough entropy for the length. kebab-case slugs fail
the entropy test and hex digests have only two character classes. Paths and
long ``KEY=value`` lines can still trip it — that is the false-positive cost
of a floor low enough to catch 24-40 character secrets."""
return (
_character_classes(s) >= 3
and any(c.isdigit() for c in s)
and _shannon_entropy(s) >= _entropy_floor(len(s))
)
def _looks_like_alnum_secret(s: str) -> bool:
"""For a value that a credential-*named* assignment holds: letters and
digits only (so it cannot be a code expression, a path or a placeholder
such as ``${DB_PASSWORD}``), at least one of each, and a gentler entropy
floor. Lower-case-plus-digit tokens have only two character classes and a
36-symbol alphabet, so ``_looks_random`` would never accept them."""
return (
_ALNUM_ONLY.fullmatch(s) is not None
and any(c.isdigit() for c in s)
and any(c.isalpha() for c in s)
and _shannon_entropy(s) >= min(4.0, 0.75 * math.log2(len(s)))
)
@dataclass(frozen=True)
class SecretFinding:
kind: str # e.g. "openai_key", "high_entropy_literal", "assignment"
line: int
column: int
# The matched text with its middle replaced — enough to locate it in a
# diff or a log line, never enough to replay the credential.
excerpt: str
def _redact(match_text: str) -> str:
"""At most 10 characters of the value survive — mostly a public prefix
such as ``sk-proj-`` — and short values keep only 4."""
if len(match_text) < 24:
return match_text[:4] + "…"
return match_text[:8] + "…" + match_text[-2:]
def scan_secrets(text: str) -> list[SecretFinding]:
"""Scan one string; return findings ordered by line."""
findings: list[SecretFinding] = []
seen_spans: set[tuple[int, int]] = set()
def already_covered(start: int, end: int) -> bool:
return any(not (end <= s or start >= e) for s, e in seen_spans)
# Pass 1: known provider/vendor shapes — highest confidence.
for kind, pattern in _KNOWN_PATTERNS:
for m in pattern.finditer(text):
if already_covered(m.start(), m.end()):
continue
line = text.count("\n", 0, m.start()) + 1
col = m.start() - text.rfind("\n", 0, m.start())
findings.append(SecretFinding(kind, line, col, _redact(m.group(0))))
seen_spans.add((m.start(), m.end()))
# Pass 2: credential-named assignments. The NAME carries the suspicion, so
# the value test is gentler than for an anonymous literal: no whitespace
# (a value with spaces is prose or a passphrase — `password = "correct
# horse battery staple"` is a choice for a human to judge, and "Enter
# your password" is a UI label), and either random-looking or a long hex
# string (hex API keys are common; hex *digests* only get here when
# something named "key" or "token" holds them), or a plain letters-and-
# digits value such as a lower-case token or a password.
for m in _ASSIGNMENT.finditer(text):
group = 1 if m.group(1) is not None else 2
value = m.group(group)
# An unquoted value with brackets, braces or "$" is a code expression
# (``token = self._fp.read(1)[0]``) or a placeholder (``${DB_PASSWORD}``).
if group == 2 and _CODE_CHARS.search(value):
continue
if not (_looks_random(value) or _HEX_ONLY.fullmatch(value)
or _looks_like_alnum_secret(value)):
continue
start, end = m.start(group), m.end(group)
if already_covered(start, end):
continue
line = text.count("\n", 0, start) + 1
col = start - text.rfind("\n", 0, start)
findings.append(SecretFinding("assignment", line, col, _redact(value)))
seen_spans.add((start, end))
# Pass 3: opaque high-entropy literals anywhere else (keys pasted into
# URLs, command lines, JSON blobs without a friendly field name).
for m in _OPAQUE.finditer(text):
token = m.group(0)
if len(token) < _MIN_OPAQUE_LEN or not _looks_random(token):
continue
if already_covered(m.start(), m.end()):
continue
line = text.count("\n", 0, m.start()) + 1
col = m.start() - text.rfind("\n", 0, m.start())
findings.append(SecretFinding("high_entropy_literal", line, col,
_redact(token)))
seen_spans.add((m.start(), m.end()))
return sorted(findings, key=lambda f: (f.line, f.column))
def scan_file(path: str | Path) -> list[SecretFinding]:
return scan_secrets(Path(path).read_text(encoding="utf-8", errors="replace"))
# ---------------------------------------------------------------------------
# 2. Hash-pinned dependency checks
# ---------------------------------------------------------------------------
# pip accepts sha256, sha384 and sha512 digests in --hash=algo:hex.
_HASH_RE = re.compile(
r"--hash=(?:sha256:[0-9a-fA-F]{64}|sha384:[0-9a-fA-F]{96}|sha512:[0-9a-fA-F]{128})"
)
# What pip's --require-hashes accepts as "pinned": exactly ONE specifier, ``==``
# (or ``===``), or a direct ``name @ url``. ``x==1,!=1.1`` and ``x>=1`` are not.
_PINNED_RE = re.compile(
r"[A-Za-z0-9][A-Za-z0-9._-]*(?:\s*\[[^\]]*\])?\s*"
r"(?:===?\s*[A-Za-z0-9][A-Za-z0-9._!+*-]*|@\s*\S+)"
)
_COMMENT_RE = re.compile(r"(?:^|\s)#") # pip's rule: "#" starts a comment only at a word start
_REQ_NAME_RE = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)")
# Options that send pip somewhere other than the pinned, hashed list: an extra
# index is the dependency-confusion route, find-links and a trusted host drop
# transport checks, and an editable install cannot be hash-checked at all.
_RISKY_OPTION_RE = re.compile(
r"(?:--(?:extra-index-url|index-url|find-links|trusted-host|editable)\b|-[ife]\b)")
@dataclass
class RequirementsReport:
path: str
total: int
hashed: int
missing: list[str] = field(default_factory=list)
malformed_hashes: list[str] = field(default_factory=list)
unpinned: list[str] = field(default_factory=list)
# Option lines that change where packages come from or how they are checked
# (extra indexes, find-links, trusted hosts, editable installs).
risky_options: list[str] = field(default_factory=list)
@property
def ok(self) -> bool:
return (not self.missing and not self.malformed_hashes
and not self.unpinned and not self.risky_options)
def audit_requirements(path: str | Path) -> RequirementsReport:
"""Check a pip-style requirements file the way ``pip install
--require-hashes`` will: every requirement must be pinned (``==``, or a
direct ``name @ url``) and carry at least one valid ``--hash=``
(sha256/384/512; several per line — one per acceptable distribution
file), and every ``--hash=`` on the line must be well-formed. It does not
follow ``-r other.txt`` includes: audit each file."""
report = RequirementsReport(path=str(path), total=0, hashed=0)
# Join backslash continuations first: pip hashes live on the lines
# AFTER the requirement line, so per-line parsing would miss them.
logical: list[str] = []
buf = ""
# utf-8-sig: a BOM would otherwise hide the first requirement from the name match.
for raw in Path(path).read_text(encoding="utf-8-sig").splitlines():
stripped = raw.rstrip()
buf = (buf + " " + stripped.strip()) if buf else stripped
if stripped.endswith("\\"):
buf = buf[:-1].rstrip() + " "
continue
logical.append(buf)
buf = ""
if buf:
logical.append(buf)
for raw in logical:
line = _COMMENT_RE.split(raw, maxsplit=1)[0].strip()
if line.startswith("-"):
if _RISKY_OPTION_RE.match(line):
report.risky_options.append(line.split()[0])
continue # other options (-r, -c, --require-hashes) are not requirements
if not line:
continue
# A line we cannot parse (``./local/pkg``, ``"quoted"``) is still a
# requirement pip will try to install: count it, never skip it.
name_m = _REQ_NAME_RE.match(line)
name = name_m.group(1) if name_m else line.split()[0]
report.total += 1
spec = re.split(r"\s--|;", line, maxsplit=1)[0].strip() # drop options and markers
if not _PINNED_RE.fullmatch(spec):
report.unpinned.append(name)
hash_args = re.findall(r"--hash=\S*", line)
if not hash_args:
report.missing.append(name)
elif all(_HASH_RE.fullmatch(h) for h in hash_args):
report.hashed += 1
else: # at least one --hash= that pip would reject, even if another is valid
report.malformed_hashes.append(name)
return report
@dataclass
class LockPackage:
name: str
version: str
has_hash: bool
source_kind: str
@dataclass
class LockReport:
path: str
packages: list[LockPackage] = field(default_factory=list)
@property
def unhashed(self) -> list[LockPackage]:
return [p for p in self.packages if not p.has_hash]
@property
def needs_review(self) -> list[LockPackage]:
"""Unhashed packages that are not a local path. Filtering on
``source_kind == "registry"`` alone would let a package that quietly
changed to a URL or an unrecognised source skip the check."""
return [p for p in self.unhashed if p.source_kind != "path"]
# uv records "sha256:" plus 64 hex digits for the sdist and every wheel it locks.
_LOCK_HASH_RE = re.compile(r"sha256:[0-9a-fA-F]{64}")
def audit_uv_lock(path: str | Path) -> LockReport:
"""Parse a ``uv.lock`` (TOML) and report which packages record a hash.
uv records a sha256 for the sdist and every wheel of registry packages;
path/git/editable sources legitimately have none. Fails closed: a file
that is not valid TOML, or has no ``[[package]]`` entries (an empty file,
a ``pyproject.toml`` passed by mistake), raises ValueError instead of
returning a report that looks clean; a distribution whose ``hash`` is
missing, not text, or not ``sha256:`` plus 64 hex digits counts as
unhashed. It checks that hashes are recorded, not that they are right
(``uv sync --locked`` and pip's hash checking do that at install time)."""
try:
data = tomllib.loads(Path(path).read_text(encoding="utf-8-sig"))
except tomllib.TOMLDecodeError as exc:
raise ValueError(f"{path}: not valid TOML: {exc}") from exc
packages = data.get("package")
if (not isinstance(packages, list) or not packages
or not all(isinstance(p, dict) for p in packages)):
raise ValueError(f"{path}: no [[package]] entries, so this is not a uv.lock")
report = LockReport(path=str(path))
for pkg in packages:
source = pkg.get("source")
source = source if isinstance(source, dict) else {}
kind = "registry" if "registry" in source else \
"git" if "git" in source else \
"path" if "path" in source or "editable" in source else "other"
# Every distribution (the sdist and each wheel) must record a hash.
wheels = pkg.get("wheels", [])
dists = ([pkg["sdist"]] if "sdist" in pkg else []) + \
(wheels if isinstance(wheels, list) else [None])
has_hash = bool(dists) and all(
isinstance(d, dict) and isinstance(d.get("hash"), str)
and _LOCK_HASH_RE.fullmatch(d["hash"]) for d in dists)
name, version = pkg.get("name"), pkg.get("version")
report.packages.append(LockPackage(
name=name if isinstance(name, str) and name else "?",
version=version if isinstance(version, str) and version else "?",
has_hash=has_hash,
source_kind=kind,
))
return reportBlock 2 of 2 — the pickle opcode inspector, demo fixtures and __main__ driver (concatenate after block 1 to get the full file). Run it with no arguments for the built-in demo, or pass file paths to scan them for secrets: python -m llm_guard_kit.supply_chain app.log .env.example prints one line per finding and exits 1 if anything was found.
# ---------------------------------------------------------------------------
# 3. Pickle opcode inspection (never unpickles)
# ---------------------------------------------------------------------------
# Whole modules that turn "load a file" into "run a command", "reach the
# network" or "import anything": ANY attribute pickled from them is flagged,
# matching on the top-level package (so ``urllib.request`` and ``http.client``
# are covered by ``urllib`` and ``http``). The list mirrors what
# picklescan/ModelScan flag; it is a tripwire — a determined payload can hide
# behind a callable nobody thought to list, which is why safetensors, not
# this scanner, is the real control.
_DANGEROUS_MODULES = frozenset({
"os", "posix", "nt", "subprocess", "socket", "socketserver", "pty",
"runpy", "importlib", "ctypes", "webbrowser", "multiprocessing",
"asyncio", "pdb", "code", "codeop", "timeit", "urllib", "http",
"requests", "httpx", "aiohttp", "ftplib", "smtplib", "telnetlib",
"xmlrpc", "paramiko",
# Helpers that call or look up arbitrary objects, and low-level twins of
# the modules above (the C accelerators pickle actually names).
"operator", "functools", "pkgutil", "types", "inspect", "pydoc", "platform",
"shutil", "tempfile", "sys", "_posixsubprocess", "_socket", "_ctypes",
"_winapi", "_multiprocessing",
# Profilers and debuggers that run a string, installers, and other
# serialisers that can themselves load arbitrary objects.
"cProfile", "profile", "trace", "bdb", "doctest", "distutils", "venv",
"ensurepip", "pip", "setuptools", "idlelib", "lib2to3", "shelve", "dbm",
"dill", "cloudpickle", "joblib", "zipfile", "tarfile", "sqlite3", "_sqlite3",
})
# Specific callables in modules that are otherwise fine to pickle from.
_DANGEROUS_GLOBALS = {
"builtins": {"eval", "exec", "compile", "__import__", "open", "input",
"breakpoint", "getattr", "setattr", "delattr", "globals",
"locals", "vars"},
"__builtin__": {"eval", "exec", "compile", "__import__", "open",
"getattr", "setattr", "delattr", "globals", "locals",
"vars"},
"pickle": {"loads", "load"},
"marshal": {"loads", "load"},
"pathlib": {"Path"},
# ``open`` lives in the io module, and CPython pickles it as ``_io.open``.
"io": {"open", "open_code", "FileIO"},
"_io": {"open", "open_code", "FileIO"},
"_pickle": {"loads", "load", "Unpickler"},
"numpy.testing._private.utils": {"runstring"},
"numpy": {"load"}, # np.load(..., allow_pickle=True)
"torch.storage": {"_load_from_bytes"}, # a torch.load inside the pickle
"pandas.io.pickle": {"read_pickle"},
"pandas": {"read_pickle"},
}
# Opcodes that mean "this pickle does something" rather than "this pickle
# is data". A pure-tensor .pkl contains mostly BINUNICODE/BINPUT proto
# opcodes and LONG1/BININT for shapes; BUILD/REDUCE/INST/GLOBAL are the
# ones that can run code.
_INTERESTING_OPS = {"GLOBAL", "STACK_GLOBAL", "INST", "OBJ", "REDUCE",
"BUILD", "NEWOBJ", "NEWOBJ_EX", "EXT1", "EXT2", "EXT4"}
# Opcodes that push a text string — the only operands STACK_GLOBAL accepts.
_STRING_PUSH_OPS = {"SHORT_BINUNICODE", "BINUNICODE", "BINUNICODE8", "UNICODE",
"STRING", "BINSTRING", "SHORT_BINSTRING"}
_MARK = object() # stand-in for pickle's MARK on our simulated stack
@dataclass(frozen=True)
class PickleFinding:
kind: str
detail: str
@dataclass
class PickleReport:
path: str
opcode_count: int
globals_seen: list[tuple[str, str]] = field(default_factory=list)
dangerous: list[PickleFinding] = field(default_factory=list)
interesting_ops: list[str] = field(default_factory=list)
# Imports we could not resolve to a (module, name) pair — treated as unsafe.
unresolved: list[str] = field(default_factory=list)
parse_error: str | None = None
@property
def safe_to_load(self) -> bool:
"""Heuristic verdict: no known-dangerous global, no import we failed
to resolve, and a stream that parsed cleanly to the end. It means
"this tripwire did not fire", NOT "this file is safe": prefer
safetensors for weights you didn't build yourself."""
return not self.dangerous and not self.unresolved and not self.parse_error
def _global_name(module: str, name: str) -> PickleFinding | None:
# A protocol 0-2 pickle may spell a global with its Python 2 name
# (``commands.Popen`` for ``subprocess.Popen``) and the unpickler maps it
# back, so judge the name as written AND as it will be resolved.
resolved = _compat_pickle.NAME_MAPPING.get((module, name)) or (
_compat_pickle.IMPORT_MAPPING.get(module, module), name)
for mod, attr in {(module, name), resolved}:
if (
mod.split(".")[0] in _DANGEROUS_MODULES
or attr in _DANGEROUS_GLOBALS.get(mod, ())
):
return PickleFinding("dangerous_global", f"{module}.{name}")
return None
def _record_global(report: PickleReport, module: str, attr: str) -> None:
report.globals_seen.append((module, attr))
finding = _global_name(module, attr)
if finding:
report.dangerous.append(finding)
def _step(report: PickleReport, stack: list[object], memo: dict[int, object],
marks: list[int], opcode: pickletools.OpcodeInfo, arg: object) -> None:
"""Analyse one opcode and mirror its effect on a simulated stack.
The stack only has to be faithful about *strings* — a protocol-4
STACK_GLOBAL takes its module and name from the two values on top, which
may have come through the memo (BINGET) rather than straight from a push.
``opcode.stack_before`` / ``stack_after`` (the same tables
``pickletools.dis`` uses) say how many values each opcode pops and pushes.
"""
name = opcode.name
if name in _INTERESTING_OPS and name not in report.interesting_ops:
report.interesting_ops.append(name)
if name in ("GLOBAL", "INST"):
# pickletools reports the operand as "module name".
parts = str(arg).replace("\n", " ").split()
if len(parts) >= 2:
_record_global(report, parts[0], parts[1])
else:
report.unresolved.append(f"{name} operand {arg!r}")
elif name == "STACK_GLOBAL":
module, attr = (stack[-2], stack[-1]) if len(stack) >= 2 else (None, None)
if isinstance(module, str) and isinstance(attr, str):
_record_global(report, module, attr)
else:
report.unresolved.append("STACK_GLOBAL with operands that are not literal strings")
elif name in ("EXT1", "EXT2", "EXT4"):
report.unresolved.append(f"{name} {arg!r}: extension-registry code")
# --- mirror the stack -------------------------------------------------
if name == "MARK":
marks.append(len(stack)) # where this MARK sits, so we never scan for it
stack.append(_MARK)
return
if name == "DUP":
stack.append(stack[-1] if stack else None)
return
if name in ("PUT", "BINPUT", "LONG_BINPUT", "MEMOIZE"):
# Memo writes copy the top value and leave the stack alone.
memo[arg if name != "MEMOIZE" else len(memo)] = stack[-1] if stack else None
return
before, after = opcode.stack_before, opcode.stack_after
numtopop = len(before)
if pickletools.markobject in before or (name == "POP" and stack and stack[-1] is _MARK):
if marks:
del stack[marks.pop():] # through the top MARK
numtopop = before.index(pickletools.markobject) if pickletools.markobject in before else 0
else:
report.unresolved.append(f"{name}: no MARK on the stack")
numtopop = 0
if numtopop > len(stack):
report.unresolved.append(f"{name}: stack underflow")
numtopop = len(stack)
if numtopop:
del stack[len(stack) - numtopop:]
stack.extend([None] * len(after))
if after and name in _STRING_PUSH_OPS and isinstance(arg, str):
stack[-1] = arg
elif after and name in ("GET", "BINGET", "LONG_BINGET"):
stack[-1] = memo.get(arg)
def inspect_pickle(data: bytes, *, path: str = "<bytes>") -> PickleReport:
"""Walk the opcode stream. ``pickletools.genops`` is a parser — it
decodes opcodes and arguments without executing anything, which is
exactly why it's safe to point at a file you don't trust (as long as
you never pass the bytes to ``pickle.load``).
Three habits that matter for untrusted files:
* Opcodes are analysed as they stream past, so everything seen *before*
a corrupt tail is still reported — a payload followed by garbage (the
"broken pickle" evasion) shows its dangerous globals AND a parse error.
* A stream may hold several pickles back to back (legacy ``torch.save``
does): after each STOP, parsing continues with the next one.
* An import we cannot resolve is a finding, not a pass.
"""
report = PickleReport(path=path, opcode_count=0)
stream = io.BytesIO(data)
try:
while True:
stack: list[object] = [] # stack, memo and marks are per pickle
memo: dict[int, object] = {}
marks: list[int] = []
for opcode, arg, _pos in pickletools.genops(stream):
report.opcode_count += 1
_step(report, stack, memo, marks, opcode, arg)
if stream.tell() >= len(data):
break
except Exception as e: # pickletools raises ValueError on malformed input
report.parse_error = f"{type(e).__name__}: {e}"
return report
def inspect_pickle_file(path: str | Path) -> PickleReport:
p = Path(path)
return inspect_pickle(p.read_bytes(), path=str(p))
# ---------------------------------------------------------------------------
# Demo fixtures (all synthetic — nothing here is a real credential)
# ---------------------------------------------------------------------------
def _demo_secrets() -> str:
return """\
# config.py — a file that SHOULD fail the scanner
OPENAI_API_KEY = "sk-proj-EXAMPLEkeymaterial0000000000000000" # synthetic
ANTHROPIC_KEY = "sk-ant-EXAMPLEkeymaterial00000000000000000" # synthetic
api_key = "AIzaSyEXAMPLEexampleEXAMPLEexampleEXAMP" # synthetic, 39 chars
GH_TOKEN = "ghp_EXAMPLEtokenmaterial000000000000000000" # synthetic
AWS_KEY = "AKIAIOSFODNN7EXAMPLE" # AWS docs example
JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJVadQssw5c" # jwt.io example
auth_token = "correct horse battery staple" # passphrase, not a leak
PRIVATE KEY:
-----BEGIN PRIVATE KEY-----
opaque = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08" # sha256 hex
blob = "aGVsbG8gd29ybGQhMTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6" # b64-ish
db_password = "Tr0ub4dor&3xK!zz" # synthetic: short, but named like a secret
{"client_secret": "xK9mQ2vL7nR4wZ8aB3cD"} # synthetic, JSON-style
"""
def _demo_requirements() -> str:
return """\
# requirements.txt — mixed pinned/unpinned, for the audit demo
requests==2.32.3 \\
--hash=sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6 \\
--hash=sha256:58cd2187c01e70e6e26505bca751777aa9f2ee0b7f4300988b709f44f7e3a0b5
flask==3.0.3
numpy>=1.26
pydantic==2.14.3 --hash=sha256:not-a-real-hash-but-right-shape-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
"""
def _demo_uv_lock() -> str:
return """\
version = 1
requires-python = ">=3.11"
[[package]]
name = "requests"
version = "2.32.3"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/x/requests-2.32.3.tar.gz", hash = "sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/x/requests-2.32.3-py3-none-any.whl", hash = "sha256:58cd2187c01e70e6e26505bca751777aa9f2ee0b7f4300988b709f44f7e3a0b5" },
]
[[package]]
name = "local-helper"
version = "0.1.0"
source = { editable = "." }
"""
def _demo_pickle_benign() -> bytes:
"""A plain data pickle — what a safetensors-free weights file might
contain. Only opcodes, no globals beyond builtins."""
import pickle
return pickle.dumps({"weights_shape": [2, 3], "note": "synthetic tensor meta"})
def _demo_pickle_broken_tail() -> bytes:
"""The flagged pickle with its STOP byte replaced by garbage — the shape
of the "broken pickle" evasion: a loader executes the opcodes up to the
corrupt byte, while a scanner that only reports on files that parse
completely sees nothing. Never unpickled."""
return _demo_pickle_flagged()[:-1] + b"\xff"
def _demo_pickle_flagged() -> bytes:
"""Hand-built protocol-0 pickle bytes that *reference* os.system.
These bytes are NEVER unpickled — inspect_pickle only parses the
opcode stream, which is the whole point of the tool. The format:
c<module>\\n<name>\\n GLOBAL: import module.name
S'...' STRING: the argument
\\x85 TUPLE1: wrap it
R REDUCE: call it <- code execution
. STOP
"""
return b"cos\nsystem\nS'echo this-would-run-if-unpickled'\n\x85R."
if __name__ == "__main__":
import sys
# CLI mode: `python -m llm_guard_kit.supply_chain FILE [FILE ...]`
# scans each file for secrets. One line per finding, and exit status
# 1 if anything was found — the convention CI secret scanners use,
# so this can gate a pipeline the same way gitleaks does.
if len(sys.argv) > 1:
status = 0
for arg in sys.argv[1:]:
try:
found = scan_file(arg)
except OSError as exc:
print(f"{arg}: cannot read file ({exc})")
status = 2
continue
for f in found:
print(f"{arg}:{f.line}:{f.column} {f.kind:22s} {f.excerpt}")
print(f"{arg}: {len(found)} finding(s)")
if found:
status = 1
sys.exit(status)
print("=== scan_secrets on a file that should fail ===")
for f in scan_secrets(_demo_secrets()):
print(f" line {f.line:2d} col {f.column:2d} {f.kind:22s} {f.excerpt}")
print("\n=== scan_secrets on clean text ===")
clean = 'print("hello")\nname = "world"\n'
print(" ", scan_secrets(clean) or "no findings")
print("\n=== audit_requirements ===")
import tempfile, os
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as t:
t.write(_demo_requirements()); req_path = t.name
rep = audit_requirements(req_path)
print(f" {rep.path}: {rep.hashed}/{rep.total} hashed")
print(f" missing hashes : {rep.missing}")
print(f" malformed : {rep.malformed_hashes}")
print(f" not pinned (==): {rep.unpinned}")
print(f" verdict : {'PASS' if rep.ok else 'FAIL'}")
os.unlink(req_path)
print("\n=== audit_uv_lock ===")
with tempfile.NamedTemporaryFile("w", suffix=".lock", delete=False) as t:
t.write(_demo_uv_lock()); lock_path = t.name
lrep = audit_uv_lock(lock_path)
for p in lrep.packages:
print(f" {p.name:15s} {p.version:8s} source={p.source_kind:8s} hash={'yes' if p.has_hash else 'NO'}")
print(f" unhashed and not a local path: {[p.name for p in lrep.needs_review]}")
os.unlink(lock_path)
print("\n=== inspect_pickle: benign data pickle ===")
benign = inspect_pickle(_demo_pickle_benign(), path="weights_meta.pkl")
print(f" opcodes={benign.opcode_count} globals={benign.globals_seen} "
f"dangerous={benign.dangerous} interesting={benign.interesting_ops}")
print(f" verdict: {'SAFE-LOOKING' if benign.safe_to_load else 'FLAGGED'}")
print("\n=== inspect_pickle: hand-built os.system reference ===")
flagged = inspect_pickle(_demo_pickle_flagged(), path="evil_meta.pkl")
print(f" opcodes={flagged.opcode_count} globals={flagged.globals_seen}")
print(f" dangerous={[f.detail for f in flagged.dangerous]}")
print(f" interesting ops seen: {flagged.interesting_ops}")
print(f" verdict: {'SAFE-LOOKING' if flagged.safe_to_load else 'FLAGGED — do not load'}")
print(f" parse_error: {flagged.parse_error}")
print("\n=== inspect_pickle: same payload, corrupt tail ===")
broken = inspect_pickle(_demo_pickle_broken_tail(), path="broken_meta.pkl")
print(f" dangerous={[f.detail for f in broken.dangerous]}")
print(f" verdict: {'SAFE-LOOKING' if broken.safe_to_load else 'FLAGGED — do not load'}")
print(f" parse_error: {broken.parse_error}")9.1 Output (ran locally — real, not illustrative; Python 3.14, no keys)#
=== scan_secrets on a file that should fail ===
line 2 col 19 openai_key sk-proj-…00
line 3 col 18 anthropic_key sk-ant-E…00
line 4 col 12 google_api_key AIzaSyEX…MP
line 5 col 13 github_token ghp_EXAM…00
line 6 col 12 aws_access_key AKIA…
line 7 col 8 jwt eyJhbGci…5c
line 10 col 1 private_key_block -----BEG…--
line 12 col 9 high_entropy_literal aGVsbG8g…l6
line 13 col 16 assignment Tr0u…
line 14 col 20 assignment xK9m…
=== scan_secrets on clean text ===
no findings
=== audit_requirements ===
.../tmpXXX.txt: 1/4 hashed
missing hashes : ['flask', 'numpy']
malformed : ['pydantic']
not pinned (==): ['numpy']
verdict : FAIL
=== audit_uv_lock ===
requests 2.32.3 source=registry hash=yes
local-helper 0.1.0 source=path hash=NO
unhashed and not a local path: []
=== inspect_pickle: benign data pickle ===
opcodes=19 globals=[] dangerous=[] interesting=[]
verdict: SAFE-LOOKING
=== inspect_pickle: hand-built os.system reference ===
opcodes=5 globals=[('os', 'system')]
dangerous=['os.system']
interesting ops seen: ['GLOBAL', 'REDUCE']
verdict: FLAGGED — do not load
parse_error: None
=== inspect_pickle: same payload, corrupt tail ===
dangerous=['os.system']
verdict: FLAGGED — do not load
parse_error: ValueError: at position 49, opcode b'\xff' unknownRead the output like a reviewer:
- The scanner found seven known credential shapes, one opaque base64 blob and two credential-named assignments (a short but strong password and a JSON-style client secret) in a 14-line file — and correctly ignored
auth_token = "correct horse battery staple"(a value with spaces is a passphrase or a UI label, a human's call) and thesha256hex digest (64 chars, but hex has only two character classes and about 3.8 bits per character). Notice the excerpts: at most ten characters of any value survive, mostly the public prefix (sk-proj-). - Why the entropy floor scales with length. A measured Shannon entropy can never exceed log2(n): 32 characters cap at 5.0 bits however random they are, and a truly random 32-character base64url string averages about 4.6. In a quick simulation (5,000 random 32-character strings, not part of the demo), a flat 4.5-bit floor passed only about 70% of them, and almost none of the 24-character ones. So the floor here is 85% of log2(n), capped at 4.5, and precision comes back from two extra tests: at least three character classes and at least one digit. Hex digests, camelCase identifiers and kebab-case slugs fail those; base64 data URIs and long path-like strings can still false-positive. That is the precision/recall trade made visible: it will miss some real secrets (obscure formats, 32-hex API keys that nothing names, low-entropy passwords outside a credential-named assignment) and flag a few false positives — which is why it's a CI gate that a human reviews, not an auto-blocker.
audit_requirementsshows why--require-hashesmatters:requestspasses (its\-continued--hashlines were joined before parsing),flask/numpyare unhashed,numpyis not pinned with==either (pip would refuse it in this mode),pydantic's hash isn't a valid sha256 → FAIL. In a real pipeline this file would never reachpip install.audit_uv_lockconfirms uv's behaviour: registry packages carry hashes; your own editable/path packages legitimately don't — so the check is "nothing unhashed except a local path" (needs_review), not "every package has a hash". Filtering onsource_kind == "registry"alone would let a package that was edited to a URL or an unrecognised source drop out of the check, which is the edit an attacker would make. The function also refuses to return a clean-looking report for a file that is not a lockfile (empty, apyproject.toml, invalid TOML), and counts ahashthat is notsha256:plus 64 hex digits (a boolean, a short string, another algorithm) as missing.inspect_pickleis the star: the benign data pickle shows 19 opcodes, no globals, SAFE-LOOKING; the hand-builtos.systempickle — five opcodes — is FLAGGED with the exact dangerous global. The third pickle is the same payload with itsSTOPbyte replaced by garbage — the shape of the "broken pickle" evasion in the failure gallery: a scanner that only reports on files that parse completely would say nothing, but this one streams opcodes, so it still showsos.systemnext to the parse error. Note what it didn't do: execute anything.pickletools.genopsparses;pickle.loadexecutes. Same bytes, different function. Two practical limits: the inspector reads a raw pickle stream, so for a modern PyTorch.pt/.pthfile (a zip archive) extract thedata.pklmember and inspect that, because the zip bytes themselves will come back as a parse error (flagged, which is the safe direction); and the module and global lists are a tripwire, so a pickle that merely passes it is not thereby safe.
Attack tests. The demo uses clean fixtures. These six tests hold the fixes for inputs that fooled or stalled earlier versions (the last three are audit_uv_lock's: a file that is not a lockfile, hashes that are present but not real sha256 values, and an unhashed package that is not a local path): a run of eyJ- prefixes that made the JWT pattern quadratic (2.7 seconds on 100 kB), a requirements file that is fully hashed but adds an --extra-index-url (the dependency-confusion route) or an editable install (which pip cannot hash-check), and pickles that name a profiler (cProfile.run runs a string) or a database driver. Save as test_supply_chain.py:
# test_supply_chain.py — inputs that fooled or stalled earlier versions.
# Run from the project root: python3 -m unittest test_supply_chain -v
import os
import pickle
import tempfile
import time
import unittest
from llm_guard_kit.supply_chain import (audit_requirements, audit_uv_lock, inspect_pickle,
scan_secrets)
HASH = "--hash=sha256:" + "a" * 64
def audit(text: str):
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "requirements.txt")
with open(path, "w", encoding="utf-8") as handle:
handle.write(text)
return audit_requirements(path)
LOCK_HASH = "sha256:" + "b" * 64
def audit_lock(text: str):
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "uv.lock")
with open(path, "w", encoding="utf-8") as handle:
handle.write(text)
return audit_uv_lock(path)
def package(files: str, source: str = 'registry = "https://pypi.org/simple"') -> str:
return f'[[package]]\nname = "a"\nversion = "1"\nsource = {{ {source} }}\n{files}\n'
class SupplyChainAttackTests(unittest.TestCase):
def test_a_run_of_jwt_prefixes_is_scanned_in_linear_time(self):
start = time.perf_counter()
scan_secrets("eyJ-" * 25_000) # 100 kB; the first version took 2.7 s
self.assertLess(time.perf_counter() - start, 0.5)
def test_an_extra_index_or_an_editable_install_fails_the_audit(self):
self.assertTrue(audit(f"requests==2.32.3 {HASH}\n").ok)
for option in ("--extra-index-url https://packages.example/simple",
"-e git+https://example.test/pkg.git#egg=pkg"):
self.assertFalse(audit(f"requests==2.32.3 {HASH}\n{option}\n").ok, option)
def test_a_profiler_and_a_database_driver_are_flagged_by_name(self):
import cProfile
import sqlite3
for obj in (cProfile.run, sqlite3.connect):
self.assertFalse(inspect_pickle(pickle.dumps(obj)).safe_to_load, obj)
def test_a_file_that_is_not_a_lockfile_raises_instead_of_looking_clean(self):
for text in ("", "[project]\nname = 'x'\n", "package = 'x'\n", "[[package"):
with self.assertRaises(ValueError, msg=text):
audit_lock(text)
def test_a_hash_must_be_a_real_sha256_on_every_distribution(self):
good = f'sdist = {{ url = "u", hash = "{LOCK_HASH}" }}'
self.assertEqual(audit_lock(package(good)).unhashed, [])
for files in ('sdist = { url = "u", hash = true }',
'sdist = { url = "u", hash = "sha256:abc" }',
f'{good}\nwheels = [{{ url = "w" }}]',
""):
self.assertEqual(len(audit_lock(package(files)).unhashed), 1, files)
def test_an_unhashed_package_that_is_not_a_local_path_needs_review(self):
report = audit_lock(package("", source='url = "https://example.test/a.whl"'))
self.assertEqual([p.name for p in report.needs_review], ["a"])
self.assertEqual(audit_lock(package("", source='editable = "."')).needs_review, [])
if __name__ == "__main__":
unittest.main()Run python3 -m unittest test_supply_chain -v and you get real output (Python 3.14 here; older versions word each line slightly differently, and the timing will differ):
test_a_file_that_is_not_a_lockfile_raises_instead_of_looking_clean (test_supply_chain.SupplyChainAttackTests.test_a_file_that_is_not_a_lockfile_raises_instead_of_looking_clean) ... ok
test_a_hash_must_be_a_real_sha256_on_every_distribution (test_supply_chain.SupplyChainAttackTests.test_a_hash_must_be_a_real_sha256_on_every_distribution) ... ok
test_a_profiler_and_a_database_driver_are_flagged_by_name (test_supply_chain.SupplyChainAttackTests.test_a_profiler_and_a_database_driver_are_flagged_by_name) ... ok
test_a_run_of_jwt_prefixes_is_scanned_in_linear_time (test_supply_chain.SupplyChainAttackTests.test_a_run_of_jwt_prefixes_is_scanned_in_linear_time) ... ok
test_an_extra_index_or_an_editable_install_fails_the_audit (test_supply_chain.SupplyChainAttackTests.test_an_extra_index_or_an_editable_install_fails_the_audit) ... ok
test_an_unhashed_package_that_is_not_a_local_path_needs_review (test_supply_chain.SupplyChainAttackTests.test_an_unhashed_package_that_is_not_a_local_path_needs_review) ... ok
----------------------------------------------------------------------
Ran 6 tests in 0.022s
OKWhat these tools do not catch, said plainly: scan_secrets is a tripwire for accidental secrets, so a key split with a zero-width character or base64-encoded by hand is found only by the opaque-literal pass, and a low-entropy password outside a credential-named assignment is not found at all; audit_requirements does not follow -r other.txt (audit each file) and audit_uv_lock does not say which index a registry package came from; inspect_pickle is a deny-list, so the real control remains safetensors or a sandbox.
9.2 Using these in CI (reference — not run)#
The scanners are designed to drop into a pipeline. This GitHub Actions sketch shows the pattern — review before copying, pin actions to SHAs per Part 5.3:
# .github/workflows/supply-chain.yml — REFERENCE, unrun
name: supply-chain
on: [push, pull_request]
permissions: {} # least privilege — jobs declare what they need
jobs:
secrets:
runs-on: ubuntu-latest
permissions:
contents: read # `permissions: {}` above removes even this; checkout needs it
steps:
- uses: actions/checkout@<full-length-sha> # the commit behind v7; pin to a SHA, not the tag
with:
fetch-depth: 0 # a shallow clone has no history to scan
- name: Scan the full history for secrets
# gitleaks is not preinstalled: install a pinned release binary (or use
# its official action) first. Alternative: trufflehog git file://.
run: gitleaks git --verbose .
deps:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@<full-length-sha> # the commit behind v7
- uses: astral-sh/setup-uv@<full-length-sha> # the commit behind v10.3.3
- run: uv lock --check # lockfile is current
- run: uv export --locked --no-emit-project -o requirements.txt
- name: Audit for known vulnerabilities
run: uvx pip-audit -r requirements.txt
- name: Verify hashes on every requirement
run: |
# uv export emits --hash lines; fail if any requirement lacks one
python - <<'PY'
import sys; sys.path.insert(0, "llm_guard_kit")
from supply_chain import audit_requirements
rep = audit_requirements("requirements.txt")
print(rep)
sys.exit(0 if rep.ok and rep.total else 1) # an empty file must not pass
PYThe shape: scan secrets → verify lockfile → audit vulnerabilities → verify hashes → gate the merge. Each step is a different layer from Part 5.2 — none of them is sufficient alone, which is exactly why they compose.
Part 10: Decision tables, failure gallery and the checklist#
Reference
10.1 Master decision table — attack → primary defence → residual risk#
| Threat | Where it lands | Primary defence | Residual risk you accept |
|---|---|---|---|
| Indirect prompt injection via document | RAG corpus, tool output | Injection scanning + output validation (12.2, 12.5) | Sophisticated injections still get through — hence least privilege |
| Data poisoning (targeted steering) | Knowledge base | Trust tiers + quarantine + hash-pinned curated corpora + rollback | Determined attacker with a trusted write path — shrink that path |
| Junk flooding / availability poisoning | Index | Ingest anomaly alerts + source quotas + diversity constraints | Cost of embeddings until detected — budget for it |
Metadata poisoning (acl:*, fake tier) |
Vector store fields | System-owned fields written only by pipeline; ingest validation | Bugs in your own metadata code — test it |
| Vector inversion / membership inference | Vector store | Treat vectors as sensitive; encrypt, isolate, delete with source | Research-grade attacks on small corpora — minimise what's embedded |
| Cross-tenant retrieval | Query path | ACL-in-query mandatory + isolation tests in CI | Permission-change lag — alert on revocation latency |
| Cache/memory poisoning | Response/semantic caches, agent memory | Scoped keys, no caching of flagged output, memory write validation | TTL window exposure — keep TTLs short on user-influenced data |
| Expensive-query DoS | Query path | Hard caps on k/filters/query length; per-user budgets |
Legit heavy queries throttled — tune caps with data |
| Leaked provider key | Anywhere | Scoped keys + spend limits + secret scanning + leak playbook | A live key between leak and rotation — shorten that window |
| Malicious model file (pickle RCE) | Model loading | safetensors-only policy + use_safetensors + opcode scanning + isolated load |
Legacy formats you must support — sandbox them |
| Backdoored weights | Model behaviour | Provenance + behavioural evals + isolation | Undetected trigger — red-team regularly |
trust_remote_code |
Model repo | Default off; verified org + pinned revision + code review when on | Novel architectures that genuinely need it — treat as running a package |
| Typosquat / slopsquat package | pip install |
Hash-pinned lockfiles + dep review + "does this package exist" check | A compromised legitimate package — hashes don't help; scanning + minimal deps do |
| LiteLLM-style malicious release | Installed deps | Exact pins + hashes + pip-audit/osv-scanner + short-lived creds |
0-day malicious release — rotate creds anyway |
| Compromised CI/CD | Pipeline | SHA-pinned actions, least-privilege permissions, OIDC, no pull_request_target checkout |
A compromised action you pinned — provenance/attestation helps verify |
| Vendor data access / breach | Provider | Vendor review + ZDR where offered + data minimisation + exit plan | Provider insider risk — contractual + architectural (don't send what you don't need) |
| Self-hosted runtime exposed | Ollama/vLLM/llama.cpp | Loopback bind + authenticating reverse proxy + endpoint allowlist | Misconfigured proxy — test from outside, not just inside |
| Model extraction / endpoint abuse | Public API | Rate limits + quotas + output filtering + watermarking (attribution only) | Determined well-funded extractor — raise cost, don't claim prevention |
10.2 Failure gallery — real incidents, the control that fails, the fix#
| Incident | What happened | The missing control | The fix pattern |
|---|---|---|---|
| LiteLLM 1.82.7/1.82.8 (Mar 2026) | Credential stealer — .pth file in 1.82.8, embedded in proxy_server.py in 1.82.7; live on PyPI for hours (reports range from ~40 min to ~3 h); build-time token reportedly stolen via a compromised CI action |
Unpinned deps + no install-time scanning + env-var secrets; for the publisher, a long-lived upload token reachable from CI | Hash-pinned lockfile; dependency cooldown; scoped/short-lived creds so env theft yields little; pip-audit in CI; (publishers) Trusted Publishing and SHA-pinned CI actions |
| LiteLLM 1.107.0 (Oct 2026) | Credential stealer via cook.pth on PyPI and Docker; stolen developer GitHub CLI tokens ran the real release workflow against a lookalike repository, so provenance pointed at the wrong source |
Developer CLI tokens treated as low-value; "has provenance" accepted as "is trusted" | Pin by version and image digest; dependency cooldown; verify the expected repository and workflow identity, not just that an attestation exists; scope and rotate developer tokens; delete stray .pth files, not just the package |
| JFrog ~100 malicious HF models (early 2024) | Pickle __reduce__ payloads → RCE on load |
torch.load/pickle on untrusted weights |
safetensors-only; weights_only=True default since PyTorch 2.6 (watch for weights_only=False); opcode scanning; isolated loading |
| ReversingLabs nullifAI (Feb 2025) | Corrupt pickle evading HF detection | Trusting hub scanning alone | Scanner-in-your-CI (modelscan/picklescan/your own inspect_pickle); provenance review |
| HiddenLayer Silent Sabotage | Compromised conversion bot → malicious PRs impersonating HF | Trusting ecosystem tooling | Pin + verify conversion/serving tools; signed commits awareness; least-privilege tokens for bots |
| PoisonedRAG (USENIX '25) | 5 crafted docs → ~90% targeted-answer success | Untrusted corpus write path + no trust tiers | Source allowlists, quarantine, trust labels in query, rollback |
| Sleeper Agents (Anthropic '24) | Backdoors persist through safety training | "Safety-tuned" as an assumption | Behavioural evals; provenance distance as risk metric; don't trust, verify |
| Slopsquatting (USENIX '25) | 19.7% hallucinated package recommendations; attackers register them | Paste-installing LLM suggestions | Verify package exists + maintained + in approved list; minimal deps |
| TruffleHog-style verified scanning | Scanner sends found secrets to provider APIs to check if live | Running verification scanners carelessly | Run in controlled env; remember the scanner itself handles secrets |
| Ollama/vLLM exposed | Inference port on public internet, no auth | Assuming "local" stays local | Loopback bind + authenticating proxy; verify --api-key coverage (vLLM's is partial) |
GitHub pull_request_target |
Privileged workflow checks out untrusted code → secret theft | Misunderstanding trigger trust model | Never checkout untrusted code in privileged triggers; GitHub will block by default in public repos from 2 Dec 2026 (announced Nov 2026) |
10.3 The supply-chain hardening checklist#
The one-page version — print it, tape it to the wall:
Data chain
- Every document has
source_tier+ lineage; system fields pipeline-owned only - Untrusted sources quarantined + injection-scanned before indexing
- Curated corpora hash-pinned; every ingest batch retractable
- ACL-in-query on every retrieval path; isolation tests in CI
- Vector DB isolated, authenticated, audited; vectors treated as sensitive
- Caches scoped by permission + version; flagged output never cached
- Agent memory writes validated; deletion propagates everywhere
- Ingest anomaly alerts + canary documents per trust tier
Credential chain
- Keys in secret manager/OIDC — never in code, images, prompts, logs
- Per-env + per-service keys; project/workspace scoped where offered
- Spend limits + alerts configured at provider (hard cap + warning)
- Secret scanning: pre-commit + CI (history) + periodic sweeps
- GitHub secret scanning + push protection where applicable
- Leak-response playbook written and rehearsed
Code & model chain
-
uv.lock/hashed requirements enforced;pip-audit/osv-scannerin CI - Minimal deps; new deps reviewed (maintainer, activity, install behaviour); dependency cooldown (
exclude-newer, Dependabotcooldown, RenovateminimumReleaseAge) configured - CI security tools and actions pinned by commit SHA; the job that runs them holds no publish credentials; developer CLI tokens scoped and rotated
- SBOM generated in CI; images scanned + signed
- Models: safetensors-only where possible; pinned revisions; hashed manifest; signatures verified where the publisher offers them (OpenSSF Model Signing/Sigstore — most public Hub repos are unsigned, so hash-pinning + provenance review remains the practical control); scanned before load;
trust_remote_codeoff by default - Third-party models get behavioural smoke evals before production
- MCP servers/plugins vetted like packages — provenance + permissions + code
Vendor & infra chain
- Vendor security review done (certs, subprocessors, ZDR terms, exit plan)
- Private endpoints where offered; egress allowlisted; AI tier segmented
- Self-hosted runtimes behind authenticating proxy; loopback by default
- Containers hardened; images signed; CI uses OIDC not stored cloud keys
- Watermarking understood as provenance signal, not a control
Common misconceptions#
| Misconception | Reality |
|---|---|
"A .env in .gitignore keeps secrets safe" |
.gitignore stops accidents, not git add -f, force-pushes, or secrets in other files — you need scanning |
| "Deleting the key from the repo fixes the leak" | Git history, clones, forks and CI caches keep it — rotate first, clean history second (and history rewriting is housekeeping, not the fix) |
| "The provider says they don't train on our data" | True per-tier and per-endpoint — free tiers, abuse review and ZDR-eligible endpoints differ; get it in writing for the exact API paths you call |
"safetensors makes a model safe" |
It makes the format safe (no code execution) — a safetensors file can still contain a backdoored model; provenance + behavioural evals still required |
| "A signed or attested package is a safe package" | Provenance says which pipeline built it from which source — the October 2026 LiteLLM release carried genuine build provenance for the wrong source. Verify the expected repository and workflow, and keep cooldowns, hashes and scanning |
| "Hash-pinned lockfiles prove packages are safe" | They prove packages are unchanged — a compromised release gets hashed too; integrity ≠ safety |
"pip-audit/osv-scanner catch malicious packages" |
They catch known CVEs — a brand-new malicious release has no advisory yet; they're one layer, not the defence |
| "Scanners catch all secrets" | Entropy heuristics miss low-entropy keys and obscure formats; known-pattern lists miss new providers — scan with multiple tools and accept residual risk |
| "The vector DB is just an index" | It's a second copy of your corpus with its own access surface — whoever queries it directly bypasses your ACL layer entirely |
| "Watermarking prevents abuse/theft" | Watermarks provide provenance (attribution), not prevention — they degrade under editing and can't be an access control |
| "Private endpoint = encrypted" | Private endpoints provide network isolation; encryption is separate — you need both, and they solve different problems |
| "An env var is a safe place for a key" | Env vars are visible in /proc, docker inspect, crash dumps and child processes — they're convenient, not secure; scope and rotate accordingly |
"trust_remote_code=True is fine for popular models" |
It's executing arbitrary Python from a repo you didn't audit — HF itself warns to verify contents and pin revisions; default should be off |
| "Model cards are audited claims" | They're author claims — benchmarks, intended use, training data hints; treat as marketing until independently evaluated |
| "One provider is fine" | Vendor risk is concentration risk — a breach, deprecation, price change or geopolitical event becomes your outage; keep an approved-provider list |
Key takeaways#
- Three supply chains converge on every LLM app: data (corpus, vectors, caches, memory), credentials (provider keys, secrets), and code/models (dependencies, weights, vendors). You can't make them safe — you make them bounded: smaller blast radius, faster detection, cleaner rollback.
- The corpus is an attack surface. PoisonedRAG showed ~90% targeted-answer success with five crafted documents; your defences are trust tiers, quarantine, hash-pinned curated corpora, ACL-in-query, anomaly detection, canary documents and versioned-index rollback — not "the model will ignore weird docs".
- A leaked key is a billing incident waiting to happen. Scope keys per env/service/project, set spend limits at every layer, scan for secrets in pre-commit + CI history + periodic sweeps, and rehearse the leak playbook: rotate first, investigate second.
- Keep the key in a secret manager, fetch it by name at runtime. AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault and HashiCorp Vault all give per-workload access, versions and an audit log; cache the value briefly, refetch once on
401for rotation, mask it in logs, and never pass the value through a prompt or a tool argument (3.6). - Model files are programs in data formats.
pickleexecutes on load;safetensorsdoesn't. Pin revisions, hash manifests, scan before load (modelscan/picklescan/your own opcode inspector), keeptrust_remote_codeoff, and load anything legacy in isolation. - Your dependencies are strangers' code with your secrets in env. Hash-pinned lockfiles (
uv.lock,--require-hashes),pip-audit/osv-scannerin CI, minimal deps, SBOMs, signed images, SHA-pinned actions, OIDC instead of stored cloud keys — and never paste-install an LLM's package suggestion (slopsquatting is real: 19.7% of recommendations were hallucinated in the USENIX study). - Two LiteLLM compromises in 2026 (March and October) are the template. Both delivered a credential stealer through a trusted package name and a
.pthfile that runs on every interpreter start. The defences that would have mattered: exact pins with hashes, a dependency cooldown, scoped short-lived credentials, SHA-pinned CI tooling, and verifying who an attestation says built the artefact. - Vendor risk is architectural. Review security posture, get data terms in writing per endpoint, use private connectivity where offered, plan your exit — and remember watermarks are provenance signals, not security controls.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Data poisoning | Corrupting a knowledge base or training corpus so a system produces wrong, leaky or steered outputs without touching the model or prompt |
| Denial-of-wallet | An attack where the goal is not to crash a service but to make it expensive — typically via a leaked API key or unbounded agent loop running up provider bills |
| Canary document | A document planted in a corpus containing a unique canary string; if the string appears in an output, log or trace, it signals unauthorised retrieval or exfiltration |
| Canary token (honeytoken) | A decoy credential planted where an attacker might find secrets; any use of it is unambiguous proof of scanning or theft |
| Secret manager | A service that stores secrets encrypted, grants access per workload, versions them and logs every read (AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault, HashiCorp Vault) |
| Runtime secret fetch | Reading a secret from the store when the process needs it (cached briefly, refetched on 401) instead of baking it into code, an image or a prompt |
| Masked secret | A wrapper type whose repr and str print stars, so logging or printing it cannot leak the value |
| Slopsquatting | Registering a package name that an LLM hallucinated in generated code, so the next developer who pastes the suggestion installs attacker-controlled code |
| Model file format risk | The security property that pickle-based model files execute arbitrary code on load while safetensors is data-only — the format determines whether "loading a model" means "reading numbers" or "running code" |
| Weight-level backdoor | A model whose weights were trained or fine-tuned to behave differently on trigger inputs — no code execution required, and persistent through standard safety training |
| SBOM (Software Bill of Materials) | A machine-readable inventory of every component in a software artefact — libraries, frameworks, models, datasets — so you can answer "are we affected?" when a vulnerability or compromise is disclosed |
| AI-BOM / ML-BOM | An SBOM extension covering AI-specific components: model architecture, training data provenance, datasets, evaluation metrics and ethical considerations — formalised in CycloneDX ML-BOM and SPDX 3.0 AI/Dataset profiles |
| Dependency cooldown | A resolver or bot setting that ignores releases newer than N days (uv exclude-newer, pip --uploaded-prior-to, Dependabot cooldown, Renovate minimumReleaseAge) so a malicious upload is usually yanked before you can install it; it buys time, it does not detect malware |
.pth file |
A text file in site-packages whose import lines Python executes at every interpreter start — a legitimate packaging feature that both 2026 LiteLLM payloads abused, so uninstalling the package may not remove it |
| Trusted Publishing / attestation | PyPI's keyless publishing from a CI identity (OIDC) and the signed statement (PEP 740) recording which workflow published a file — evidence of origin, not of safety |
| SLSA (Supply-chain Levels for Software Artifacts) | An OpenSSF framework defining progressive assurance levels for software artefacts — from documented build processes to hermetic builds with verified provenance — used to evaluate how much you can trust an artefact's origin |
| NIST SSDF | The NIST Secure Software Development Framework (SP 800-218) — secure development practices covering preparation, software protection, secure production and vulnerability response; SP 800-218A extends it to generative AI |
| Workload identity federation | A keyless authentication pattern where a CI/CD platform (e.g., GitHub Actions) mints a short-lived OIDC token that a cloud provider exchanges for temporary credentials — eliminating stored long-lived secrets |
| Push protection | A GitHub secret-scanning feature that blocks pushes containing supported secret patterns before they reach the repository — prevention rather than after-the-fact alerting |
| Zero data retention (ZDR) | A provider arrangement where prompts and responses are not retained after processing — offered per-endpoint and per-tier by some providers, and enforceable via guardrails on aggregation layers like OpenRouter |
| Private endpoint / PrivateLink | Cloud networking that keeps traffic to a service on the provider's private backbone — AWS VPC endpoints for Bedrock, Azure private endpoints for OpenAI, Vertex Private Service Connect — so model API calls never traverse the public internet |
| Model extraction | Stealing a model's functionality by systematically querying its prediction API — practical for classical ML models, expensive and approximate for frontier LLMs, but a real threat for smaller/self-hosted models and for distillation at scale |
| Text watermarking / SynthID / textGrain | Techniques that embed invisible statistical signals in generated text (or images/audio) to signal AI provenance — OpenAI's textGrain and Google's SynthID — useful for attribution and compliance, not for preventing abuse or theft |
| OpenSSF Model Signing (OMS) | An implementation-agnostic spec for cryptographically signing a whole model bundle — weights, config, tokenizer — as one manifest of file hashes under a single signature, carried in the Sigstore bundle format |
Exercises#
No keys, no services, no GPU required — everything runs locally.
-
Run the scanner on your own history. Install
gitleaks(brew install gitleaksor download from gitleaks.io) and rungitleaks giton a repo you've worked in. Compare its findings to runningpython -m llm_guard_kit.supply_chain app.log .env.example(after saving the file — file arguments switch the module from demo mode into scan mode) on a log file or.env.example. What did each catch that the other missed? What are the false-positive rates? -
Audit a real lockfile. Create a
uvproject (uv init), add a few deps (uv add requests pydantic), runuv lock, then runaudit_uv_lock("uv.lock")from Part 9. Verify every registry package showshash=yes. Then edituv.lockto remove one package'ssdisthash and re-run — does it flag it? -
Requirements hash audit. Generate a
requirements.txtwithuv pip compile pyproject.toml --generate-hashes -o requirements.txt, runaudit_requirementson it (should PASS), then remove one--hashline and re-run (should FAIL). This is the CI gate from Part 9.2 in miniature. -
Pickle inspection. Write a Python script that creates a benign pickle (
pickle.dumps({"a": 1})), then hand-craft a malicious one using the protocol-0 format from_demo_pickle_flagged. Runinspect_pickleon both. Now trypickle.loadson the malicious one in a subprocess (it will executeecho) — understand viscerally why the inspector exists. (Do this only on your own machine, only with theechopayload — never with anything that touches real systems.) -
Tabletop: the leaked key. Write a one-page incident-response plan for "an OpenAI key was committed to a public repo 6 hours ago" using the playbook in 3.5. Include: who rotates, what logs to pull, what to check for data exposure, who to notify, and what permanent controls to add. Compare with a partner's plan — where do they differ?
-
Vendor review. Pick one provider you use (or plan to). Fill in the 6.1 checklist: find their security page, check for SOC 2/ISO reports, look at their subprocessors list, find their data-retention terms per endpoint. What's missing or unclear?
-
Dependency review drill. Pick a package you depend on. Check: last release date, maintainer count, open security issues, install-time behaviour (
pip installrunssetup.py— does it?). Would you bet your infra on their next release? -
Try a cooldown (no keys). In a scratch
uv initproject add[tool.uv]/exclude-newer = "1 week"topyproject.toml, runuv add requests, then openuv.lockand find the recorded cut-off timestamp. Change the value to"1 hour", runuv lock --upgrade, and note what moves. Then answer: what would the setting have done for someone who resolvedlitellmat 11:00 UTC on 24 March 2026, and what would it not have done for someone with an exact pin on one of the two malicious releases? (Hint: a one-week window would have excluded both malicious releases; an exact pin bypasses the window.) -
The "three chains" map. Draw your own app's three supply chains (data/credentials/code) as a Mermaid diagram like Part 1.1. For each arrow, ask: "what's the worst thing that could flow through here?" Where are your trust boundaries actually enforced — in code, in config, or in someone's head?
Check yourself#
- Why is a RAG corpus a "supply chain"?Because documents arrive from sources you don't control and get embedded into a store that can be attacked at ingest, at query time, and inside caches/memory — the same "consume artefacts you didn't produce" problem as software dependencies.
- What did PoisonedRAG demonstrate?That ~5 crafted documents per target question could achieve ~90% attack success at making a RAG system emit attacker-chosen answers — and that common defences (paraphrase filters, perplexity detection) were insufficient.
- What's the difference between
pickleandsafetensorsmodel files?Pickle executes arbitrary code on load (__reduce__can callos.system); safetensors is a data-only format designed to prevent code execution.use_safetensors=Truein transformers errors rather than falling back to pickle. - What is
trust_remote_codeand why is it dangerous?It tells transformers to download and execute Python modelling files from the model repo — arbitrary code from a stranger's repository running with your credentials in env. HF recommends verifying contents and pinning revisions; default should be off. - Name three ways a provider API key typically leaks.Git history (committed then "removed"), logs/traces (printed or captured by observability), client bundles (shipped to browser/mobile). Also: CI logs, screenshots, notebooks, dependency configs, core dumps.
- What's the first step in the leak-response playbook and why?Revoke or rotate the key before investigating — a leaked key is assumed compromised; every minute it stays live is billable risk. Investigation comes second.
- What does
--require-hashesdo in pip?Refuses to install any requirement that lacks a--hash=sha256:entry — verifies the downloaded artefact matches the recorded hash, detecting tampering even if the version number is unchanged. - What does
uv.lockrecord thatrequirements.txtdoesn't?SHA-256 hashes for every distribution's sdist and wheels by default, plus universal resolution across platforms —requirements.txtneeds explicit--generate-hashes. - What is slopsquatting and why is it AI-specific?Registering package names that LLMs hallucinate in generated code — the model suggests
import fake-vector-db, the attacker registers it on PyPI, the next dev who paste-installs gets malware. USENIX '25 found 19.7% of recommendations were hallucinated. - What's the difference between SLSA and NIST SSDF?SLSA is a technical framework for artefact provenance and build integrity (levels of assurance); SSDF is a broader organisational practice framework for secure development lifecycle. They complement each other.
- Why is
pull_request_targetdangerous?It runs with base-repo secrets and write tokens — if you check out untrusted PR code, you've handed secrets to a stranger. GitHub will begin blocking it by default in public repositories on 2 December 2026 (announced 2 November 2026; enforcement had previously been scheduled for 2 November, and brownout windows run on 9 and 16 November). - What can you do about model extraction?Rate limits, per-user quotas, output filtering, withholding logprobs, ToS + monitoring — raise the attacker's cost. You cannot prevent it entirely; for frontier LLMs it's expensive and approximate anyway.
- What do watermarks (textGrain, SynthID) actually provide?Provenance/attribution — "this output came from a watermarked model." They do NOT prevent extraction, abuse, or theft, and they degrade under editing. They're one signal, not a security boundary.
- Why does vLLM's
--api-keynot fully secure it?It only protects the/v1,/v2,/inferenceand/coherepath prefixes —/invocations,/tokenize,/metricsand operational-control endpoints such as/pauseon the same server are unauthenticated (as of November 2026). You need a reverse proxy that allow-lists the endpoints you mean to expose. - What is a dependency cooldown, and name two things it does not protect against.A resolver/bot setting that skips releases newer than N days so a fresh malicious upload is likely yanked before you take it. It does not detect malware, does not help against an exact pin you already hold or code you already run, does not stop install-time code in a version old enough to pass the window, and needs the index to publish upload times.
- What did the October 2026 LiteLLM 1.107.0 incident show about build provenance?That provenance proves which pipeline built the artefact from which source, not that the source is trusted: stolen developer tokens ran the legitimate release workflow against a lookalike repository, so the artefacts carried provenance for the wrong repository. Verify the expected repository and workflow identity, and keep layered controls (cooldown, hashes, scoped credentials).
Further resources#
This lesson's sources (all verified as of November 2026):
- OWASP GenAI/LLM Top 10 2026 — genai.owasp.org/resource/owasp-genai-llm-top-10-2026/ and github.com/GenAI-Security-Project/GenAI-LLM-Top10
- PoisonedRAG — arXiv:2402.07867 (USENIX Security 2025)
- Sleeper Agents — arXiv:2401.05566 (Anthropic, Jan 2024)
- Package hallucination / slopsquatting — arXiv:2406.10279 (USENIX Security 2025); 2026 follow-up arXiv:2605.17062
- Model extraction — arXiv:1609.02943 (USENIX Security 2016)
- Embedding inversion — arXiv:2310.06816 (EMNLP 2023)
- Hugging Face security — transformers security policy, pickle scanning, JFrog scanner, Azure eligibility
- Malicious model incidents — JFrog research (Feb 2024), BleepingComputer, Dark Reading, Ars Technica, ReversingLabs nullifAI, HiddenLayer Silent Sabotage
- LiteLLM incidents — March: docs.litellm.ai/blog/security-update-march-2026, StepSecurity payload analysis, Snyk root-cause timeline, Wiz on the Trivy compromise; October (1.107.0): Datadog Security Labs, The Hacker News
- Dependency cooldowns and attestations — uv resolution, pip install options, Dependabot options reference, pydevtools on cooldowns, PyPI attestations, GitHub artifact attestations
- Provider key controls — OpenAI spend limits, OpenAI projects/keys, Anthropic workspaces, Anthropic auth, Gemini API keys, GCP API key restrictions, OpenRouter auth, OpenRouter guardrails, OpenRouter management keys
- Secret scanning tools — gitleaks.io, trufflehog, detect-secrets, GitHub secret scanning, GitHub push protection
- Dependency security — uv locking, pip-audit, osv-scanner, modelscan, picklescan
- Supply-chain frameworks — SLSA, NIST SSDF, CycloneDX ML-BOM, SPDX AI profiles, Sigstore/cosign, GitHub Artifact Attestations, OpenSSF Model Signing, sigstore/model-transparency, NVIDIA NGC model signing
- CI/CD security — GitHub Actions security, securely using pull_request_target, pull_request_target default block changelog, OIDC in cloud providers
- Private connectivity — AWS Bedrock VPC endpoints, OpenAI Private Link, Vertex PSC
- Self-hosted runtimes — Ollama auth, vLLM security
- Watermarking — OpenAI provenance, OpenAI provenance signals, Google SynthID, SynthID Detector, SynthID Text
Earlier lessons this builds on: 12.1 Threat modelling · 12.2 Prompt injection · 12.5 Guardrails · 12.6 Tools, agents and MCP · 12.8 Red teaming · 12.9 Responsible AI · 12.10 Security operations
← 12.6 — Securing Tools, Agents and MCP | Module 12 overview | 12.8 — Red Teaming and Security Testing →