How to Block Malicious File Writes in Autonomous Python Agents A developer released AgentWritePathResolver, a standalone Python standard-library script that validates and canonicalizes file paths proposed by autonomous LLM agents before any disk write occurs. The tool runs an eleven-step check covering directory traversal, symlink abuse, null bytes, control characters, hidden files, extension allowlists and workspace boundaries, returning an ALLOW or REFUSE verdict with a specific refusal reason. It requires Python 3.8 or higher and no external packages. Autonomous AI agents, automated coding assistants, and Large Language Model LLM tool executors frequently need to write files to disk. However, accepting a file path generated by an AI model introduces substantial security risks. If an agent hallucinates, encounters prompt injection, or attempts to modify files outside its target directory, it can overwrite system configurations, expose private keys, or destroy version control history. Common attacks and edge cases include directory traversal such as ../../ , symlink abuse where a link points to an arbitrary location outside the project, embedded null bytes, non-printable control characters, and writes targeting sensitive files like .env or .ssh/authorized keys . The AgentWritePathResolver script provides a security policy engine designed specifically for these workflows. It inspects, canonicalizes, and verifies candidate file write paths before any modification is permitted on disk. The tool is implemented as a standalone script using only the Python standard library. It requires Python 3.8 or higher. No external packages need to be installed via pip . To set it up: agent write path resolver refuse writes whose.py . python agent write path resolver refuse writes whose.py --help You can integrate the resolver directly into your agent execution loop or tool-handling layer. Below is an example of importing the resolver inside a Python application to guard an agent tool function: python from pathlib import Path from agent write path resolver refuse writes whose import AgentWritePathResolver, PathVerdict, RefusalReason, Define the boundaries of the agent workspace workspace = Path "/tmp/agent workspace" workspace.mkdir parents=True, exist ok=True Initialize the resolver with custom rules resolver = AgentWritePathResolver workspace root=workspace, deny hidden=True, allowed extensions= ".py", ".txt", ".json", ".md" , disallow symlinks=True, Test candidate paths proposed by an agent candidates = "safe file.py", "../../etc/passwd", "notes/todo.md", ".env", "script\x00.py", for candidate in candidates: result = resolver.resolve candidate if result.verdict == PathVerdict.ALLOW: print f" ALLOWED {candidate} - {result.resolved path}" else: print f" REFUSED {candidate} - Reason: {result.reason} {result.message} " When evaluated, paths escaping the root or matching protected rules are flagged with PathVerdict.REFUSE , halting execution before any disk write operation occurs. The resolver executes an eleven-step validation sequence against the requested path. It validates the input string, checks system constraints, traces ancestor paths for symbolic links, verifies boundaries, and inspects pattern denylists. Before resolving the path on the file system, the resolver checks for control characters and null byte injection attempts: 1. Null byte detection if "\x00" in candidate: return ResolutionResult candidate path=candidate, verdict=PathVerdict.REFUSE, reason=RefusalReason.NULL BYTE DETECTED, message="Candidate path contains prohibited null byte injection vector .", workspace root=str self.workspace root , 2. Control characters detection if re.search r" \x01-\x1f\x7f ", candidate : return ResolutionResult candidate path=candidate, verdict=PathVerdict.REFUSE, reason=RefusalReason.CONTROL CHAR DETECTED, message="Candidate path contains non-printable control characters.", workspace root=str self.workspace root , If the candidate path passes sanitization, the resolver checks whether the provided workspace directory actually exists. If the workspace does not exist or is not a directory, it returns RefusalReason.WORKSPACE NOT FOUND . Agents often target files that do not yet exist. Calling standard resolve directly on non-existent paths on some platforms can fail to expand intermediate symlinks correctly. The safe canonicalize method resolves intermediate directories step-by-step from the root downward. This ensures that if any parent directory is a symbolic link leading outside the workspace, the link is detected: php def safe canonicalize self, path: Path - Tuple Path, bool : symlink encountered = False parts = path.parts if not parts: return path.resolve , False Build incrementally from anchor current = Path parts 0 for part in parts 1: : current = current / part if current.is symlink : symlink encountered = True try: current = current.resolve except RuntimeError: Possible circular symlink symlink encountered = True break resolved = current.resolve return resolved, symlink encountered If disallow symlinks=True is configured and an intermediate path component is a symlink, the operation is refused with RefusalReason.SYMLINK ESCAPE . Once canonicalized, the target path must reside strictly within self.workspace root . The helper method is subpath uses Path.relative to to confirm containment: php @staticmethod def is subpath target: Path, base: Path - bool: try: target.relative to base return True except ValueError: return False If the resolved target passes the boundary check, the relative path is checked against DEFAULT DENY PATTERNS . This built-in denylist rejects modifications to sensitive project files and directories: .git , /.git/ .env , .pem , .key , .id rsa .ssh/ , /authorized keys .bashrc , .zshrc , .profile .vscode/ , /node modules/ Additionally, if deny hidden=True is enabled, any path component containing a leading period such as .config/test.json triggers RefusalReason.HIDDEN TARGET REFUSED . Finally, the resolver checks for extension constraints, directory collisions, and write permissions on existing files. While AgentWritePathResolver prevents common path manipulation exploits, you should be aware of the following architectural limitations: .env and .git , but it cannot anticipate every custom secret or proprietary configuration file name your system may use. Custom patterns should be explicitly supplied via deny patterns . Why does the resolver track symlinks if it already checks the final resolved path? Even if a symlink resolves to a location inside the workspace, allowing agents to navigate or create symlinks can lead to loops, bypass naming rules, or alter files across logically separated subdirectories. Setting disallow symlinks=True blocks symlink traversal entirely. Can an agent target an absolute path that happens to be inside the workspace? Yes. If an agent passes /path/to/workspace/file.txt , the resolver evaluates the absolute path directly. As long as it resides within the configured workspace root and satisfies all pattern and extension rules, the verdict will be PathVerdict.ALLOW . If it falls outside the root, it returns RefusalReason.ABSOLUTE PATH ESCAPE . How does the tool handle writes to existing read-only files? Before returning an approval verdict, the resolver checks whether the target file exists. If it exists and os.access target, os.W OK returns False , the operation is refused with RefusalReason.EXISTING FILE READONLY rather than failing mid-write. Full version and the rest of the toolkit: Agent write path resolver refuse writes whose on PyForge https://py-forge.com/products/agent-write-path-resolver-refuse-writes-whose?utm source=devto&utm medium=article&utm campaign=agent-write-path-resolver-refuse-writes-whose . Product page: https://py-forge.com/products/agent-write-path-resolver-refuse-writes-whose https://py-forge.com/products/agent-write-path-resolver-refuse-writes-whose