Skip to main content
Back to all articles
AI Engineering 18 min readUpdated November 25, 2026

When the Package Runs Before Your App: Quarantining AI Framework Releases

The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#agent-security#python#supply-chain#pypi#dependency-security#incident-response#typescript#fastapi#devsecops
On this page

On November 17, 2026, two releases of the legitimate Microsoft Agent Framework meta-package appeared on PyPI. They looked like normal patch updates. Inside their distribution files was a credential stealer wired into Python startup behavior.

This is not a prompt-injection story. The malicious code did not need a user to ask the agent a question, a tool call to be selected, or the framework to be imported by application code. The dependency was dangerous at the Python environment boundary.

The documented affected releases were agent-framework versions 1.26.1 and 1.26.2. The GitHub malware advisory GHSA-764m-3ppc-5m73 identifies 1.26.0 as the last known clean release before those two. The malicious wheels were removed. Security researchers documented the attack mechanism independently, including the Elastic Security Labs incident analysis.

I would use this incident to change a production AI team's dependency workflow in one specific way: a newly resolved distribution is a quarantined artifact until a trusted release service admits its exact bytes for a particular execution environment.

This is an original design proposal for a hypothetical Python/FastAPI agent platform with ephemeral CI runners, container builds, and separate production inference services. It is not a report that I operated the affected infrastructure, and the policy/code examples are not an implemented security product. My earlier articles on agent-skill supply chains, sandboxing generated code, and isolating gateway credentials cover adjacent risks. Here the specific boundary is the package installation and interpreter startup path.

A dependency can execute before application code

It is tempting to think of a dependency as dormant until the program imports it. Python startup makes that assumption unsafe for certain installed artifacts.

The Python site module documentation describes how the interpreter processes path configuration files in site-packages. Some executable lines in files ending in .pth are processed when Python initializes its site environment. Those lines can execute without an explicit import of the affected package in your application.

The distinction matters operationally:

EventWhat a conventional app-level guard can observeWhat a startup-hook compromise changes
Package resolutionSelected dependency name and versionThe name may still be legitimate
Artifact installationFiles copied into an environmentA startup hook enters the interpreter's trusted startup path
Next Python launchApplication code has not run yetHook execution may happen first
Agent framework importApplication instrumentation may beginTheft can already have occurred
Successful unit testAssertions passThe malicious hook can operate while tests still pass

The incident illustrates this sequence. Analysts found that the compromised meta-package still depended on the legitimate framework core. The application could remain functional while the unexpected startup behavior ran independently.

This is a useful reminder that a dependency scanner and a test suite answer different questions. A build can be green without having proved that its runtime environment was safe.

What the November incident actually established

The most reliable account is the published malware advisory together with vendor security analyses.

  • The two known malicious releases were 1.26.1 and 1.26.2, published on November 17.
  • Each introduced a Python .pth startup hook.
  • The mechanism collected accessible environment secrets, credential files, and attempted additional cloud or CI identity-token acquisition.
  • The payload sent collected information to an attacker-controlled collection endpoint.
  • The affected wheels were subsequently removed from PyPI.

The Cloud Security Alliance research note distinguishes attempted token minting from confirmed successful issuance. I would preserve that distinction in incident reporting. The fact that malware tried to acquire a token is sufficient reason to investigate identity activity, but not evidence that every attempted token request succeeded.

The security question is not whether a package came from a familiar project name. These releases used the project's legitimate distribution identity. The relevant questions are which *artifact* was installed, where it came from, how it was approved, and what that environment was allowed to access.

Do not treat 1.26.0 as a blanket endorsement for all future production uses. It is the last known unaffected version in the incident reporting, not a permanent guarantee of security or compatibility. At the time of the cited GitHub advisory update, no patched version was listed; future release decisions need fresh verification rather than a hardcoded assumption.

Draw the trust boundary before the dependency solver

I would separate four services that are often collapsed into one CI command:

  1. Resolver: discovers candidate versions and exact downloadable distribution files.
  2. Artifact quarantine: stores downloaded bytes without executing or installing them.
  3. Promotion service: verifies digest, provenance, content policy, review state, and approved usage scope.
  4. Build runner: installs only promoted artifacts, with no ability to resolve an unreviewed release from the public index.

