Lesson · Security & Robustness Essentials
Safe Input & Data Handling
55 min readSafe Input & Data Handling
Security starts by treating external data as untrusted. Validate structure, avoid code-evaluation shortcuts, handle paths safely, and keep shell interpretation out of data flows unless you truly need it.
Learning goals
- Validate external data at the boundary with explicit checks that reject invalid input and name the failed rule.
- Explain why
evalturns input into executable code, and parse literals withast.literal_evalorjsoninstead. - Build a target path with
Path, resolve it, and confirm with.parentsthat it stays under the expected root. - Pass command arguments to
subprocessas a list and say whatshell=Truewould reinterpret. - State one input that
ast.literal_evalrejects whileevalhappily executes.
Mental model
The boundary is where trust stops: text crossing into your program is data until a check says otherwise. Parsing extracts structure without executing anything, and paths and commands stay data by construction, through a containment check and an argument list rather than an assumption that the sender was friendly.
Mental model
read it top to bottom
untrusted text arrives ↓ is it data or code? data: parse it with json or ast.literal_eval never hand it to eval ↓ does it name a location? build it with Path, resolve(), check it stays under the root ↓ does it name a command? pass an argument list, keep the shell out of it
Core idea
Untrusted input is the root of most injection bugs: the moment a string is executed, resolved into a filesystem target, or pasted into a shell command, the sender gains a say in what your program does. The defensive move is structural: parse data with a format parser instead of an expression evaluator, keep resolved paths inside their root, and hand subprocess arguments over as a list. Validation then confirms the shape you expect, so the rest of the code reasons about a small set of known cases.
Input validation
Input validation should happen at a boundary where invalid data can be rejected with a useful error. Keep validation rules explicit and avoid silently converting values in ways that hide mistakes.
Avoiding eval
eval executes Python expressions and therefore turns input into code. Prefer a parser for the expected data format, such as JSON or ast.literal_eval for limited Python literals.
ast.literal_eval
ast.literal_eval parses only Python literal structures rather than arbitrary executable expressions. It is safer than eval, although extremely large or malicious inputs can still consume resources.
Safe path handling
Safe path handling means treating a path string from outside the program as a candidate rather than a destination. Build it as a Path, call resolve() to fold away . and .., and confirm that the expected root appears in the resolved path's parents before any file operation. A prefix check on the raw string is not enough, because containment is defined by directory segments, not by a shared start to the characters.
Command injection basics
Command injection occurs when untrusted data becomes shell or command syntax. Pass argument arrays directly to subprocess APIs and avoid a shell unless shell features are genuinely required.
Shell invocation cautions
Shell invocation cautions are about what shell=True adds: the string is handed to the system shell, which interprets quotes, pipes, ;, and wildcards before any program runs. Passing an argument list to subprocess.run skips that interpretation layer, so each element reaches the target program as one literal argument. Use a shell only when you deliberately need a shell feature and the text is not controlled by whoever sent it.
Walkthrough
(root / user_name).resolve()builds the absolute target first:/joins the segments andresolve()folds away.and.., so the check sees the path the filesystem would actually use rather than the raw text.root = root.resolve()normalizes the other side of the comparison as well. With the root left unresolved, comparing it against an absolute candidate would be unreliable.if root not in candidate.parentsenforces containment before any file operation:"user-123/file.txt"resolves under/tmp/uploadsand passes, while"../etc/passwd"resolves outside and raisesValueError("path escapes root").- The function returns a
Path, not a string, so callers keep filesystem semantics. Predict before running: whatsafe_child(root, "../secrets.txt")raises, and whether"user-123"itself (the directory, not a child) passes theparentscheck.
Experiments to try
- Call
safe_childwith"user-123/file.txt","../secrets.txt","user-123/../../escape.txt", and"/etc/passwd"; record which inputs raiseValueErrorand which pass. - Compare
eval("1 + 1"),ast.literal_eval("1 + 1"), andast.literal_eval("[1, (2, {'a': 3})]"); note which input each parser accepts and the exact exception the others raise. - Feed
{'name': 'Ada', 'score': 98}to bothjson.loadsandast.literal_eval, then repeat with{"name": "Ada", "score": 98}and note that each parser accepts exactly one of the two spellings. - Run
subprocess.run([sys.executable, "-c", "import sys; print(sys.argv[1])", payload])withpayload = "x; echo injected", then build the same command as one shell string and compare what arrives.
Common mistakes
- Treating validation and escaping as interchangeable: validation decides whether data is acceptable, while escaping changes how special characters are interpreted at the next boundary, so passing a check never removes the need to quote correctly later.
- Passing untrusted text to
evalor toshell=True: both hand the string to something that executes it, so__import__("os").system("...")or; rm -rf buildbecomes program behavior instead of remaining data. - Checking a path with
str.startswith("/tmp/uploads"): a sibling such as/tmp/uploads-evilshares the prefix without living inside the directory, so containment must be decided on resolved paths and segment boundaries, assafe_childdoes with.parents. - Assuming
ast.literal_evalis free because it is safe: it still parses and allocates the whole structure, so an oversized literal can consume memory and time even though it cannot execute code.
Practice: Easy
- Run the worked example, then call
safe_child(root, "../secrets.txt")and record the exact exception class and message. Repeat with"user-123/../../escape.txt". - Feed
"[1, (2, {'a': 3})]"toast.literal_evaland tojson.loads; record which one succeeds and the exception the other raises. - Write
is_safe(root, candidate)that returnsTrueorFalseusing the sameresolve()andparentslogic instead of raising, and test it with one accepted and one rejected path.
Practice: Medium
- Extend
safe_childto reject an absoluteuser_nameand an emptyuser_namebefore resolving, each with its ownValueErrormessage; demonstrate both rejections. - Take a snippet that parses a config string with
eval, replace it withast.literal_evalwrapped so a failure raisesValueError("expected a Python literal"), and show one input thatevalaccepted while the new version rejects it. - Run
subprocess.run([sys.executable, "-c", "import sys; print(sys.argv[1])", payload])and a shell-string version withpayload = "x; echo injected"; explain the difference in what each child receives.
Practice: Hard
- Build an upload gate that parses a JSON manifest with
json.loads, requires a stringnameand an integersizethat is not negative, rejects anything else with aValueErrornaming the offending key, and passesnamethroughsafe_child; test one valid case and three rejections. - Build a parser comparison for
eval,ast.literal_eval, andjson.loadsover four inputs ("1 + 1","{'a': 1}",'{"a": 1}',"__import__('os').getcwd()"), recording result or exception for each, and state which parser belongs at which trust boundary. - Review a call of the form
subprocess.run("grep " + pattern + " " + filename, shell=True), rewrite it with an argument list, and list which inputs change meaning between the two versions (spaces, quotes,;,*), explaining the mechanism for each.
Lesson checklist
- I can explain why
evalon external text is a code-execution bug rather than a style preference. - I can parse a literal string with
ast.literal_evaland name one input it rejects thatevalexecutes. - I can build a target path, resolve it, and test containment with
.parentsbefore touching the filesystem. - I can pass subprocess arguments as a list and state what
shell=Truewould reinterpret in the same text.
Remember
External data stays data: validate its shape at the boundary, parse literals with `ast.literal_eval` or `json` instead of `eval`, confirm that resolved paths still live under their root, and hand commands over as argument lists. The worked example's `safe_child` shows the full path pattern: resolve both sides, compare segments through `.parents`, and raise a specific `ValueError` when the check fails.
Interview angles
What is the main purpose of **Input validation**?+
Input validation should happen at a boundary where invalid data can be rejected with a useful error. Keep validation rules explicit and avoid silently converting values in ways that hide mistakes.
What should you pay attention to when using **Avoiding eval**?+
eval executes Python expressions and therefore turns input into code. Prefer a parser for the expected data format, such as JSON or ast.literal_eval for limited Python literals.
How does **ast.literal_eval** fit into this lesson?+
ast.literal_eval parses only Python literal structures rather than arbitrary executable expressions. It is safer than eval, although extremely large or malicious inputs can still consume resources.
Why can a `str.startswith` check on a path reject the wrong files or accept the wrong ones?+
A string comparison works on characters, not directory segments: /tmp/uploads-evil shares the prefix /tmp/uploads without being inside that directory. Containment has to be decided on resolved Path objects, as safe_child does by checking the root against candidate.parents.