Orchestrate

Report an issue

Something wrong, out of date or unclear? Tell us. Corrections are prioritized over new topics. You don't need to sign in.

0 / 2000

Don't include personal or confidential company details. Reports are reviewed with AI assistance.

AI supply-chain controls after the LiteLLM compromises

Pin, hash and delay the packages your AI services install, know where each runs, and be ready to rotate secrets, with LiteLLM's 2026 compromises as the case.

Updated Nov 23, 2026
Foundational layer · 8 min read

The 60-second version

An AI service is mostly other people's code. A typical Python agent or gateway installs dozens of open-source packages, and each one runs with the service's passwords and keys within reach. Whoever controls a package release controls part of your system.

In 2026 that stopped being theory for one of the most used AI libraries. LiteLLM, an open-source gateway that many teams use to reach model providers, including SAP's generative AI hub, had two malicious releases on PyPI, the public Python package index:

  • March: versions 1.82.7 and 1.82.8 stole credentials from any machine that installed them (LiteLLM, 24 March).
  • October: version 1.107.0 did the same, and this time the project's official Docker images carried it too. It was on PyPI from 11:39 to about 13:23 UTC on 21 October 2026 (LiteLLM incident report).

The October release was validly signed and published through the project's normal release identity (attack chain). Checking signatures would not have stopped it. What did protect teams was dull: they installed a fixed version they had already tested, and they didn't take a release on its first day.

This topic turns that into five controls you can check: pin exact versions, hash them so the files can't change, wait before taking new releases, know where each package runs, and be ready to rotate every secret a bad release could read.

Why it matters to the business

Take Calder Pumpworks, the fictional pump maker this course follows. Its AI platform team runs calder-ai-gw, a LiteLLM proxy in front of SAP's generative AI hub. Calder's invoice-triage and order-exceptions agents call models through it. To do that, the gateway holds Calder's SAP AI Core service key, the gateway's own admin key and the password of the database where it keeps the agents' keys.

The gateway's build file says "install LiteLLM", with no version. On 21 October at 12:05 UTC a routine rebuild ran. It picked up the newest release, 1.107.0, and deployed it to quality and production at 12:20. By 16:10 a later rebuild had replaced it with a clean version. Nobody noticed in between.

Four hours of a bad release cost Calder far more than four hours:

  • Every secret on those machines has to be treated as stolen. That means the AI Core service keys for both environments, the gateway's admin and agent keys, its database password and the token the build used to push images. Each rotation has an owner, a change window and a test.
  • Stolen model credentials cost money. LiteLLM's incident report tells affected teams to check their cloud logs for use of the machine's credentials from outside their own infrastructure. A stolen AI Core key can run models on Calder's bill in the same way.
  • The first question is "where do we run it?" If nobody can list which services use LiteLLM and in which version, the response stalls while people search repositories.

Now the other side. If the gateway had installed a pinned, already-tested version, the rebuild at 12:05 would have installed that same version again. Nothing would have needed rotating.

How SAP does it

None of the SAP pages read for this topic offers a supply-chain scanner for your own Python services. Your packages are your responsibility, just as your code is. What SAP does provide, as of November 2026:

  • Two ways to reach the generative AI hub from Python. The SAP Cloud SDK for AI is one. LiteLLM is the other, and a set of examples published under SAP's sap-contributions GitHub organization shows agent frameworks reaching the hub through a LiteLLM proxy. Its proxy setup guide installs litellm[proxy] without a version and passes the AI Core client ID and secret as environment variables. That is fine for a first run. Pin it before anything real depends on it.
  • A place for secrets, and a rule to rotate them. SAP's reference architecture for third-party MCP access (updated 26 October 2026) says to keep API keys and client secrets in a dedicated store such as SAP Credential Store, rotate them regularly, and never keep long-lived credentials in MCP servers.
  • Rotation you can automate. On SAP BTP's Kubernetes runtime, the SAP BTP service operator can rotate service binding credentials on a schedule, or at once when you ask.

The five controls, replayed on 21 October

Control What it means What it would have done for Calder
Pin Install exact versions you chose, never "latest" The 12:05 rebuild installs the tested version again; 1.107.0 never arrives
Hash Record a fingerprint of each file; refuse any file that differs Even a replaced file under a trusted version number is refused
Wait Take a release only after it has been public for some days A 7-day wait skips 1.107.0 entirely; it was gone within two hours
Know where Keep a parts list (SBOM) for every service "Which services run LiteLLM, which version?" is answered in a minute
Be ready to rotate List each secret, where it lives, who owns it The rotation list for the affected machines exists before the incident

The first three keep bad code out. The last two decide how bad the day is when something gets in anyway. You need both halves: no control on this list catches a release that is malicious from its first minute and stays undetected for weeks.

Questions to ask

Ask your team:

  • Which of our services install Python packages without an exact version? Which container images do we pull by tag?
  • How long after a release do we install it? Who can approve an urgent exception, and how is it recorded?
  • If a package advisory lands this afternoon, how long until we know every service, environment and version that runs it?
  • For each AI service: which secrets are on its machines, who owns each one, and when was it last rotated?

Ask a vendor or partner who builds or hosts an AI service for you:

  • Do you install from a locked, hashed set of dependencies? Can we see the parts list (SBOM) for each release?
  • How quickly did you check your exposure to the LiteLLM releases in March and October 2026, and what did you find?
  • Which of our credentials sit on your machines, and how fast can you help us rotate them?

Common misconceptions

  • "A signed release is a safe release." LiteLLM 1.107.0 was signed with the project's key and uploaded through its normal publishing identity. A signature proves who released it, not that the code is what the project intended.
  • "We use the official Docker image, so we're covered." In March that was true, because the image pinned its dependencies. In October the official images themselves were affected.
  • "Upgrading to the fixed version cleans it up." The malicious code may already have run and sent your secrets away. Rebuild the environment from scratch and rotate what it could read.
  • "Pin once and you're done." Old pins collect known vulnerabilities. Pinning controls when you change; you still have to change, on purpose and on a schedule.
  • "An SBOM is paperwork for auditors." On the day of an advisory it is the fastest way to find where you are exposed.

Key terms

All course terms, A to Z, in the glossary

  • Supply-chain attack: malicious code delivered through a package, image or update you install and trust.
  • Pin: naming the exact version to install, such as litellm==1.106.2.
  • Hash (of a file): a fingerprint of a file's exact bytes. Any change gives a different hash.
  • Lock file: a file that lists every package an app installs, including indirect ones, with exact versions and usually hashes.
  • Cooldown: a rule to install only releases that have been public for some days.
  • SBOM (software bill of materials): a machine-readable parts list of the software in a service.
  • Credential rotation: replacing a secret with a new one and retiring the old one.
  • Blast radius: everything a compromised component could reach, such as the secrets on the same machine.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1LiteLLM 1.107.0 was signed with the project's key and published through its normal release identity. What should a leader take from that?

Answer: A. The October release passed signature and publishing checks because attackers used the project's own release pipeline. Signatures still help against other attacks, but they don't replace pinning and waiting.

2Calder's gateway build installs "the newest LiteLLM" on every rebuild. Which change would have kept 1.107.0 out on 21 October?

Answer: C. A pinned version installs the same tested code on every rebuild, so a new malicious release never arrives. More frequent rebuilds or the latest image tag would have pulled 1.107.0 sooner.

3A bad release ran on two of your servers for four hours and has since been replaced. What does the response need first?

Answer: B. The malicious code may already have sent the secrets away, so replacing the code is not enough. Rotation needs an inventory of secrets per machine and an owner for each.

4Why does waiting several days before taking a new release help so much?

Answer: A. Both LiteLLM releases were pulled from PyPI within hours. A cooldown lets that discovery happen before your build installs the release, at the cost of taking real fixes a little later.

5An advisory names a package this afternoon. Which control lets you say within minutes which services run it?

Answer: A. An SBOM is the parts list per service and version, so searching it answers "where do we run it?" The other controls matter, but none of them tells you where a package is installed.

6A partner says their AI service uses the official LiteLLM Docker image, so they were safe from both 2026 incidents. How do you respond?

Answer: B. The official image was safe in March because it pinned its dependencies, but in October the project's own images carried 1.107.0. The right follow-up is which images and tags they ran on 21 October.
Deep layer · 40 min read

Mental model: you can't prove a package is safe, so control when it enters and what it can reach