The model itself has no authority to approve package bytes. Neither does a dependency bot opening an upgrade pull request. A pull request is a request for review, not permission for a runner holding production credentials to execute arbitrary newly published distributions.

~~~text Developer / dependency bot | Candidate version | v Isolated resolver no production secrets | v Immutable quarantine store exact wheel + digest | +----------+-----------+ | | | v v v Metadata Offline Provenance / policy archive publisher + cooldown inspection verification | | | +----------+-----------+ | Review / promotion signed decision record | v Internal approved index | Secrets-free CI builder pinned, hash-checked | Artifact / image scan | v Runtime identity boundary scoped credentials + egress | Agent workload

Public package metadata never grants production execution by itself. ~~~

A compromised distribution can still be downloaded for investigation. The essential constraint is that the investigation path is not an execution path.

For high-risk dependencies, keep the resolver and scanner in isolated workers with no production secrets, no cloud instance identity, restricted network access, and a disposable filesystem. The final build can then consume an internal approved artifact repository rather than silently falling back to public package resolution.

Hash pinning is essential—and not sufficient

The pip secure-installation documentation recommends hash-checking mode and explains that pinned versions, hashes for *every* dependency, and binary-only installs can make installation more controlled. Hashes chosen by the local requirements policy are stronger than trusting a digest supplied alongside an arbitrary remote download.

For a reviewed and approved artifact, hash checking means a later install cannot silently replace it with other bytes while keeping the same dependency name.

But a hash answers a narrow question: are these the bytes we approved? It does not answer should we approve them?

If a bot updates both the version and its matching hash, and an unreviewed CI job installs that change automatically, the hash check can pass while the dependency is malicious. The trusted approval has simply moved to an untrusted process.

The same applies to a lockfile. A lockfile is useful evidence of intended resolution, but it does not prove that the person or automation who updated it was authorized to admit a new distribution into a privileged environment.

My release design therefore uses two independent controls:

  • Content identity: exact hash for every allowed distribution file, checked during installation.
  • Admission authority: a protected promotion record that specifies who reviewed those hashes, what evidence was checked, when the release is eligible, and where it may execute.

The second control must be enforced outside the repository branch that a dependency bot can edit.

TypeScript: an immutable promotion decision

A promotion gate can be implemented as a pure decision function after verified supply-chain evidence has been collected.

This example is intentionally restrictive. It does not fetch packages, infer that a publisher is honest, or compute an attestation. Those checks belong to trusted adapters that provide the evidence.

~~~typescript type Evidence = Readonly<{ packageName: string; version: string; archiveSha256: string; uploadedAtMs: number; nowMs: number; advisoryDisposition: "clear" | "malicious" | "unknown"; provenance: "verified_expected_publisher" | "missing" | "mismatch"; staticInspection: "passed" | "review_required" | "rejected"; scope: "build" | "runtime"; approvedBy: readonly string[]; }>;

type Policy = Readonly<{ minimumReleaseAgeMs: number; requireProvenance: boolean; minimumIndependentReviewers: number; }>;

type Admission = | { decision: "promote"; artifactSha256: string } | { decision: "hold"; reason: string } | { decision: "reject"; reason: string };

