Beagle Lesson #4: How to Check a Package Before an AI Agent Installs It
From the publisher’s feed, collected in the ZeroLabs newsroom.
A practical guide to invented dependencies, registry identity and reviewed artifacts, with an offline Python exercise.A plausible package name is a starting point for review, not permission to install its code.A coding assistant cannot find a convenient parser for your import job. It proposes a dependency, adds an import and offers to install the package so it can finish testing. The name looks plausible. A registry search even finds something with the same spelling.Before the command runs, someone still needs to establish who publishes that package, where it will be downloaded from and why that specific artifact belongs in the project. A successful lookup answers only one of those questions.This lesson uses a fictional dependency called beagle-demo-parser. It is a teaching label, not a recommendation to find or install a real package. We will inspect the path from suggestion to installation, distinguish a name from an approved artifact, and run a local check that rejects unreviewed changes without downloading anything.An invented name can become a real installation targetA package hallucination occurs when generated code refers to a dependency that does not exist in the relevant ecosystem at the time it is checked. Slopsquatting describes the associated attack pattern: someone registers a name that models are likely to suggest and relies on a later developer or agent to install that package.The USENIX Security 2025 study We Have a Package for You! evaluated 16 models and generated 576,000 code samples across Python and JavaScript. Its authors documented fabricated package names and examined whether suggestions recur. This establishes a measured failure mode in that study’s models and prompts. It does not give the current compromise rate of coding agents, or prove that every nonexistent recommendation is an attack. Source: the authors’ USENIX publication.The timing explains why existence alone is an inadequate defense. A model can invent a name on Monday. An attacker can register it on Tuesday. A developer repeating the task on Wednesday can find a real package, even though the recommendation did not originate from knowledge of that publisher’s software. The authors describe that attack sequence in their accompanying explanation. Source: USENIX author article.There are other routes to the wrong package. A misspelled name may select a lookalike. A private dependency may resolve from an unintended public source. A legitimate project can also ship a compromised release. These cases have different causes, so the review should establish the chosen artifact’s identity rather than merely classify the spelling mistake.Review the dependency proposal before making it executableFor the fictional import job, ask what the proposed library does that the existing code or standard library cannot. A small, routine transformation may need no new dependency. Removing unnecessary installation is useful because it removes an entire software-trust decision from this task.When a dependency is justified, check its identity using the project’s own documentation and the relevant registry. Compare the distribution name, maintained repository, release history and documented installation method. A README inside the candidate package is a claim from its publisher, not independent proof that it is the project you intended.Use the term distribution name carefully in Python. The name passed to an installer can differ from the name used in an import statement. Python's packaging documentation explicitly distinguishes those concepts, so do not infer an install command solely by copying the import token. Source: Python Packaging User Guide.For an organization, the review should connect the candidate to a maintained dependency policy. That policy may already define approved registries, allowed namespaces, reviewed versions and who can authorize a new package. An agent proposing a dependency should not also be able to edit the policy that approves it.Check the publisher and source, pin reviewed artifacts, and inspect the full dependency change before installation.A useful proposal includes the purpose of the dependency, the exact version, its source and the dependency changes it introduces. Review the lockfile as well as the line added to the top-level manifest. The direct package is only the first part of the code being admitted.Installation can execute code before your test beginsIt is easy to treat installation as a preliminary step before execution. Package managers do not always preserve that distinction.npm documents lifecycle hooks that run during installation, including preinstall, install and postinstall. Its ignore-scripts option suppresses package scripts for installation, but explicitly requested script commands still run their named script. The setting is a specific control, not a general sandbox. Sources: npm's scripts documentation and npm ci.For Python, pip’s secure-install guidance recommends hash-checking mode and disallowing source distributions where appropriate. Building a source distribution can involve executing build-system code. A wheel avoids that source-build step, but code from the installed package can still run when imported or used. Source: pip secure installs.This is why our review happens before granting a coding agent an unrestricted installation tool. A credential-free disposable environment limits what an unknown dependency can reach during assessment. It should also have an explicit network policy and resource limits; an empty working directory alone does not isolate the host.For an already reviewed npm project, a restricted validation run might begin with:npm ci --ignore-scriptsThis is an installation command and can contact configured registries. It is shown as an example for a disposable review environment, not as part of the offline exercise below. npm ci requires a lockfile and fails when the manifest and lockfile disagree. It does not certify the locked packages as trustworthy. Source: npm ci.Some legitimate packages need a build hook. Investigate that requirement, review the hook and allow it deliberately in the appropriate environment. Disabling a control globally to get a green build changes the security decision for every dependency in that run.Learn what a hash actually establishesA cryptographic digest identifies bytes. When a trusted approval records a digest, comparing the downloaded artifact with that value can detect substitution or corruption. Matching the digest does not establish that the approved artifact is benign.If the same unreviewed agent supplies both the package and the expected digest, it can make the comparison pass by hashing whatever it chose. The expected value must come from a reviewed record outside the agent’s write authority.pip’s hash-checking mode requires exact requirements and hashes for the dependency set, including dependencies of dependencies. Its documentation explains why partial coverage leaves a gap. Use the package manager’s supported mechanism rather than inventing a text comparison around an installer command. Source: pip secure installs.Name normalization matters as well. Python distribution names are compared after lowercasing and replacing runs of hyphens, underscores and periods with a hyphen. Beagle_Demo.Parser and beagle-demo-parser therefore represent the same normalized distribution name in this exercise. Treating them as unrelated packages can break a policy check. Source: Python packaging name normalization.Existence, publisher identity, artifact integrity and execution safety answer different questions.Run an offline artifact checkThe following Python 3.10+ program uses only the standard library. Its artifact is a short byte string, not an installable package. Its registry address ends in .invalid, and the program never resolves or contacts it.The approved record is fixed by the exercise. The proposed dependency is allowed to vary. The check accepts only the reviewed identity and the reviewed bytes, including equivalent normalized spelling.Save it as dependency_demo.py:"""Check a fictional dependency against a trusted local approval. No installs."""from dataclasses import dataclass, replacefrom hashlib import sha256import redef normalize_name(name: str) -> str: if type(name) is not str or not re.fullmatch( r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?", name ): raise ValueError("Invalid distribution name") return re.sub(r"[-_.]+", "-", name).lower()@dataclass(frozen=True)class Dependency: name: str version: str registry: str digest: strARTIFACT = b"BEAGLE TEACHING FIXTURE ONLY; NOT AN INSTALLABLE PACKAGE\n"APPROVED = Dependency( "beagle-demo-parser", "1.0.0", "https://registry.example.invalid/simple", sha256(ARTIFACT).hexdigest(),)def check(candidate: Dependency, artifact: bytes) -> bool: # APPROVED is reviewed policy, not data supplied by the coding agent. try: same_name = normalize_name(candidate.name) == normalize_name(APPROVED.name) except (ValueError, TypeError): return False return ( same_name and candidate.version == APPROVED.version and candidate.registry == APPROVED.registry and candidate.digest == APPROVED.digest and sha256(artifact).hexdigest() == APPROVED.digest )def main() -> None: trials = [ ("approved artifact", APPROVED, ARTIFACT, True), ("normalized spelling", replace(APPROVED, name="Beagle_Demo.Parser"), ARTIFACT, True), ("different package", replace(APPROVED, name="beagle-demo-parser-pro"), ARTIFACT, False), ("different version", replace(APPROVED, version="9.9.9"), ARTIFACT, False), ("different registry", replace(APPROVED, registry="https://other.invalid"), ARTIFACT, False), ("changed bytes", APPROVED, ARTIFACT + b"changed", False), ] for label, candidate, artifact, expected in trials: result = check(candidate, artifact) if result != expected: raise AssertionError(f"Unexpected decision: {label}") print(f"{label}: {'ACCEPT' if result else 'BLOCK'}")if __name__ == "__main__": main()Run:python3 dependency_demo.pyExpected output:approved artifact: ACCEPTnormalized spelling: ACCEPTdifferent package: BLOCKdifferent version: BLOCKdifferent registry: BLOCKchanged bytes: BLOCKThe accompanying tests also change the proposed digest to match altered bytes. That request still fails because the separately held approved record did not change.This program demonstrates an approval comparison for one fictional artifact. It does not scan malware, resolve real dependencies, verify a publisher or prevent a package from behaving badly after import. A production dependency pipeline must cover the full resolved set and ensure the bytes checked are the bytes installed. Checking a file and later installing a newly downloaded file would reintroduce a gap.Ask what the lockfile did and did not promiseA lockfile helps keep a dependency graph reproducible. A reviewed graph gives you something concrete to compare against later changes. It does not establish that every resolved package is safe, or that the original review was correct.For this exercise’s workflow, keep the approval boundary outside the agent-editable project. The agent can propose changes to the manifest and lockfile, but a separate review decides whether those changes become the approved build input. Do not let a passing test automatically approve its own new dependencies.Inspect source changes, new versions and added transitive packages. Check whether a private dependency can resolve from a second source. pip explicitly warns that using --extra-index-url to find private packages can expose a dependency-confusion risk. The resolver's behavior must match the source policy you intended. Source: pip install reference.Some teams use an internal proxy or artifact repository to enforce that policy. Such a service is useful only if its routing and admission rules are configured deliberately. A cache that accepts everything from the public internet should not be described as a reviewed package catalog.For build actions, GitHub recommends pinning third-party actions to full commit hashes and verifying that a chosen commit belongs to the intended repository. That is another application of the same identity question: a short label or mutable tag is not a complete artifact identity. Source: GitHub Actions secure-use reference.Test your coding workflow before an unexpected dependency arrivesCreate a disposable project with a known dependency policy. Start with a task that can be completed without new packages, then a task for which one already approved package is available. Confirm that both legitimate paths still work.Next, propose a fictional unapproved package without installing it. The workflow should stop at the review boundary and report what approval is missing. Repeat with an unreviewed version of an approved package and with the same name routed to a different registry.Test whether the agent can alter the expected digest or lockfile in the approval store. It may be permitted to edit its proposal, but that edit must not silently modify the policy against which the proposal is checked.Use a harmless local package fixture to test lifecycle-script handling in an isolated environment. The script can write a unique marker to the disposable working directory. Observe whether installation runs it, whether the script suppression setting is applied and whether the workflow can bypass that setting through another command. Do not run unknown registry packages to make this test realistic.Test new names, versions, sources and install hooks in a disposable environment without credentials.Finally, compare the resolved dependency set with the approved one. Record the package-manager version, configuration, lockfile and artifact identifiers. A clean installation in one configuration is not evidence about a different machine that uses another registry or enables lifecycle scripts.Respond to the evidence you haveAn invented name that was never installed is a rejected proposal. A suspicious artifact that was downloaded but never executed requires investigation of how the tooling handled it. Installation or import introduces additional questions about code execution and available credentials. Keep these stages distinct in the incident record.If unknown code ran in a privileged environment, stop using that environment for further secrets or releases. Preserve the relevant logs and artifacts, assess what was reachable, and follow the affected platform’s incident procedures. Deleting the dependency line does not establish that its code had no effect.The enduring control is an accountable installation path: a justified dependency, verified project identity, reviewed artifact set and a constrained execution environment. The agent can keep suggesting ways to finish the job. The installer should continue requiring a decision about the actual software it is about to run.Sources RegisterSource: the authors’ USENIX publicationSource: USENIX author articleSource: Python Packaging User GuideSources: npm’s scripts documentationnpm ciSource: pip secure installsSource: Python packaging name normalizationSource: pip install referenceSource: GitHub Actions secure-use referenceBeagle Lesson #4: How to Check a Package Before an AI Agent Installs It was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.