A Python audit hook can report runtime events, but it is not a security boundary against hostile code.
Python audit hooks: observe an owned file open without claiming a sandbox
Operation contract
Inside a temporary directory, the program registers a hook that records only open events. Writing an owned receipt file causes an open event, and the result is reduced to a boolean. The hook stays installed for this short process; no private path or event arguments are printed.
Failure boundary
Python-level hooks can be bypassed by code with native memory access and cannot be removed after registration. Do not use this fixture to run untrusted plugins safely. Event arguments may contain sensitive paths, so filter and protect any production audit log. A hook can also raise, changing program behavior; observation and enforcement are different contracts.
Working program
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
observed_opens = []
def record_open(event, arguments):
if event == "open":
observed_opens.append(event)
sys.addaudithook(record_open)
receipt_file = Path(directory) / "receipt-47.txt"
receipt_file.write_text("paid", encoding="utf-8")
print("observed_open", bool(observed_opens))Output
observed_open TrueCosts and limits
Every observed event calls the hook. Production hooks should avoid heavy work and unbounded in-memory event lists, especially on file-intensive paths.
Common Mistakes
- A Python audit hook is not a sandbox.
- Do not log raw audit arguments without a data policy.
- Do not assume a registered hook can be removed later.