export function decidePromotion( evidence: Evidence, policy: Policy, ): Admission { const hold = (reason: string): Admission => ({ decision: "hold", reason }); const reject = (reason: string): Admission => ({ decision: "reject", reason });

if (!evidence.packageName || !evidence.version || !/^[a-f0-9]{64}$/i.test(evidence.archiveSha256) || !Number.isSafeInteger(evidence.uploadedAtMs) || !Number.isSafeInteger(evidence.nowMs) || !Number.isSafeInteger(policy.minimumReleaseAgeMs) || policy.minimumReleaseAgeMs < 0 || !Number.isSafeInteger(policy.minimumIndependentReviewers) || policy.minimumIndependentReviewers < 1) { return reject("invalid_evidence_or_policy"); }

if (evidence.advisoryDisposition === "malicious" || evidence.staticInspection === "rejected") { return reject("known_malicious_or_rejected"); }

const releaseAgeMs = evidence.nowMs - evidence.uploadedAtMs; if (releaseAgeMs < 0) return hold("untrusted_release_timestamp"); if (releaseAgeMs < policy.minimumReleaseAgeMs) { return hold("release_cooldown"); }

if (evidence.advisoryDisposition !== "clear") { return hold("advisory_status_unresolved"); } if (policy.requireProvenance && evidence.provenance !== "verified_expected_publisher") { return hold("publisher_provenance_unverified"); } if (evidence.staticInspection !== "passed") { return hold("static_review_needed"); }

const uniqueApprovers = new Set(evidence.approvedBy); if (uniqueApprovers.size < policy.minimumIndependentReviewers) { return hold("insufficient_independent_approvals"); }

return { decision: "promote", artifactSha256: evidence.archiveSha256.toLowerCase(), }; } ~~~

This policy assumes a trusted evidence service has already normalized and authenticated every field. The caller must not take status values from an untrusted manifest embedded inside the wheel. Reviewers must be real, distinct, authorized identities, not arbitrary strings that the dependency author supplied. A real implementation should also bind the decision to a policy revision, the artifact storage object, platform target, immutable evidence identifiers, and the exact repository/release approval.

A release cooldown is a useful *delay*, not a malware detector. A malicious package that remains unnoticed beyond the cooldown can still pass an age check. The incident's brief exposure window shows why time can help, but time alone cannot prove integrity.

For urgent security fixes, the exception procedure should be a separately approved, audited change. It must not mean setting the global cooldown to zero for every project.

Inspect wheels without importing or installing them

A .whl file is a ZIP archive. A safe pre-installation scanner can examine its member names and selected small files without installing the package into site-packages or executing package code.

The key rule is inspect the archive as data in a clean isolated environment. Do not run the scanner using a Python interpreter that may already contain an infected startup hook.

This Python function is intentionally conservative. It flags any .pth file for human review and flags lines matching executable import syntax as a high-priority finding. It also rejects suspicious paths and oversized archives.

~~~python from dataclasses import dataclass from hashlib import sha256 from pathlib import Path, PurePosixPath from zipfile import ZipFile, BadZipFile

MAX_TOTAL_BYTES = 200 * 1024 * 1024 MAX_MEMBER_BYTES = 50 * 1024 * 1024 MAX_PTH_BYTES = 64 * 1024

@dataclass(frozen=True) class Finding: severity: str member: str reason: str

def inspect_wheel(wheel: Path) -> tuple[str, list[Finding]]: # Run only in a CLEAN isolated scanner. # This reads archive bytes; it never installs the wheel. data = wheel.read_bytes() digest = sha256(data).hexdigest() findings: list[Finding] = []

try: with ZipFile(wheel, "r") as archive: total_uncompressed = 0 names: set[str] = set()

for entry in archive.infolist(): name = entry.filename parsed = PurePosixPath(name) total_uncompressed += entry.file_size

if ( name.startswith("/") or "\\" in name or ".." in parsed.parts or name in names ): findings.append(Finding( "reject", name, "unsafe_archive_member" )) continue names.add(name)

if ( entry.file_size > MAX_MEMBER_BYTES or total_uncompressed > MAX_TOTAL_BYTES ): findings.append(Finding( "reject", name, "uncompressed_size_limit" )) break

if not name.lower().endswith(".pth"): continue

findings.append(Finding( "review", name, "startup_configuration_file" ))

if entry.file_size > MAX_PTH_BYTES: findings.append(Finding( "reject", name, "oversized_startup_file" )) continue

text = archive.read(entry).decode( "utf-8", errors="replace" ) for lineno, line in enumerate(text.splitlines(), 1): stripped = line.lstrip() if ( stripped.startswith("import ") or stripped.startswith("import\t") ): findings.append(Finding( "reject", name, f"executable_startup_line:{lineno}", ))

except (BadZipFile, OSError, RuntimeError) as exc: findings.append(Finding( "reject", "<archive>", type(exc).__name__ ))

return digest, findings ~~~

