The Complete Production SOP: How to Deploy and Run Path Traversal Defense & Canonical Path Sanitizer in Autonomous AI Agents
Step-by-step SOP to install and run Path Traversal Defense & Canonical Path Sanitizer in Codex, Claude Code, and Cursor. Includes verified security prompts.
Technical Overview & Architectural Context
Autonomous coding agents frequently generate vulnerable file-handling logic when implementing asset download, upload, or file retrieval endpoints. When asked to fetch a file from disk, models routinely rely on naive string concatenation (e.g., path.join(uploadDir, userInput)) or regex-based blacklist scrubbing (e.g., removing '../'). These naive mitigations fail against nested traversal sequences ('....//'), URL-encoded dot segments ('%2e%2e%2f'), null byte poisoning in legacy runtimes, or symlink dereference attacks that point outside the expected workspace. Without explicit, deterministic boundaries, LLMs also suffer from context drift—often introducing inconsistent sanitizers across Express, Fastify, Flask, or Next.js API routes within the same repository. By mounting the 'path-traversal-canonical-sanitizer' skill, agents are forced to abandon blacklist approaches in favor of strict canonicalization: resolving absolute realpaths via os.path.realpath() or path.resolve(), enforcing strict base-directory prefix verification, and decoupling raw user filenames from filesystem storage keys.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local agent skill manifest directory and inject verified procedural rules into your IDE or workspace config.
Agent engines inspect project-level and user-level skills directories (.agents/skills/ or .claude/skills/) to establish runtime guardrails. Mounting the skill at project root ensures deterministic rule invocation across Cursor, Windsurf, Codex, and Claude Code.
mkdir -p .agents/skills/path-traversal-canonical-sanitizer && curl -fsSL https://askills.dev/api/skills/path-traversal-canonical-sanitizer/raw -o .agents/skills/path-traversal-canonical-sanitizer/SKILL.md---
name: "path-traversal-canonical-sanitizer"
description: "Prevent unauthorized file system access by strictly validating and canonicalizing paths."
metadata:
author: "OWASP"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "prevent path traversal"
- "sanitize file download path"
- "validate path stays in base directory"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Path Traversal Defense & Canonical Path Sanitizer
Defends file serving and download endpoints against directory traversal attacks (../): resolving canonical realpaths, validating paths stay within root base directories, and stripping null bytes.
## Execution SOP & Rules
1. Resolve target path to absolute canonical path using path.resolve() or os.path.realpath().
2. Verify canonical path starts with base directory: resolvedPath.startsWith(baseDirectory + path.sep).
3. Reject or strip directory separator characters (/ and \) from filenames intended for storage.
4. Use random UUIDs or database IDs on the filesystem rather than user-provided filenames.Mounting the skill in the project root (.agents/skills/) allows the agent runtime to dynamically reference rules via index pointer, consuming fewer than 180 tokens compared to dumping large custom prompts into every chat interaction.
Ensure directory permissions grant read access to your agent runtime (chmod 644 SKILL.md). When fs_write is locked to 'workspace', Codex or Claude Code will fail if an untrusted path resolves outside the repository boundary.
Environment Secrets & Dependency Validation
Validate required core runtime modules and ensure safe filesystem configurations without hardcoding absolute server paths.
Canonical path verification requires standard platform-native path and filesystem libraries (Node.js 'node:path' and 'node:fs', or Python 'pathlib' and 'os'). Base storage directories must be dynamically computed relative to process.cwd() or validated environment variables rather than hardcoded string paths.
test -f package.json && node -e "require('node:path'); require('node:fs')" || python3 -c "import pathlib, os"import path from 'node:path';
import fs from 'node:fs';
export function resolveSafePath(baseDir: string, untrustedPath: string): string {
const safeBase = path.resolve(baseDir);
const resolved = path.resolve(safeBase, untrustedPath);
// Ensure base boundary with platform-specific separator to prevent prefix collision
if (!resolved.startsWith(safeBase + path.sep) && resolved !== safeBase) {
throw new Error('ACCESS_DENIED: Path traversal detected');
}
// Check realpath to defeat symlink bypasses if file/dir exists
if (fs.existsSync(resolved)) {
const canonical = fs.realpathSync(resolved);
if (!canonical.startsWith(safeBase + path.sep) && canonical !== safeBase) {
throw new Error('ACCESS_DENIED: Symlink traversal detected');
}
return canonical;
}
return resolved;
}Always append path.sep to the base directory check. If baseDir is '/var/data', a path resolving to '/var/data_secret/file.txt' passes startsWith('/var/data') unless you enforce startsWith('/var/data/').
Avoid passing user input to fs.existsSync without prior path.resolve canonicalization; in unpatched older runtimes, null byte injections (%00) can truncate filenames.
Intent Matching & Trigger Invocation
Trigger the deterministic sanitization SOP in Codex, Claude Code, Cursor, or Windsurf using exact semantic phrases.
Natural language triggers in the SKILL.md frontmatter alert the agent's planner to bind to this procedural rule set when generating or refactoring file-access logic.
claude "Refactor our static asset serving route to sanitize file download path and validate path stays in base directory."Include the trigger phrase 'validate path stays in base directory' explicitly in your Cursor Composer or Claude Code prompt to ensure 100% deterministic adherence to canonical checks.
Do not instruct the agent to 'remove ../ characters'. That prompt forces the agent into an anti-pattern blacklist mindset rather than canonical validation.
Verification, Linting & Output Quality Gate
Run automated test suites and negative boundary security checks before committing agent-generated code.
The skill mandates that the agent verify its own implementation using local test runners, passing traversal exploit payloads to assert proper exception handling.
npm test -- tests/safePath.test.ts || pytest tests/test_safe_path.pyimport { describe, it, expect } from 'vitest';
import { resolveSafePath } from '../src/utils/safePath';
import path from 'node:path';
describe('resolveSafePath Traversal Defense', () => {
const base = path.resolve('tmp/storage');
it('should allow valid relative paths within base directory', () => {
const target = resolveSafePath(base, 'reports/2026/report.pdf');
expect(target).toBe(path.join(base, 'reports/2026/report.pdf'));
});
it('should reject dot-dot directory traversal', () => {
expect(() => resolveSafePath(base, '../../etc/passwd')).toThrow('ACCESS_DENIED');
});
it('should reject sibling directory prefix collision', () => {
// tmp/storage vs tmp/storage_confidential
expect(() => resolveSafePath(base, '../storage_confidential/secret.key')).toThrow('ACCESS_DENIED');
});
});Check git diff before accepting the agent's pull request to ensure it did not modify the security boundaries defined in SKILL.md.
Watch out for tests that stub fs.realpathSync; mocked filesystem tests can mask critical platform-specific path separator flaws on Windows runtimes.
Real-World Scenario: Secure Express.js File Download Endpoint Against Traversal Exploits
“Review our Express download route in src/routes/download.ts. Sanitize file download path and ensure the requested file strictly validates and stays in base directory ./public/uploads.”
Runtime Troubleshooting & Failure Modes
Root Cause: The user input begins with a leading slash ('/documents/invoice.pdf') which path.resolve treats as root, resolving to '/documents/invoice.pdf' instead of concatenating to the base directory.
Strip leading path separators before resolution: const relativePath = untrustedPath.replace(/^[\\/]+/, ''); resolveSafePath(baseDir, relativePath);Root Cause: Invoking fs.realpathSync() on a path that has not yet been written to disk during an upload or write operation causes Node.js to throw ENOENT.
For write operations, verify the canonical parent directory using fs.realpathSync(path.dirname(resolvedPath)) instead of resolving the non-existent leaf file directly.Frequently Asked Questions (Path Traversal Defense & Canonical Path Sanitizer SOP)
Q:Can I use Path Traversal Defense & Canonical Path Sanitizer across Codex, Claude Code, and Cursor simultaneously?
Yes. The SKILL.md format complies with the open agent skill specification, which is parsed uniformly by Cursor, Claude Code CLI, Codex Desktop, and Windsurf via standard repository discovery.
Q:How does Path Traversal Defense & Canonical Path Sanitizer prevent context window overflow during long agent sessions?
The skill provides compact, procedural instructions and precise error signatures, removing the need to repeatedly feed lengthy OWASP documentation into prompt windows on every chat turn.
Q:Does this skill require escalated root or container permissions?
No. The skill is rated 98/100 on security, requiring zero network permissions and confining filesystem write capabilities strictly to the agent workspace.
Ready to equip your autonomous agent with Path Traversal Defense & Canonical Path Sanitizer?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.