Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python packaging: inspect an imported module origin before using it

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A module spec records the loader and origin selected by Python import resolution.

Download Python source kit

Operation contract

The fixture creates a package module inside an owned temporary directory and imports it through an explicit search path. It checks that the resolved file is the expected owned path before calling a function from the module. The procedure demonstrates provenance inspection in one local process; the example does not claim that a pathname alone authenticates code.

Failure and ownership boundary

An attacker controlling the directory can replace the file before or during import. Source code is executed during import, so an after-import origin check is too late as a security boundary. For received code, authenticate bytes before execution and run only trusted packages. Python package layout: owned imports and module entrypoints, Python module cache: repeated imports reuse an owned module object and Python artifact hashes: verify owned bytes against a separately trusted expectation cover these layers.

Working program

python
import importlib.util
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as directory:
    owned = Path(directory, "receipt_policy.py")
    owned.write_text("def limit():\n    return 500\n", encoding="utf-8")
    spec = importlib.util.spec_from_file_location("aitrove_owned_receipt_policy", owned)
    if spec is None or spec.loader is None or Path(spec.origin).resolve() != owned.resolve():
        raise ValueError("unexpected module origin")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    print("owned origin:", Path(spec.origin).resolve() == owned.resolve())
    print("limit:", module.limit())

Output

Output
owned origin: True
limit: 500

Costs and limits

Creating a spec and executing a module includes filesystem access and arbitrary module initialization cost. The example bounds the source to owned fixed bytes. Filesystem path equality is a diagnostic, not a signature or sandbox.

Common Mistakes

  • Do not import received code before deciding whether its bytes are trusted.
  • A path can change contents while a process is running.

Connected lessons

Python package layout: owned imports and module entrypoints, Python module cache: repeated imports reuse an owned module object, Python artifact hashes: verify owned bytes against a separately trusted expectation.

python
module-origin-check
Storage details