This is a screening sketch, not a complete hardened archive parser. It reads the whole wheel to compute the digest, so a production implementation should enforce an on-disk file-size limit before reading. A real scanner needs archive-integrity and decompression controls, unusual ZIP metadata handling, policy for other executable installation surfaces, and tests against malformed inputs. It should be sandboxed even though it does not intentionally execute wheel code.

The absence of a suspicious .pth file does not prove the distribution is safe. Packages can execute code through other paths, and an attacker can hide behavior in ordinary modules. That is why static inspection is one input to promotion, not an all-clear certificate.

Legitimate packages can also use .pth files for path configuration or import hooks. A high-signal policy should preserve an approved baseline and allow a reviewed exception where genuinely required, rather than assert that every .pth file is malware.

Provenance must bind to the expected release workflow

PyPI supports digital attestations that cryptographically bind a distribution to an attested identity and, where available, publishing or build provenance.

I would validate more than the presence of an attestation object. The release service should check:

  • The distribution digest matches the artifact being installed.
  • The attested identity matches the project and the organization's *expected publishing workflow*.
  • The release is consistent with the reviewed source and build process, to the level of assurance the project supports.
  • The publisher's normal artifact pattern has not changed unexpectedly.
  • There are no known-malicious advisories or unresolved release anomalies.
  • A protected policy reviewer approved the exact artifact for its intended scope.

Attestations are meaningful evidence of origin, not proof that a build is free of malicious code. If an attacker controls the authorized workflow itself, valid provenance may faithfully describe a compromised build. Review the release pipeline and permissions too.

PyPI's Trusted Publishing documentation explains OIDC-based short-lived publishing credentials. That helps reduce reliance on long-lived publishing tokens, but it does not automatically revoke every other existing publishing route or eliminate CI compromise risk.

In the November incident, analysts observed a suspicious publishing pattern for the malicious distribution. That is useful evidence for an anomaly gate: a package that usually publishes both wheel and source distributions, but suddenly publishes only a wheel without expected attestations, deserves investigation. It is not a universal rule that wheel-only releases are malicious.

CI must not be a credential warehouse

The strongest static scanner will sometimes miss a malicious artifact. The runtime design must therefore make the consequence of a compromise smaller.

A build job typically does not need all of the following simultaneously: source-control write permissions, production database credentials, cloud control-plane privileges, model-provider API keys, package-registry publishing credentials, and unrestricted outbound networking.

I would split the pipeline into stages:

StageCredentials permittedNetwork posture
Quarantine downloadRestricted artifact-read identity onlyApproved package sources
Static inspectionNone beyond artifact-read accessEgress disabled where feasible
Dependency buildNo production or deployment secretsInternal approved index
Test executionDisposable test identities and fixture dataTest-only destinations
Image signing and promotionShort-lived signing authority scoped to artifactsAttested release service
Production runtimeOnly task-specific operational identityExplicit service destinations

The target is not an impossible promise that code never handles credentials. It is that a compromised dependency in one stage cannot harvest all credentials held by the organization.

Restrict access to cloud metadata endpoints on runners that do not need workload identity. Minimize CI OIDC token permissions. Give production model gateways their own credential custody rather than injecting every provider key into every framework-based worker.

This builds on my multi-tenant gateway compromise budget: the blast radius depends on the authority of the executing environment as much as on which code was compromised.

Respond as a host compromise, not as a failed package install

If a team discovers that an affected wheel was installed in a developer environment, runner, or image, the question is what that environment could access during exposure. Waiting for proof that credentials were exfiltrated before taking precautions can be unsafe.

I would use this sequence:

1. Contain from outside the affected interpreter. Disable impacted workers, isolate their network access, and preserve relevant evidence using clean incident-response tooling. Do not run an ordinary Python-based uninstall in the suspect environment just to "clean up": that interpreter startup may trigger the hook again.

2. Find all artifact exposure paths. Search build image manifests, lockfiles, package caches, CI install logs, ephemeral-runner records, and internal mirrors for the exact affected versions and distribution hashes. Include jobs whose build succeeded; a passing test is not a sign of safety here.