You will never read every line of every dependency. Neither will anyone else, which is why both LiteLLM releases worked. What you can control is narrower and more useful:

  1. Admission: when new code enters, and exactly which bytes. An exact pin decides the version. A hash decides the files. A cooldown decides how old a release must be before it is eligible. Together they mean a rebuild never installs anything you haven't chosen.
  2. Inventory: where everything runs. An SBOM per build and a build log tell you which services, environments and hosts had a given version, and when.
  3. Containment and recovery: what a bad release can steal, and how fast you replace it. Fewer secrets per machine, short-lived where possible, each with an owner and a tested rotation path. And a rebuild from scratch, never a repair in place.

Controls in group 1 make incidents rarer. Groups 2 and 3 decide how long and how expensive the incident is. A supply-chain plan that has only group 1 fails on the first release that is malicious for longer than your cooldown.

How it works

Two incidents, two routes in

March 2026. LiteLLM believes the compromise came from Trivy, a security scanner its CI pipeline used, which had itself been compromised; it called that root cause unconfirmed. The attacker bypassed the project's official release workflow and uploaded 1.82.7 and 1.82.8 directly to PyPI on 24 March, from 10:39 UTC (LiteLLM, March). The payload collected environment variables, SSH keys, cloud and Kubernetes credentials and database passwords. The official proxy Docker image wasn't affected because it installed pinned dependencies.

October 2026. This time the attacker didn't need an upload credential. The attack chain runs like this:

flowchart LR
  K[Admin key for an<br/>experimental agent platform<br/>public since May] --> T[Owner's GitHub<br/>CLI token]
  T --> S[CI secrets and<br/>maintainers' tokens]
  S --> R[Release workflow<br/>pointed at a<br/>lookalike repo]
  R --> P[Signed 1.107.0 on<br/>PyPI, Docker Hub, GHCR]
  P --> V[Victims' builds<br/>install it]

An admin key for an experimental LiteLLM project was committed to a public repository in May and never revoked. In October it returned a GitHub token belonging to the organization's owner. From there the attacker collected CI secrets and maintainers' tokens. One token triggered the release workflow, pointed at a lookalike repository; another approved it. The workflow built, signed and published 1.107.0. LiteLLM's incident report adds that the normal release flow publishes through Trusted Publishing and that the bad images carry a valid signature from the project's cosign key.

Read that again as a defender. Every check that asks "did the right pipeline publish this?" said yes. The October controls that worked were all on the consumer's side.

What the payload did

The October wheels added three files to the Python environment: cook.pth, cook.py and sitecustomize.py. Python runs .pth files with an import line, and sitecustomize, every time the interpreter starts, not only when you import the package. So any Python process in that environment ran the stealer: the gateway itself, a test command, a one-off script (LiteLLM incident report).

The report's remediation list shows what that reaches: the machine's cloud role, every provider key stored in the gateway's database, the gateway's master and virtual keys, the database password, and every secret in the environment of any process on the host. Its advice is also the method: delete the dropped files before running pip again, rebuild from scratch rather than repair, and if the host had outbound internet access, assume the secrets left.

Pins, hashes and source builds

pip, by default, does no check against tampering (pip, Secure installs). Three switches change that:

  • An exact pin (==) fixes the version.
  • A hash fixes the file. Adding --hash=sha256:... to any requirement turns on hash-checking mode for the whole install. Then every requirement, including every indirect dependency, needs an == pin and a hash, or pip refuses. You can force the mode with --require-hashes.
  • --only-binary :all: refuses source distributions. pip's own guidance recommends it next to hashes. A source distribution runs build code on your machine during install. It also gives pip a second file to fall back to: a lock usually lists the hash of the wheel and of the source archive, and without this switch pip may accept the other file.

A hand-written requirements file can't do this; nobody types hashes for 150 transitive dependencies. A lock tool generates them. In this topic that is pip-compile from pip-tools; Python projects done right showed uv.lock, which records hashes as well.

Cooldowns: let someone else find it first

Both malicious LiteLLM releases were removed within hours. A cooldown says "only consider releases older than N days", so your build sleeps through the dangerous window. pip supports it directly: --uploaded-prior-to arrived in pip 26.0, and from pip 26.1 it accepts a duration such as P7D for seven days (pip changelog). It works where the index reports upload times, as PyPI does.

The cost is real: a genuine security fix also waits N days. That's why a cooldown needs a documented exception path, used by a named person, for urgent fixes.

What publishing identity does and doesn't prove

PyPI's Trusted Publishing replaces long-lived upload tokens with short-lived ones, issued to a specific CI workflow and expiring within 15 minutes (PyPI security model). That closes the route of a stolen long-lived upload token. PyPI's own page states the limit: it does not assert the safety of the code, and you should treat a Trusted Publisher as if it were an API token, because anyone who can change the workflow can publish. October is that case.

So verify provenance where you can, but don't let it replace pins, hashes and a cooldown.

Knowing where: SBOMs and advisories

An SBOM lists every component in a build, with name, version and a package URL (purl) such as pkg:pypi/litellm@1.106.2. The common formats are CycloneDX and SPDX; this topic uses CycloneDX JSON, produced by the cyclonedx-py tool. Keep one per build, next to the image, and you can answer "where does 1.107.0 run?" by searching files instead of people.

Known-bad versions are published as advisories. OSV, an open vulnerability database, carries malicious releases with MAL- identifiers. MAL-2026-2144 covers all three bad LiteLLM versions: 1.82.7, 1.82.8 and 1.107.0. pip-audit, which the Unit 11 setup installed, checks pinned versions against advisory data and exits with an error when it finds something, so a pipeline can stop on it.

Images: tags move, digests don't

A container tag such as latest or main-stable is a movable label. In October, LiteLLM's latest, main-latest and main-stable tags on Docker Hub pointed at the bad image until 14:20 UTC. A digest (image@sha256:...) names exact content and can't be repointed. Pull base images and third-party images by digest, and record the digest you tested.

Rotation: the half nobody rehearses

Rotation is only fast if three things exist before the incident: a list of secrets per host, an owner for each, and a tested way to replace each without an outage. SAP's guidance points the same way: keep secrets in a dedicated store such as SAP Credential Store and rotate regularly (SAP Architecture Center). Where a secret can be short-lived or exchanged per call, it is less worth stealing.

Build it yourself: replay 21 October and lock down your course folder

Before you start Complete Set up your computer for this course and Set up for Unit 11. Python projects done right explains lock files; this lab adds hashes, a cooldown, an SBOM and a rotation list.

You will run a small checker against Calder's gateway as it stood on 21 October, see exactly which builds installed the bad release and which secrets must be rotated, then check the fixed version. Then you'll do the same to your own course folder: compile a hashed lock with a seven-day cooldown, install from it, watch pip refuse a tampered file, write an SBOM and audit it.

flowchart LR
  IN[requirements.in<br/>what you want] -->|pip-compile<br/>hashes, 7-day cooldown| LOCK[requirements.lock]
  LOCK -->|pip --require-hashes| ENV[.venv]
  ENV -->|cyclonedx-py| SBOM[course.cdx.json]
  LOCK --> CHK[supply_chain_check.py]
  SBOM --> CHK
  LOCK -->|pip-audit| ADV[advisory data]

What you need

  • Your course folder orchestrate-course with its .venv, from the setup topics. Python 3.10 or newer.
  • pip 26.3 (Step 2 installs it), pip-tools 7.6.2, cyclonedx-bom 8.0.1 and pip-audit 2.10.1. These are deliberately not the newest releases: on 21 November 2026 the newest pip-tools and cyclonedx-bom were younger than this topic's own seven-day cooldown.
  • Internet access to PyPI for Steps 2 and 7 to 12. Steps 4 to 6 run offline.
  • About 40 minutes. Cost: free. No account.

Step 1: Open your course folder and turn on the virtual environment

  1. Open VS Code, choose File > Open Folder, and open orchestrate-course.

  2. Open a terminal: Terminal > New Terminal.

  3. Turn on the virtual environment if the prompt doesn't start with (.venv):

    • Windows (PowerShell):

      .venv\Scripts\Activate.ps1
    • macOS / Linux:

      source .venv/bin/activate

Run every command in this topic from the course folder.

Step 2: Add the tools, pinned

  1. Update pip itself. The cooldown option in Step 7 needs pip 26.1 or newer:

    python -m pip install pip==26.3
  2. Open requirements.txt and add these three lines at the end. If pip-audit is already there without a version, replace that line:

    pip-tools==7.6.2
    cyclonedx-bom==8.0.1
    pip-audit==2.10.1
  3. Install and check:

    pip install -r requirements.txt
    pip --version
    pip-compile --version
    cyclonedx-py --version

    You should see pip 26.3 and version numbers for the other two.

Step 3: Save the checker

In VS Code, right-click the unit11 folder, choose New File, name it supply_chain_check.py, paste the code below and save. It uses only Python's built-in modules.

"""Supply-chain checks for a Python AI service (Orchestrate course, Unit 11).

Built-in modules only. Runs without an account:

  python unit11/supply_chain_check.py --sample            # Calder's gateway on 21 October 2026
  python unit11/supply_chain_check.py --sample --fixed    # the same service after the fixes
  python unit11/supply_chain_check.py --whatif 2026-10-21T12:05 --cooldown 7
  python unit11/supply_chain_check.py --requirements requirements.txt
  python unit11/supply_chain_check.py --requirements requirements.txt --pypi   # online

All Calder names, hosts, secrets and dates are fictional course values.
The LiteLLM upload times and bad versions are real (PyPI and OSV MAL-2026-2144,
read 21 November 2026).
"""

import argparse
import csv
import io
import json
import re
import sys
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
SAMPLE = HERE / "supply_sample"

# Versions the OpenSSF malicious-packages feed lists for litellm (OSV MAL-2026-2144).
KNOWN_BAD = {"litellm": {"id": "MAL-2026-2144", "versions": ["1.82.7", "1.82.8", "1.107.0"]}}

# First upload time on PyPI of some litellm releases (UTC), read 21 November 2026.
# 1.107.0 is not on PyPI any more: it was live from 11:39:51 to about 13:23 UTC
# on 21 October 2026 (LiteLLM incident report).
LITELLM_UPLOADS = {
    "1.104.3": "2026-10-11T10:31", "1.105.0": "2026-10-11T09:47",
    "1.105.1": "2026-10-14T04:27", "1.106.0": "2026-10-18T05:49",
    "1.105.2": "2026-10-20T18:10", "1.106.1": "2026-10-20T18:53",
    "1.105.3": "2026-10-21T09:56", "1.106.2": "2026-10-21T10:44",
    "1.107.0": "2026-10-21T11:39", "1.106.3": "2026-10-24T09:14",
}
BAD_WINDOW = ("2026-10-21T11:39", "2026-10-21T13:23")

# ---------------------------------------------------------------- sample data

SAMPLE_FILES = {
    "before/Dockerfile": (
        "FROM python:3.12-slim\n"
        'RUN pip install --no-cache-dir "litellm[proxy]"\n'
        "COPY config.yaml /app/config.yaml\n"
        'CMD ["litellm", "--config", "/app/config.yaml"]\n'
    ),
    "before/requirements.txt": "litellm[proxy]\npython-dotenv>=1.0\n",
    "fixed/Dockerfile": (
        "# The digest is a course placeholder, not a real image.\n"
        "FROM python:3.12-slim@sha256:" + "0" * 64 + "\n"
        "COPY requirements.lock /app/requirements.lock\n"
        "RUN pip install --no-cache-dir --require-hashes --only-binary :all: -r /app/requirements.lock\n"
        "COPY config.yaml /app/config.yaml\n"
        'CMD ["litellm", "--config", "/app/config.yaml"]\n'
    ),
    "fixed/requirements.txt": (
        "# Excerpt. The full lock from pip-compile --generate-hashes lists every dependency.\n"
        "litellm[proxy]==1.106.2 \\\n"
        "    --hash=sha256:cb1a2a1e55a4a8350ae2167525dc0d06f59b078cd685fb3e0f5419f02da5420e \\\n"
        "    --hash=sha256:9f0e770cb007c8c6e78917ad7b5c4f059f7bdc4a3606f854831780ea53fd9e2d\n"
        "python-dotenv==1.2.4 \\\n"
        "    --hash=sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc\n"
    ),
    "builds.csv": (
        "build_id,built_at,service,litellm,deployed_to,deployed_at,build_secrets\n"
        "B201,2026-10-20T22:00,calder-ai-gw,1.106.1,gw-qa;gw-prod,2026-10-20T22:20,REGISTRY_PUSH_TOKEN\n"
        "B202,2026-10-21T12:05,calder-ai-gw,1.107.0,gw-qa;gw-prod,2026-10-21T12:20,REGISTRY_PUSH_TOKEN\n"
        "B203,2026-10-21T16:00,calder-ai-gw,1.106.2,gw-qa;gw-prod,2026-10-21T16:10,REGISTRY_PUSH_TOKEN\n"
        "B204,2026-10-28T09:00,calder-ai-gw,1.106.2,gw-qa;gw-prod,2026-10-28T09:30,REGISTRY_PUSH_TOKEN\n"
    ),
    "before/secrets.csv": (
        "name,what_it_opens,hosts,last_rotated,max_age_days,owner\n"
        "AICORE_CLIENT_SECRET,SAP AI Core service key calder-aicore-gw (generative AI hub),gw-prod,2026-06-02,90,BTP admin\n"
        "AICORE_CLIENT_SECRET_QA,SAP AI Core service key calder-aicore-gw-qa,gw-qa,2026-09-01,90,BTP admin\n"
        "LITELLM_MASTER_KEY,Gateway admin key and virtual keys for AGT_INV_TRIAGE and AGT_ORDER_EXC,gw-qa;gw-prod,2026-09-15,90,AI platform team\n"
        "DATABASE_URL,Gateway database holding virtual keys and spend logs,gw-qa;gw-prod,2026-05-10,180,AI platform team\n"
        "REGISTRY_PUSH_TOKEN,Push to Calder's container registry,ci-runner-1,2026-10-01,90,Platform engineering\n"
        "S4_OAUTH_CLIENT_SECRET,OAuth client for the order-exceptions agent's S/4HANA calls,agent-prod,2026-09-20,90,Basis\n"
    ),
    "fixed/secrets.csv": (
        "name,what_it_opens,hosts,last_rotated,max_age_days,owner\n"
        "AICORE_CLIENT_SECRET,SAP AI Core service key calder-aicore-gw (generative AI hub),gw-prod,2026-10-21,90,BTP admin\n"
        "AICORE_CLIENT_SECRET_QA,SAP AI Core service key calder-aicore-gw-qa,gw-qa,2026-10-21,90,BTP admin\n"
        "LITELLM_MASTER_KEY,Gateway admin key and virtual keys for AGT_INV_TRIAGE and AGT_ORDER_EXC,gw-qa;gw-prod,2026-10-21,90,AI platform team\n"
        "DATABASE_URL,Gateway database holding virtual keys and spend logs,gw-qa;gw-prod,2026-10-22,180,AI platform team\n"
        "REGISTRY_PUSH_TOKEN,Push to Calder's container registry,ci-runner-1,2026-10-21,90,Platform engineering\n"
        "S4_OAUTH_CLIENT_SECRET,OAuth client for the order-exceptions agent's S/4HANA calls,agent-prod,2026-09-20,90,Basis\n"
    ),
}


def _sbom(name, comps):
    return json.dumps({
        "bomFormat": "CycloneDX", "specVersion": "1.6", "version": 1,
        "metadata": {"timestamp": "2026-10-21T16:00:00Z", "component": {"type": "application", "name": name}},
        "components": [{"type": "library", "name": n, "version": v, "purl": f"pkg:pypi/{n}@{v}"} for n, v in comps],
    }, indent=1)


SAMPLE_FILES["sboms/calder-ai-gw.cdx.json"] = _sbom("calder-ai-gw", [("litellm", "1.106.2"), ("openai", "2.8.1"), ("python-dotenv", "1.2.4")])
SAMPLE_FILES["sboms/invoice-triage.cdx.json"] = _sbom("invoice-triage", [("litellm", "1.82.6"), ("requests", "2.34.2"), ("python-dotenv", "1.2.4")])
SAMPLE_FILES["sboms/order-exc-agent.cdx.json"] = _sbom("order-exc-agent", [("mcp", "2.3.0"), ("python-dotenv", "1.2.4")])


def write_sample():
    for rel, text in SAMPLE_FILES.items():
        p = SAMPLE / rel
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(text, encoding="utf-8")


# ---------------------------------------------------------------- checks

class Report:
    def __init__(self):
        self.rows = []

    def add(self, status, check, detail):
        self.rows.append((status, check, detail))
        print(f"{status:<5} {check:<4} {detail}")

    def fails(self):
        return sum(1 for s, _, _ in self.rows if s == "FAIL")


REQ_LINE = re.compile(r"^([A-Za-z0-9_.\-]+)(\[[^\]]*\])?\s*(.*)$")


def parse_requirements(text):
    """Return a list of (name, spec, has_hash). Joins lines ending in a backslash."""
    joined = text.replace("\\\n", " ")
    out = []
    for raw in joined.splitlines():
        line = raw.split("#", 1)[0].strip()
        if not line or line.startswith(("-r ", "-c ", "--")):
            continue
        has_hash = "--hash=sha256:" in line
        line = line.split("--hash", 1)[0].strip()
        line = line.split(";", 1)[0].strip()       # drop environment markers
        m = REQ_LINE.match(line)
        if m:
            out.append((norm(m.group(1)), m.group(3).strip(), has_hash))
    return out


def check_requirements(rep, text, label):
    reqs = parse_requirements(text)
    if not reqs:
        rep.add("WARN", "C1", f"{label}: no requirements found")
        return reqs
    loose = [n for n, spec, _ in reqs if not re.fullmatch(r"==\s*[0-9][^,\s]*", spec)]
    if loose:
        rep.add("FAIL", "C1", f"{label}: not pinned with ==: {', '.join(loose)}")
    else:
        rep.add("PASS", "C1", f"{label}: all {len(reqs)} requirements pinned with ==")
    unhashed = [n for n, _, h in reqs if not h]
    if unhashed:
        rep.add("WARN", "C2", f"{label}: no --hash for {len(unhashed)} of {len(reqs)} (hash-checking mode is off)")
    else:
        rep.add("PASS", "C2", f"{label}: every requirement has a sha256 hash")
    for n, spec, _ in reqs:
        bad = KNOWN_BAD.get(n)
        if bad and spec.lstrip("=").strip() in bad["versions"]:
            rep.add("FAIL", "C3", f"{label}: {n}{spec} is a known malicious release ({bad['id']})")
    if all(not (KNOWN_BAD.get(n) and spec.lstrip("=").strip() in KNOWN_BAD[n]["versions"]) for n, spec, _ in reqs):
        rep.add("PASS", "C3", f"{label}: no pinned version on the course's known-bad list")
    return reqs


def check_dockerfile(rep, text, label):
    for line in text.splitlines():
        s = line.strip()
        if s.upper().startswith("FROM "):
            image = s.split()[1]
            if "@sha256:" in image:
                rep.add("PASS", "C4", f"{label}: base image pinned by digest")
            else:
                rep.add("FAIL", "C4", f"{label}: base image '{image}' is a tag; a tag can be moved to other content")
        if s.upper().startswith("RUN ") and "pip install" in s:
            if "--require-hashes" in s and " -r " in s:
                rep.add("PASS", "C5", f"{label}: pip installs from a hashed lock file")
            else:
                rep.add("FAIL", "C5", f"{label}: pip resolves at build time: {s[4:].strip()}")


def check_secrets(rep, rows, today):
    for r in rows:
        age = (today - datetime.fromisoformat(r["last_rotated"]).date()).days
        if age > int(r["max_age_days"]):
            rep.add("FAIL", "C6", f"{r['name']}: last rotated {r['last_rotated']} ({age} days, policy {r['max_age_days']})")
    late = [r for r in rows if (today - datetime.fromisoformat(r["last_rotated"]).date()).days > int(r["max_age_days"])]
    if not late:
        rep.add("PASS", "C6", f"all {len(rows)} secrets within their rotation policy")


def blast_radius(rep, builds, secrets):
    """Which hosts ran a known-bad version, and which secrets were on them."""
    hosts, build_secrets, first_bad = set(), set(), ""
    for b in builds:
        if b["litellm"] in KNOWN_BAD["litellm"]["versions"]:
            first_bad = first_bad or b["built_at"]
            hosts.update(b["deployed_to"].split(";"))
            hosts.add("build " + b["build_id"])
            build_secrets.update(x for x in b["build_secrets"].split(";") if x)
            later = [x for x in builds if x["service"] == b["service"] and x["built_at"] > b["built_at"]
                     and x["litellm"] not in KNOWN_BAD["litellm"]["versions"]]
            replaced = f"; replaced by {later[0]['build_id']} at {later[0]['deployed_at']}" if later else "; STILL RUNNING"
            rep.add("PAST" if later else "FAIL", "C7",
                    f"build {b['build_id']} at {b['built_at']} installed litellm {b['litellm']}; "
                    f"deployed to {b['deployed_to'].replace(';', ', ')} at {b['deployed_at']}{replaced}")
    if not hosts:
        rep.add("PASS", "C7", "no build installed a known-bad version")
        return []
    exposed = [s for s in secrets if set(s["hosts"].split(";")) & hosts or s["name"] in build_secrets]
    for s in exposed:
        if s["last_rotated"] >= first_bad[:10]:
            rep.add("DONE", "C7", f"{s['name']} rotated on {s['last_rotated']} ({s['what_it_opens']})")
        else:
            rep.add("ROT", "C7", f"rotate {s['name']} ({s['what_it_opens']}), owner {s['owner']}")
    safe = [s["name"] for s in secrets if s not in exposed]
    rep.add("INFO", "C7", f"not on an affected host: {', '.join(safe)}")
    return exposed


def norm(name):
    return re.sub(r"[-_.]+", "-", name).lower()


def where_used(rep, sbom_dir, package):
    package = norm(package)
    found = []
    for f in sorted(Path(sbom_dir).glob("*.cdx.json")):
        bom = json.loads(f.read_text(encoding="utf-8"))
        app = (bom.get("metadata", {}).get("component") or {}).get("name") or f.name.split(".")[0]
        for c in bom.get("components", []):
            if norm(c.get("name", "")) == package:
                found.append((app, c.get("version", "?")))
    if not found:
        rep.add("INFO", "C8", f"{package} appears in no SBOM in {sbom_dir}")
    for app, v in found:
        bad = v in KNOWN_BAD.get(package, {}).get("versions", [])
        rep.add("FAIL" if bad else "INFO", "C8", f"{app} runs {package} {v}" + (" (known bad)" if bad else ""))
    return found


def whatif(at, cooldown_days):
    """What `pip install litellm` (newest stable) would have picked at a given time."""
    at = datetime.fromisoformat(at)
    cutoff = at - timedelta(days=cooldown_days)
    live = {v: datetime.fromisoformat(t) for v, t in LITELLM_UPLOADS.items()}
    lo, hi = (datetime.fromisoformat(x) for x in BAD_WINDOW)
    if not lo <= at <= hi:
        live.pop("1.107.0")          # removed from PyPI outside its live window
    candidates = [v for v, t in live.items() if t <= cutoff]
    key = lambda v: tuple(int(x) for x in v.split("."))
    pick = max(candidates, key=key) if candidates else None
    bad = pick in KNOWN_BAD["litellm"]["versions"]
    label = f"cooldown {cooldown_days} days" if cooldown_days else "no cooldown"
    print(f"At {at:%Y-%m-%d %H:%M} UTC with {label}: pip picks litellm {pick}" + ("  <- MALICIOUS" if bad else ""))
    return pick


def pypi_ages(rep, reqs, today, cooldown):
    """Online: upload age of each pinned release from PyPI's JSON API."""
    for n, spec, _ in reqs:
        if not spec.startswith("=="):
            continue
        v = spec[2:].strip()
        url = f"https://pypi.org/pypi/{n}/{v}/json"
        try:
            with urllib.request.urlopen(url, timeout=15) as r:
                data = json.load(r)
        except urllib.error.HTTPError as e:
            msg = "not on PyPI (removed, or a private package)" if e.code == 404 else f"HTTP {e.code}"
            rep.add("WARN", "C9", f"{n}=={v}: {msg}")
            continue
        except Exception as e:  # network or proxy
            rep.add("WARN", "C9", f"{n}=={v}: could not read PyPI ({e.__class__.__name__}: {e})")
            continue
        times = [f["upload_time_iso_8601"] for f in data.get("urls", [])]
        if not times:
            rep.add("WARN", "C9", f"{n}=={v}: no files on PyPI (removed or yanked?)")
            continue
        up = datetime.fromisoformat(min(times).replace("Z", "+00:00")).date()
        age = (today - up).days
        status = "WARN" if age < cooldown else "PASS"
        rep.add(status, "C9", f"{n}=={v}: uploaded {up} ({age} days ago; cooldown {cooldown})")


# ---------------------------------------------------------------- main

def main(argv=None):
    ap = argparse.ArgumentParser(description="Supply-chain checks for a Python AI service")
    ap.add_argument("--sample", action="store_true", help="check Calder's sample gateway (no account, no network)")
    ap.add_argument("--fixed", action="store_true", help="with --sample: check the fixed version")
    ap.add_argument("--requirements", help="check your own requirements file")
    ap.add_argument("--dockerfile", help="also check a Dockerfile")
    ap.add_argument("--sboms", help="folder of *.cdx.json SBOMs to search")
    ap.add_argument("--where", default="litellm", help="package to look for in the SBOMs (default litellm)")
    ap.add_argument("--pypi", action="store_true", help="online: check upload age on PyPI")
    ap.add_argument("--cooldown", type=int, default=7, help="days a release must be public (default 7)")
    ap.add_argument("--whatif", metavar="YYYY-MM-DDTHH:MM", help="what pip would have picked for litellm then (UTC)")
    a = ap.parse_args(argv)

    if a.whatif:
        whatif(a.whatif, 0)
        whatif(a.whatif, a.cooldown)
        return 0

    rep = Report()
    if a.sample:
        write_sample()
        side = "fixed" if a.fixed else "before"
        today = datetime(2026, 10, 28 if a.fixed else 21).date()
        print(f"Calder sample, {side}, as of {today} (fictional service, real LiteLLM versions)\n")
        check_requirements(rep, (SAMPLE / side / "requirements.txt").read_text(encoding="utf-8"), f"{side}/requirements.txt")
        check_dockerfile(rep, (SAMPLE / side / "Dockerfile").read_text(encoding="utf-8"), f"{side}/Dockerfile")
        secrets = list(csv.DictReader(io.open(SAMPLE / side / "secrets.csv", encoding="utf-8")))
        check_secrets(rep, secrets, today)
        builds = list(csv.DictReader(io.open(SAMPLE / "builds.csv", encoding="utf-8")))
        if not a.fixed:
            builds = [b for b in builds if b["built_at"] <= "2026-10-21T16:00"]
        blast_radius(rep, builds, secrets)
        where_used(rep, SAMPLE / "sboms", a.where)
    elif a.requirements:
        today = datetime.now(timezone.utc).date()
        path = Path(a.requirements)
        if not path.exists():
            print(f"File not found: {path}")
            return 2
        reqs = check_requirements(rep, path.read_text(encoding="utf-8"), path.name)
        if a.dockerfile:
            check_dockerfile(rep, Path(a.dockerfile).read_text(encoding="utf-8"), Path(a.dockerfile).name)
        if a.sboms:
            where_used(rep, a.sboms, a.where.lower())
        if a.pypi:
            pypi_ages(rep, reqs, today, a.cooldown)
    else:
        ap.print_help()
        return 2

    print(f"\n{rep.fails()} FAIL, {sum(1 for s, _, _ in rep.rows if s == 'WARN')} WARN, "
          f"{sum(1 for s, _, _ in rep.rows if s == 'ROT')} to rotate, "
          f"{sum(1 for s, _, _ in rep.rows if s == 'DONE')} rotated")
    return 1 if rep.fails() or any(s == "ROT" for s, _, _ in rep.rows) else 0


if __name__ == "__main__":
    sys.exit(main())

Step 4: Replay Calder's 21 October

python unit11/supply_chain_check.py --sample

The first run writes the sample files into unit11/supply_sample/ and checks them. You should see:

Calder sample, before, as of 2026-10-21 (fictional service, real LiteLLM versions)

FAIL  C1   before/requirements.txt: not pinned with ==: litellm, python-dotenv
WARN  C2   before/requirements.txt: no --hash for 2 of 2 (hash-checking mode is off)
PASS  C3   before/requirements.txt: no pinned version on the course's known-bad list
FAIL  C4   before/Dockerfile: base image 'python:3.12-slim' is a tag; a tag can be moved to other content
FAIL  C5   before/Dockerfile: pip resolves at build time: pip install --no-cache-dir "litellm[proxy]"
FAIL  C6   AICORE_CLIENT_SECRET: last rotated 2026-06-02 (141 days, policy 90)
PAST  C7   build B202 at 2026-10-21T12:05 installed litellm 1.107.0; deployed to gw-qa, gw-prod at 2026-10-21T12:20; replaced by B203 at 2026-10-21T16:10
ROT   C7   rotate AICORE_CLIENT_SECRET (SAP AI Core service key calder-aicore-gw (generative AI hub)), owner BTP admin
ROT   C7   rotate AICORE_CLIENT_SECRET_QA (SAP AI Core service key calder-aicore-gw-qa), owner BTP admin
ROT   C7   rotate LITELLM_MASTER_KEY (Gateway admin key and virtual keys for AGT_INV_TRIAGE and AGT_ORDER_EXC), owner AI platform team
ROT   C7   rotate DATABASE_URL (Gateway database holding virtual keys and spend logs), owner AI platform team
ROT   C7   rotate REGISTRY_PUSH_TOKEN (Push to Calder's container registry), owner Platform engineering
INFO  C7   not on an affected host: S4_OAUTH_CLIENT_SECRET
INFO  C8   calder-ai-gw runs litellm 1.106.2
INFO  C8   invoice-triage runs litellm 1.82.6

4 FAIL, 1 WARN, 5 to rotate, 0 rotated

Read it line by line:

  • C1 to C5 are admission checks. The gateway's requirements have no pins and no hashes, the base image is a tag, and the Dockerfile lets pip choose versions at build time. That is how build B202 got 1.107.0.
  • C6 flags a secret already past its rotation policy before the incident.
  • C7 is the blast radius. B202 ran on gw-qa and gw-prod for almost four hours. Five secrets were on those machines or in the build, so all five must be rotated. The order-exceptions agent's S/4HANA client secret lives on another host and stays out of scope; that is what keeping secrets apart buys you.
  • C8 searches the SBOMs: two services run LiteLLM. The gateway runs 1.106.2 now. invoice-triage is pinned to 1.82.6, the last version before March's bad releases, but pinned for eight months. Step 11 shows why that is also a problem.

The command exits with code 1, because there are failures and secrets to rotate. In a pipeline, that stops the release.

Step 5: Ask what pip would have installed

python unit11/supply_chain_check.py --whatif 2026-10-21T12:05
python unit11/supply_chain_check.py --whatif 2026-10-21T16:00
python unit11/supply_chain_check.py --whatif 2026-10-21T12:05 --cooldown 3

You should see:

At 2026-10-21 12:05 UTC with no cooldown: pip picks litellm 1.107.0  <- MALICIOUS
At 2026-10-21 12:05 UTC with cooldown 7 days: pip picks litellm 1.105.1
At 2026-10-21 16:00 UTC with no cooldown: pip picks litellm 1.106.2
At 2026-10-21 16:00 UTC with cooldown 7 days: pip picks litellm 1.105.1
At 2026-10-21 12:05 UTC with no cooldown: pip picks litellm 1.107.0  <- MALICIOUS
At 2026-10-21 12:05 UTC with cooldown 3 days: pip picks litellm 1.106.0

The function replays real PyPI upload times. Notice the price of a cooldown: at 16:00 the project's recommended clean version, 1.106.2, was only five hours old, so a seven-day rule still chose the older 1.105.1. A cooldown trades freshness for safety, which is why urgent fixes need an approved exception.

Step 6: Check the fixed gateway

python unit11/supply_chain_check.py --sample --fixed
Calder sample, fixed, as of 2026-10-28 (fictional service, real LiteLLM versions)

PASS  C1   fixed/requirements.txt: all 2 requirements pinned with ==
PASS  C2   fixed/requirements.txt: every requirement has a sha256 hash
PASS  C3   fixed/requirements.txt: no pinned version on the course's known-bad list
PASS  C4   fixed/Dockerfile: base image pinned by digest
PASS  C5   fixed/Dockerfile: pip installs from a hashed lock file
PASS  C6   all 6 secrets within their rotation policy
PAST  C7   build B202 at 2026-10-21T12:05 installed litellm 1.107.0; deployed to gw-qa, gw-prod at 2026-10-21T12:20; replaced by B203 at 2026-10-21T16:10
DONE  C7   AICORE_CLIENT_SECRET rotated on 2026-10-21 (SAP AI Core service key calder-aicore-gw (generative AI hub))
DONE  C7   AICORE_CLIENT_SECRET_QA rotated on 2026-10-21 (SAP AI Core service key calder-aicore-gw-qa)
DONE  C7   LITELLM_MASTER_KEY rotated on 2026-10-21 (Gateway admin key and virtual keys for AGT_INV_TRIAGE and AGT_ORDER_EXC)
DONE  C7   DATABASE_URL rotated on 2026-10-22 (Gateway database holding virtual keys and spend logs)
DONE  C7   REGISTRY_PUSH_TOKEN rotated on 2026-10-21 (Push to Calder's container registry)
INFO  C7   not on an affected host: S4_OAUTH_CLIENT_SECRET
INFO  C8   calder-ai-gw runs litellm 1.106.2
INFO  C8   invoice-triage runs litellm 1.82.6

0 FAIL, 0 WARN, 0 to rotate, 5 rotated

The fixed Dockerfile pulls the base image by digest and installs from a hashed lock with --require-hashes --only-binary :all:. All five secrets were rotated within a day of the incident. B202 stays in the history as PAST, because an incident record shouldn't disappear when it is resolved. The exit code is 0.

Step 7: Compile a hashed lock for your course folder, with a cooldown

Your requirements.txt says what you want. The lock will say exactly what gets installed.

  1. Copy it to a new file named requirements.in:

    • Windows (PowerShell):

      Copy-Item requirements.txt requirements.in
    • macOS / Linux:

      cp requirements.txt requirements.in
  2. Compile the lock. Every package and dependency gets an exact version and its hashes, and only releases at least seven days old are considered:

    pip-compile --generate-hashes --allow-unsafe --strip-extras --pip-args "--uploaded-prior-to P7D" -o requirements.lock requirements.in

    --allow-unsafe also pins pip and setuptools, which pip-tools leaves out by default; without them, a hashed install on a fresh machine can refuse to start. If a requirements.lock already exists, delete it first: pip-compile keeps the versions an existing lock already pins.

    This takes a minute or two. Open requirements.lock. Each package looks like this, with one hash per file the release offers:

    python-dotenv==1.2.4 \
        --hash=sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc \
        --hash=sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0
        # via -r requirements.in

    If a line in requirements.in pins a release younger than seven days, pip-compile stops with No matching distribution found for that pin. That is the cooldown working: choose an older version or wait.

Step 8: Install from the lock

pip install --require-hashes --only-binary :all: -r requirements.lock

pip checks every downloaded file against the lock. Packages you already have at the right version show as Requirement already satisfied.

Step 9: Watch pip refuse a tampered file

Do this in a throwaway environment, so your course environment stays untouched.

  1. Make a copy of the lock named tampered.lock, open it, find the two --hash lines under python-dotenv==, and change the last character of each hash (for example a c to a d). Save.

  2. Create a throwaway environment and install from the tampered lock:

    • Windows (PowerShell):

      python -m venv .venv-tamper
      .venv-tamper\Scripts\python -m pip install pip==26.3
      .venv-tamper\Scripts\python -m pip install --require-hashes --only-binary :all: -r tampered.lock
    • macOS / Linux:

      python -m venv .venv-tamper
      .venv-tamper/bin/python -m pip install pip==26.3
      .venv-tamper/bin/python -m pip install --require-hashes --only-binary :all: -r tampered.lock
  3. You should see pip refuse:

    ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
        python-dotenv==1.2.4 from https://files.pythonhosted.org/packages/.../python_dotenv-1.2.4-py3-none-any.whl (from -r tampered.lock (line ...)):
            Expected sha256 (your edited wheel hash)
            Expected     or (your edited source hash)
                 Got        42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc

    The "Got" line is the real file's hash. This is what a replaced file under a trusted version number would look like.

  4. Delete the throwaway environment and the tampered file:

    • Windows (PowerShell):

      Remove-Item -Recurse -Force .venv-tamper, tampered.lock
    • macOS / Linux:

      rm -rf .venv-tamper tampered.lock

Step 10: Write an SBOM of your environment and search it

  1. Make a folder for SBOMs and write one for your course environment:

    • Windows (PowerShell):

      New-Item -ItemType Directory -Force unit11\sboms
      cyclonedx-py environment --of JSON -o unit11\sboms\course.cdx.json
    • macOS / Linux:

      mkdir -p unit11/sboms
      cyclonedx-py environment --of JSON -o unit11/sboms/course.cdx.json

    The tool writes CycloneDX 1.6 by default.

  2. Ask where a package runs:

    python unit11/supply_chain_check.py --requirements requirements.lock --sboms unit11/sboms --where python-dotenv

    You should see your lock pass C1 to C3 and a C8 line such as:

    PASS  C1   requirements.lock: all 56 requirements pinned with ==
    PASS  C2   requirements.lock: every requirement has a sha256 hash
    PASS  C3   requirements.lock: no pinned version on the course's known-bad list
    INFO  C8   course runs python-dotenv 1.2.4

    Your count of requirements will differ; it depends on which units you have set up.

Step 11: Audit the lock against advisories

pip-audit -r requirements.lock --progress-spinner off

pip-audit looks every pinned version up in advisory data. No known vulnerabilities found with exit code 0 is a valid, good result. If it lists findings, each row shows the package, the version, an advisory ID and the version that fixes it, and the exit code is 1.

To see why an old pin is not a safe pin, audit the sample's invoice-triage version:

  • Windows (PowerShell):

    Set-Content old.txt "litellm==1.82.6"
    pip-audit -r old.txt --no-deps --progress-spinner off
    Remove-Item old.txt
  • macOS / Linux:

    echo "litellm==1.82.6" > old.txt
    pip-audit -r old.txt --no-deps --progress-spinner off
    rm old.txt

On 21 November 2026 this listed 31 known vulnerabilities, each with a fixed version. Your number may be higher: advisories only get added. The version before March's bad releases is free of malware, not of bugs.

Step 12: Check upload ages online

python unit11/supply_chain_check.py --requirements requirements.in --pypi

C9 lines show how many days ago each pinned version was uploaded to PyPI. WARN means younger than the seven-day cooldown, which you'd expect only for a deliberate, approved urgent fix. A version that is no longer on PyPI shows as not on PyPI (removed, or a private package): for a public package, find out why before you build again. C1 flags any line in requirements.in that still isn't pinned; the lock pins it, but decide whether the input should too.

Step 13: Save your work in Git

git add requirements.txt requirements.in requirements.lock unit11/supply_chain_check.py unit11/sboms
git commit -m "Unit 11: hashed lock with cooldown, SBOM and supply-chain checks"

Leave unit11/supply_sample/ out if you like; the checker rewrites it on every --sample run.

How the code works

Part What it does
KNOWN_BAD The course's copy of the malicious LiteLLM versions from OSV MAL-2026-2144
LITELLM_UPLOADS, BAD_WINDOW Real PyPI upload times of some releases, and the hours 1.107.0 was live
SAMPLE_FILES, write_sample Calder's before and fixed Dockerfiles, requirements, secrets, build log and three SBOMs
parse_requirements Reads a requirements or lock file, joining the backslash-continued hash lines
check_requirements C1 exact pins, C2 hashes, C3 known-bad versions
check_dockerfile C4 base image by digest, C5 pip install only from a hashed lock
check_secrets C6 compares each secret's last rotation with its policy
blast_radius C7 finds builds that installed a bad version, their hosts, and every secret on them; marks each rotated or still to rotate
where_used C8 searches CycloneDX files for a package, normalizing pip_audit and pip-audit
whatif Replays which version "newest" meant at a given time, with and without a cooldown
pypi_ages C9, online: upload date of each pinned version from PyPI's JSON API
exit code 1 when anything fails or needs rotating, so a pipeline can stop

If something goes wrong

What you see What it means What to do
python: command not found or 'python' is not recognized Python isn't on your PATH Follow Set up your computer; on macOS or Linux try python3
pip-compile: command not found or cyclonedx-py not recognized The tools aren't in the active environment Check for (.venv), then pip install -r requirements.txt
no such option: --uploaded-prior-to pip older than 26.1 python -m pip install pip==26.3
No matching distribution found for ...==X during pip-compile That pin is younger than the cooldown, or doesn't exist Pin an older version, or wait; for an urgent fix, record who approved skipping the cooldown
Hashes are required in --require-hashes mode, but they are missing A requirement has no hash, often a line added by hand Add it to requirements.in and compile the lock again
THESE PACKAGES DO NOT MATCH THE HASHES outside Step 9 A file differs from the lock: a mirror served a different file, or tampering Stop. Don't edit the hash to make it pass; find out which file and why
pip-audit or C9 shows a network or proxy error Your network blocks PyPI or the advisory service Ask IT for the proxy settings, or try from another network; Steps 4 to 6 still run offline
File not found: requirements.in You ran from inside unit11 Run from the course folder

The SAP way

Reaching generative AI hub through LiteLLM

The SAP-contributed LiteLLM proxy guide shows the gateway pattern this topic uses for Calder: a LiteLLM proxy in front of generative AI hub, with the SAP AI Core credentials passed as AICORE_AUTH_URL, AICORE_CLIENT_ID, AICORE_CLIENT_SECRET, AICORE_RESOURCE_GROUP and AICORE_BASE_URL. As read on 21 November 2026, its Dockerfile starts FROM python:3.12-slim and runs pip install "litellm[proxy]" without a version.

Those are exactly the two lines this lab's checker fails (C4 and C5), and environment variables are exactly what both LiteLLM payloads harvested. Treat the guide as a working example, then pin the base image by digest, install from a hashed lock and move the client secret into a secrets store before anything real depends on it. The same applies to the SAP Cloud SDK for AI: it is a set of PyPI packages, and it goes in the lock like any other.

Secrets: where they live and how they rotate

SAP's third-party MCP access reference architecture, updated 26 October 2026, sets three rules that shrink a supply-chain blast radius: keep API keys, client secrets and certificates in a dedicated store such as SAP Credential Store; rotate them regularly; and never keep long-lived credentials in MCP servers, exchanging tokens for scoped ones instead. A secret fetched per call, or exchanged for a short-lived token, is worth much less to a stealer than one sitting in an environment variable for months.

For services on SAP BTP's Kubernetes runtime, the SAP BTP service operator (v0.12.6, published 16 November 2026) can rotate a service binding's credentials automatically. Its credentialsRotationPolicy, set under the ServiceBinding's spec, takes enabled, rotationFrequency and rotatedBindingTTL: how long the old binding, and a secret holding its credentials, is kept before deletion while consumers switch over. The policy doesn't decide how long the credentials themselves stay valid; the bound service does. The annotation services.cloud.sap.com/forceRotate: "true" rotates at once, but only when rotation is enabled. That turns "rotate the AI Core binding" on incident day into a one-line change you have already tested, instead of a manual exercise.

Licensing

The tools in the lab are free and open source. SAP Credential Store and the Kubernetes runtime are SAP BTP services with their own entitlements; check your contract and the SAP Discovery Center for the current plans before you design around them.

Build vs. SAP

Need Build it yourself SAP offering Use
Pin and hash Python dependencies pip hash-checking mode, pip-tools or uv lock files None specific; SAP's own Python SDKs are PyPI packages you lock Always yours
Cooldown on new releases pip --uploaded-prior-to P7D, or a time filter in your package mirror None Yours, in the build or the mirror
SBOM per build cyclonedx-py in CI, stored next to the image None specific for your own services Yours
Known-bad and vulnerable versions pip-audit, OSV, your company's scanner None specific for your own services Your company's scanner if one exists; pip-audit otherwise
Secret storage A vault or cloud secret manager SAP Credential Store SAP Credential Store when the service runs on BTP
Credential rotation Scripts per secret type SAP BTP service operator binding rotation on Kubernetes The operator for BTP service bindings; scripts for the rest

Architecture view

Where it sits

flowchart LR
  PY[PyPI and<br/>image registries] --> MIR[Company mirror<br/>cooldown filter]
  MIR --> CI[CI build<br/>hashed lock, SBOM,<br/>pip-audit, checker]
  CI --> REG[Company registry<br/>images by digest]
  REG --> RT[BTP runtime<br/>calder-ai-gw]
  CS[SAP Credential Store] --> RT
  RT --> HUB[SAP AI Core<br/>generative AI hub]
  CI --> INV[SBOM and<br/>build log store]

Public packages and images never reach a running service directly. They pass a mirror that applies the cooldown, a build that locks, hashes, audits and records, and a registry that serves images by digest. Secrets reach the runtime from SAP Credential Store, not from the image or the build.

Non-functional requirements

Requirement Typical target What breaks if missed
Time to find exposure Every affected service and environment listed within 1 hour of an advisory Rotation starts late; stolen keys are used meanwhile
Time to rotate All secrets on an affected host rotated within 24 hours Attackers keep access; model spend on your bill
Cooldown 7 days for new releases; urgent exceptions approved and logged Builds install releases nobody has examined yet
Rebuild Any service rebuildable from lock and digest in under 1 hour "Fix in place" leaves dropped files behind
Secrets per host Only what that service needs, no shared admin keys One bad package on one host opens every system

Integration and identity

No user identity flows through this design; it governs what code runs next to the identities that do. The gateway authenticates to SAP AI Core with OAuth client credentials from the service key, held in SAP Credential Store. Agents authenticate to the gateway with their own keys, so rotating one agent's key doesn't touch the others. The build pushes images with a registry token that should exist only in CI, never in the runtime.

The decision to record

  • Context. Calder's AI services install open-source packages from PyPI. LiteLLM was compromised twice in 2026; in October the release passed signature and publishing checks.
  • Options. A: trust upstream signatures and install the newest versions. B: pin and hash, with no cooldown. C: pin and hash, a seven-day cooldown, an SBOM per build and a secrets inventory per host.
  • Decision. C. Urgent fixes may skip the cooldown with the security lead's recorded approval.
  • Consequences. Security fixes arrive up to seven days later unless someone approves an exception. Every build produces an SBOM and a build log. Each service owner keeps the secrets inventory current and runs a rotation test every quarter.

What a design review will ask

  1. Show me the lock and the base image digest for the version running in production today.
  2. An advisory names a package at 14:00. Walk me through the next hour: who searches what, and where?
  3. Which secrets are on the gateway's hosts, who owns each one, and when was each last rotated?
  4. What happens when an urgent fix is younger than the cooldown? Who approves, and where is it recorded?
  5. If the gateway image were malicious for a day, what could it reach beyond its own secrets?

Production concerns

  • Security and SAP authorizations. Give each service its own AI Core service key and its own agent keys, so a rotation is local. The gateway needs no S/4HANA credentials; keep it that way. Keep the registry push token in CI only.
  • A mirror, not the open internet. Install from your company's package mirror, with the cooldown applied there, so a developer's laptop and CI see the same rules.
  • Evaluation. Treat the checker's exit code like a failing test: no release with a FAIL. Record accepted pip-audit findings with an expiry date.
  • Cost. The controls are free tools and some build minutes. The expensive part is rotation, which is why the inventory and a rehearsed path matter.
  • Operations. Patch on a schedule: refresh the lock, let the cooldown apply, run the checks, deploy. Store each build's SBOM and lock with the image for as long as the image can run.
  • Clean core. None of this touches SAP standard code. The same discipline applies to the npm packages of a CAP app and to the images you deploy to SAP AI Core.

Pitfalls

  • Pinning your direct dependencies only. The bad package can be a dependency of a dependency. Lock everything, with hashes.
  • Hashing, but allowing source builds. Without --only-binary :all:, pip may fall back to the source archive, which runs build code on your machine.
  • "Fixing" a hash mismatch by updating the hash. A mismatch is the control working. Find out why the file changed first.
  • Pulling latest. A tag can be moved to other content; LiteLLM's latest on Docker Hub pointed at the bad image until 14:20 UTC, almost an hour after PyPI had removed the release.
  • Rotating only the obvious key. The October payload read everything in the process environment and the gateway's database. Rotate everything on the host and in the build.
  • Pins that never move. An eight-month-old pin avoids new malware and collects old vulnerabilities. Refresh on a schedule.
  • Upgrading instead of rebuilding. Dropped files such as cook.pth survive an upgrade.

Exercise: lock down the course's Unit 11 environment

The Unit 11 setup added its security tools to requirements.txt by name only. Apply this topic's controls to your own course folder and record what you find.

  1. In requirements.in, find every line that isn't pinned with ==. Pin each to the version currently installed (pip show <package> shows it).
  2. Compile requirements.lock again with hashes and a seven-day cooldown (Step 7). If a pin is younger than seven days, choose an older version and note why.
  3. Install from the lock with --require-hashes --only-binary :all: (Step 8). If a package has no wheel, record it.
  4. Write a fresh SBOM (Step 10) and run pip-audit -r requirements.lock.
  5. Create unit11/secrets_inventory.csv with the header name,what_it_opens,hosts,last_rotated,max_age_days,owner and one row for each key in your .env (names only, never values). Use laptop as the host.
  6. Write unit11/supply_chain_findings.md: unpinned lines you fixed, any package without a wheel, pip-audit findings and what you'll do about each, and which keys you would rotate first if your laptop's environment were compromised.
  7. Commit all of it except .env.

Done when python unit11/supply_chain_check.py --requirements requirements.in shows PASS on C1, pip install --require-hashes --only-binary :all: -r requirements.lock succeeds (or every exception is recorded in the findings), the SBOM is in unit11/sboms/, and the findings file lists every key in .env with an owner. The inventory and findings feed the review pack in Getting an AI system through security review.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1Why did checking LiteLLM's signature and publishing identity not stop the October 2026 release?

Answer: A. Stolen maintainer tokens triggered and approved the real release workflow, which signed and published 1.107.0 with the project's key and Trusted Publisher identity. PyPI's own page says Trusted Publishing doesn't assert the code is safe; bypassing the workflow was March's route, not October's.

2Your lock lists hashes for both the wheel and the source archive of each package. Why add --only-binary :all: as well?

Answer: A. Hash-checking mode accepts any file whose hash is listed, so a lock with both hashes still allows the source archive. Source archives run build code during install; pip's secure-install guidance recommends disallowing them.

3In the lab, --whatif 2026-10-21T16:00 with a 7-day cooldown picks 1.105.1, not the recommended clean 1.106.2. What does that show?

Answer: A. 1.106.2 was uploaded at 10:44 that day, younger than seven days, so the rule excluded it. That is the cooldown's cost, which the decision record handles with a named approver for urgent fixes.

4Build B202 installed 1.107.0 on gw-qa and gw-prod and was replaced four hours later. What does a correct response include?

Answer: C. The payload ran at interpreter start and read the whole environment and the gateway's database, and its dropped files survive an upgrade. The S/4HANA secret lives on another host, so it is outside this blast radius.

5The invoice-triage service is pinned to litellm 1.82.6, the last version before March's bad releases. Is that safe?

Answer: A. Pinning controls when you change, not whether you must. pip-audit showed 31 vulnerabilities for 1.82.6 on 21 November 2026; the OSV malicious entry covers only 1.82.7, 1.82.8 and 1.107.0.

6A teammate's build fails with "THESE PACKAGES DO NOT MATCH THE HASHES" and they propose copying the new hash into the lock. What do you do?

Answer: D. A hash mismatch under the same version number is what tampering looks like, and it is the control doing its job. Editing the hash or switching the check off removes the protection at the exact moment it matters.

7Why does the SAP-contributed LiteLLM proxy example fail checks C4 and C5 in the lab?

Answer: A. As read on 21 November 2026, its Dockerfile uses FROM python:3.12-slim and an unpinned pip install "litellm[proxy]". It doesn't use LiteLLM's own image, and credentials in environment variables are a separate risk the guide shares with many examples.

8On BTP's Kubernetes runtime, what does the SAP BTP service operator's rotatedBindingTTL control?

Answer: C. rotationFrequency sets how often rotation happens; rotatedBindingTTL keeps the old binding, and a secret with its credentials, for a while before deletion so consumers can pick up the new ones. Setting it too short turns a rotation into an outage.
NextAI gateways: governing model and agent trafficPut one checkpoint in front of every model, tool and agent call that checks, limits, meters and logs it, and know what SAP offers for each kind of traffic.

Sources

  • Contained: Oct 21, 2026 LiteLLM release v1.107.0 Compromised (LiteLLM blog) — opened 2026-11-21; published 21 October 2026, updated 23 and 30 October and 15 November; litellm==1.107.0, all seven wheels, on PyPI 11:39:51 to about 13:23 UTC; Docker Hub tags v1.107.0, latest, main-latest, main-stable until 14:20 UTC; GHCR litellm, litellm-database and litellm-non_root until 13:51 UTC; treat an environment that started Python with 1.107.0 as compromised; normal release flow publishes through Trusted GitHub Publishers, and the compromised v1.107.0 images carry a valid signature from the previous cosign key; delete cook.pth, cook.py and sitecustomize.py first; rebuild from scratch; pin 1.106.2; rotate the instance role, provider keys in the proxy database, master and virtual keys, the DATABASE_URL password and every secret in the host's environment
  • The attack chain behind the v1.107.0 LiteLLM release (LiteLLM blog) — opened 2026-11-21; published 23 October 2026, the canonical record; an admin key for an experimental agent platform committed to a public repository on 27 May and never revoked; it returned the GitHub organization owner's CLI token on 10 October; maintainers' tokens used to trigger and approve the release from a lookalike organization; the pipeline signed and published v1.107.0 built from the fork commit
  • Security Update: Suspected Supply Chain Incident (LiteLLM blog, March 2026) — opened 2026-11-21; published 24 March 2026; litellm 1.82.7 and 1.82.8 on PyPI from 10:39 UTC; origin believed (not confirmed) to be the Trivy dependency in CI; harvested environment variables, SSH keys, cloud and Kubernetes credentials; the official proxy Docker image was not affected because it pins dependencies in requirements.txt; treat any credentials on affected systems as compromised
  • MAL-2026-2144: Malicious code in litellm (PyPI) (OSV) — opened 2026-11-21; affected versions 1.82.7, 1.82.8 and 1.107.0; alias PYSEC-2026-2; published 2026-03-24, modified 2026-10-29; imported from the OpenSSF malicious-packages feed
  • Secure installs (pip documentation) — opened 2026-11-21; by default pip does not check against remote tampering; any --hash turns on hash-checking mode for all requirements; every requirement and dependency needs a hash and an == pin; recommends --only-binary :all: to disallow source distributions
  • Changelog (pip documentation) — opened 2026-11-21; --uploaded-prior-to added in pip 26.0 (2026-01-30) where the index provides upload-time; a duration in days such as P3D accepted from pip 26.1 (2026-04-26); pip 26.2 reads the upload-time field of pylock.toml
  • Trusted Publishers: security model and considerations (PyPI docs) — opened 2026-11-21; short-lived upload tokens that expire no more than 15 minutes after the OIDC flow; does not assert the safety of the code or the trustworthiness of its authors; treat Trusted Publishers as if they are API tokens; anyone who can commit to the repository can change the publishing workflow
  • Third-Party MCP Access to SAP Solutions (SAP Architecture Center) — opened 2026-11-21; last updated 26 October 2026; never store long-lived credentials in MCP servers; API keys, OAuth client secrets and certificates in a dedicated secrets store such as SAP Credential Store, rotated regularly; token exchange for scoped credentials
  • LiteLLM Proxy Setup Guide (litellm-agentic-examples, sap-contributions on GitHub) — opened 2026-11-21; connects agent frameworks to SAP generative AI hub through a LiteLLM proxy; installs pip install "litellm[proxy]" without a version, in a Dockerfile FROM python:3.12-slim; credentials as AICORE_AUTH_URL, AICORE_CLIENT_ID, AICORE_CLIENT_SECRET, AICORE_RESOURCE_GROUP and AICORE_BASE_URL in config, .env or environment
  • SAP BTP Service Operator (Go package documentation, github.com/SAP/sap-btp-service-operator) — opened 2026-11-21; v0.12.6 published 16 November 2026; automatic service binding rotation with spec.credentialsRotationPolicy (enabled, rotationFrequency, rotatedBindingTTL: how long the old ServiceBinding is kept before deletion; the policy does not manage the credentials' own validity); the services.cloud.sap.com/forceRotate annotation rotates at once when rotation is enabled; README re-read 2026-11-23

Sign in to track your progress

We'll email you a one-time sign-in link. No password needed.

or

Tell us a little about you

Optional, every field. It helps us pitch answers to your questions at the right level and decide which topics to write next. It is never shown publicly, and you can change or clear it anytime from the account menu.

SAP areas you work in