Security basics for builders¶
What you'll be able to do¶
- Map assets, attackers, and trust boundaries before choosing defenses.
- Recognize common injection paths and put the right boundary around each one.
- Apply a small security checklist to an API or AI tool workflow, including detection and response.
Start with what can cross a boundary¶
Security begins with an asset worth protecting: an account, dataset, API key, or service availability. An attacker needs a path to it. A trust boundary is where data or authority passes between parties with different permissions: browser to API, API to database, or model to a file-reading tool.
Use four questions for a small threat model: What are we building? What can go wrong? What will we do about it? Did we do a good job? For a document search API: users query their own documents; one user could retrieve another's results; scope queries by authenticated user; test cross-user requests and watch access-denied logs.
Never trust input means treat input as data until a boundary has checked and constrained it. Inputs include request bodies, headers, files, database records, retrieved documents, and model output. Client-side validation helps users but attackers can call the API directly. Use allowlist validation at entry points: accepted types, lengths, formats, and values. A 10 MB request limit is a capacity and security boundary. Validation cannot fix every injection bug; the next boundary still needs the destination's safe API.
Reduce attack surface with fewer endpoints and least privilege for each process. Use defense in depth so one mistake does not grant access to everything. Fail closed: if a permission check fails, deny the action.
Keep data out of command and query syntax¶
Injection happens when data is interpreted as instructions. This SQLite example builds SQL by concatenation; a name such as ' OR 1=1 -- can change the WHERE clause and return every row:
query = "SELECT id, name FROM users WHERE name = '" + name + "'"
rows = conn.execute(query).fetchall() # unsafe
Pass values separately. The database driver treats name as a value, even when it contains quote marks:
The same principle applies to operating system commands. subprocess.run("tool " + user_text, shell=True) asks a shell to parse the whole string. Prefer an allowlisted command and an argument list: subprocess.run(["tool", user_text], timeout=2, check=True). No shell parses the argument, but the tool still interprets it: a value starting with - may be read as an option. A timeout limits a stuck child process; it does not make an unsafe tool safe. Validate which tool can run and which arguments it accepts.
A path such as ../private/key can escape an upload directory. Reject absolute paths and traversal components; resolve the final path and check it remains under the base. Symbolic links can redirect a safe-looking path, and concurrent file changes can defeat a simple check. Sensitive file operations need directory-relative, race-resistant OS APIs.
Validate inputs; encode outputs¶
Validate data's shape: a username might have a maximum length and limited characters; an upload needs a size cap. When displaying data, encode for the output context. HTML text, attributes, JavaScript strings, CSS, and URLs have different rules. For HTML text, html.escape(comment, quote=True) converts < and quotes into harmless text. Template automatic escaping helps only when enabled in the right context. Raw comments can create cross-site scripting (XSS); untrusted template source can cause template injection.
Deserialization crosses another boundary. pickle can execute code while loading; do not load untrusted pickle files, including model artifacts. Avoid unsafe YAML loaders for untrusted input. Prefer a data-only format and validate the resulting structure. Treat dependencies, datasets, and retrieved content as untrusted too.
Server-side request forgery (SSRF) occurs when your server fetches a URL chosen by someone else. The request can reach addresses the caller cannot reach directly. A host allowlist and scheme checks help, but DNS answers and redirects can change the destination after validation. A production fetcher needs network-level egress limits and checks at the point of connection.
Protect data in transit and at rest¶
Use TLS on service network connections, including internal hops. Verify certificates; turning verification off removes the identity check. HSTS tells browsers that have received the policy to use HTTPS for that host for a specified period, without letting users click through certificate errors. It does not fix a broken TLS deployment.
Encryption at rest is useful, but its practical question is who can access the keys and how keys are rotated and recovered. Encryption is reversible with a key; hashing maps data to a digest and is not meant to be reversed. Do not use an ordinary fast hash as a password store. Authentication basics covers password handling and login boundaries, while config and secrets covers keeping credentials out of source code.
Know what browser defenses do¶
CORS is a browser rule about which origins may read a cross-origin response. It is not API authentication: scripts, command-line clients, and servers can still send requests. Do not reflect arbitrary origins while allowing credentials. A literal * origin also cannot authorize credentialed browser reads.
Cross-site request forgery (CSRF) matters when browsers automatically attach cookies to a request. An attacker can cause a victim's browser to send an action request. SameSite cookies reduce some cross-site sends; state-changing actions may also need CSRF tokens and careful origin checks. Neither replaces authorization on the server.
Security headers add browser-side constraints: Content Security Policy limits where page code can load from; X-Content-Type-Options: nosniff discourages MIME guessing; frame restrictions reduce clickjacking. Choose headers for the application rather than copying a bundle blindly. Rate limits help bound brute force and abusive traffic, but do not prove a caller is authorized; see rate limiting.
Prepare for mistakes and incidents¶
Keep a lockfile or pinned dependency set, review updates, and audit known vulnerabilities. Check package names for typosquatting before installation. Use minimal base images to reduce included software. An SBOM names the components in a build. Treat model weights and datasets from unknown sources as supply-chain inputs, especially formats that deserialize executable objects.
Use the OWASP Top 10 as a checklist to prompt review, not as a claim that every relevant risk is covered. Log security events such as failed logins, denied access, and unusual tool calls with enough context to investigate, while excluding secrets and unnecessary personal data. Alert on meaningful patterns rather than every single failure.
When an incident is suspected: contain the affected path, rotate exposed credentials, investigate what happened and which data was affected, then disclose to the appropriate people under your obligations. Preserve useful evidence during containment.
For AI engineers¶
For AI engineers
Your retrieval pipeline may put a web page or user document beside system instructions. That text can contain prompt injection: instructions that try to steer the model. The model is not a security boundary. Decide in code which tool calls are permitted, scope every call to the user's permissions, and validate arguments before a tool runs. A document asking the model to send a private file to a URL must remain document content, not authority.
Exfiltration can happen through tool calls or rendered links and images that include private data in a URL. Keep secrets and personal data out of prompts where possible, and treat model responses as untrusted before rendering them. Untrusted training data or retrieval content can poison answers or behavior. Sandboxing code-execution tools limits what a compromised workflow can reach. Audit model files before loading formats with executable deserialization, and log prompts only with a deliberate privacy and retention policy.
Common mistakes¶
- Building SQL strings from user input or using
shell=Truewith user data; use parameterized queries and argument lists. - Trusting browser validation or detailed error messages; validate on the server and avoid exposing stack traces or internal paths.
- Disabling TLS certificate checks to “fix” a connection error; fix certificates and trust configuration.
- Reflecting any CORS origin with credentials; restrict origins and still enforce authentication and authorization.
- Logging secrets or assuming a small service is beneath notice; automate secret filtering and prepare to rotate keys.
Check yourself¶
A search endpoint accepts a name containing ' OR 1=1 --. What should the safe query return, and why?
It should return only a row whose name is literally that string, usually none. A parameterized query passes the input as a value rather than SQL syntax.
A browser form limits upload paths to simple filenames. Can the server skip its own path check?
No. A caller can bypass the browser and send ../ or an absolute path directly. The server must reject traversal and ensure the resolved destination stays within the allowed directory.
Your API sets CORS to allow one web origin. Does that stop a script on another server from calling it?
No. CORS restricts what a browser page can read across origins; the API still needs authentication, authorization, and abuse controls.
A retrieved document tells an assistant to send its API key to a URL. What should enforce the boundary?
Tool and application code should deny access to the key and block an unauthorized network call. The model can read the document as data, but its text cannot grant permissions.
Lab¶
Build five small defensive functions in code/security-basics/. See how an unsafe SQL lookup behaves, then parameterize the safe lookup. Keep user paths within a base directory and run one allowlisted tool without a shell. Escape comments before HTML rendering, then validate URLs against a host allowlist. Read the README for each function's contract and for the URL guard's limits. Run: cd code/security-basics && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- Interactive: Designed to Scale: encryption
- Checklist: OWASP Top 10
- Your handbook: Software Engineering Handbook, ch. 12 “Bảo mật API”
See it in the wild¶
Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.