3. Revoke and rotate reachable credentials. Review provider API keys, Git credentials, registry secrets, Azure and CI identities, and other sensitive values that the environment might read. Cloud-issued short-lived tokens may not be instantly revocable in the same way as API keys; inspect token activity and expiry windows with the identity team.

4. Rebuild from known-clean infrastructure. Replace affected virtual environments and container images instead of assuming that deleting one hook repairs an execution environment. Evict suspect artifacts from caches and mirrors, and require an independently reviewed artifact for the replacement.

5. Look for downstream effects. Audit unusual API calls, cloud role changes, repository access, package publications, and deployments performed with identities reachable from affected hosts. The attack surface includes credentials that might have been used after the installation step.

6. Resume only after fresh release admission. The rebuilt environment should use a protected, reviewed artifact set. Collect evidence that the production runner is operating the expected images and has only the intended credentials.

The Elastic Security Labs incident response guidance and GitHub advisory provide incident-specific indicators and affected-version details. A general platform runbook should link to those records rather than hardcode ephemeral attacker infrastructure into normal application configuration.

What the release gate should measure

I would monitor the *completeness and quality of admission evidence*, not merely the count of blocked vulnerable dependencies.

SignalOperational decision
Artifacts awaiting promotion by risk tierAre high-impact dependency changes accumulating?
Unverified or unexpected publisher identityWhich releases need investigation?
Startup-hook changes from approved baselineWhich wheels introduce interpreter-start behavior?
Unapproved artifact installsDid any job bypass the internal index?
Release cooldown exceptionsWho overrode the delay, and why?
Credential exposure potential by build stageWhat could a compromised package have reached?
Runner/image artifact reconciliationDid the approved files actually ship?
Advisory ingestion freshnessIs "no alert" really current evidence?
Time from security advisory to containmentCan we stop exposure while releases are spreading?

High-cardinality artifact hashes and runner identities belong in protected audit records. Aggregate metrics should use bounded categories and avoid leaking full environment variables, credentials, or developer paths.

The release controller should have its own health checks. If the advisory feed becomes unavailable or provenance verification errors increase, the absence of a rejection must not be treated as approval.

Tests I would add before rollout

An admission pipeline can be bypassed through ordinary implementation mistakes. I would start with deterministic tests for these cases:

  • A new patch version has the correct package name but an unapproved digest: hold.
  • A dependency bot updates the digest and version together: still requires protected approval.
  • The publisher identity changes unexpectedly: hold pending verification.
  • A new .pth file contains executable startup lines: reject or quarantine for security review.
  • A wheel contains a legitimate, previously approved path-only .pth file: recognize the approved baseline.
  • One transitive dependency lacks a required hash: reject the install plan.
  • A binary-only policy receives a source distribution: reject before installation.
  • The security advisory feed is unavailable: mark evidence unknown, not clear.
  • An install attempts to reach the public index from a secrets-bearing runner: block by egress policy.
  • A compromised runner is terminated, but the same artifact remains in a shared cache: prevent reintroduction.
  • A later reviewed replacement is available: promote its exact digest independently instead of trusting the version number.

These are release invariants; they do not require an AI model to decide whether a package is safe.

What I would ship first

A full artifact-security platform is expensive and not always justified for a small prototype. The first useful changes can be much narrower: exact version and hash pinning for sensitive Python dependencies, a separate clean build environment, a restricted internal package index, and a documented review step before dependency bots can execute new releases on privileged runners.

Next I would add offline wheel inspection, publisher-provenance verification, a cooldown for newly published high-risk dependencies, and routine reconciliation between approved artifact manifests and actual runner images.

Finally, I would test incident containment as seriously as the admission path. A system that can detect a malicious release but cannot quickly identify which runners installed it and which credentials they held is still missing a crucial part of the boundary.

The principle is simple: do not let an unreviewed distribution become trusted merely because a package manager can resolve it and the unit tests remain green.

Python startup hooks made that lesson unusually visible in November 2026. The more general engineering rule applies to every AI framework and build tool that can execute code before the business application begins: promote the exact artifact, isolate the environment, and keep the proof of approval outside the code being installed.

Primary technical sources

KEEP READING

Related engineering notes