Security review: keys, data boundaries and abuse cases
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Audit an AI feature for secret exposure, data-boundary and abuse risks using a fixed review checklist.
- Separate controls that reduce the likelihood of an attack from controls that reduce its impact, and state residual risk honestly.
- Trace a deterministic mock that redacts secret-shaped tokens and blocks disallowed tool arguments before any side effect.
Overview
#Security is a review process, not a feature
Lesson ai-engineering-prompt-injection-and-data-boundaries showed how untrusted text can steer a model. This lesson turns that awareness into a repeatable review you run before an AI feature ships. A security review asks four questions in order: where do secrets live, where does data cross a boundary, what can the model cause to happen, and what happens when someone attacks it on purpose.
Secrets never reach the client
The single most common AI security defect is a provider API key shipped to the browser. Any key in client JavaScript, a public build-time variable, a mobile bundle or a system prompt is public the moment it ships. Keys belong on the server, behind a proxy endpoint that your client calls; the client never sees the credential. Treat the system prompt as public too: it is part of the model input and can be extracted, so it must not contain secrets, internal URLs or credentials.
Data boundaries
Every AI feature has at least three boundaries: user to model, retrieved data to model, and model output to the user or a downstream system. A review names each one and states the rule that holds at it. Retrieved documents from one tenant must never appear in another tenant's context. Personally identifiable information should be minimized before it enters a prompt and redacted before it enters logs. Model output that flows into a database, an email or a shell needs the same validation as any untrusted input, because the model can be steered by the data it read.
Abuse cases, not just bugs
Attackers do not use your feature the way you designed it. Review for prompt injection through retrieved content and tool results, tool misuse through crafted arguments, data exfiltration through tools that can both read and send, and cost amplification where a loop or a large context is triggered repeatedly. Each abuse case maps to a control: allowlists for tool arguments, path restrictions for file tools, rate and budget ceilings, and audit logs that record what the model asked for and what was executed.
Mitigate likelihood and impact separately
A useful review separates controls that reduce how often an attack succeeds from controls that reduce the damage when it does. Delimiters and an instruction hierarchy reduce likelihood but are not guarantees. Least-privilege tools, output validation, redaction and human approval gates reduce impact. Honest reviews state residual risk: after all controls, what can still go wrong, and how would you detect it.
A deterministic redaction and gate mock
The exercises use a deterministic local mock, so no key and no network are involved. The redactor removes any whitespace-delimited token that starts with a sensitive prefix; the tool gate checks a call against an allowlist of tool names, argument keys and path prefixes. Both are pure functions you can trace by hand.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement redactSecrets(text, prefixes). Split text on single spaces, replace any token that starts with one of the given prefixes with the literal [REDACTED], and join the tokens back with single spaces. It must not throw for an empty prefixes array.
starter.javascriptfunction redactSecrets(text, prefixes) { // Split on single spaces, replace any token that startsWith one of the // prefixes with "[REDACTED]", and join back with single spaces. }Reveal the reference answer
reference.javascriptfunction redactSecrets(text, prefixes) { return text .split(" ") .map((token) => (prefixes.some((prefix) => token.startsWith(prefix)) ? "[REDACTED]" : token)) .join(" "); } console.log(redactSecrets("key sk-live-abc123 and password=hunter2", ["sk-live-", "password="]));Authored expected output: key [REDACTED] and [REDACTED]
Tokens sk-live-abc123 and password=hunter2 start with a sensitive prefix and become [REDACTED]; the words key and and are untouched. Redaction at the boundary keeps secrets out of logs and prompts, but it is a mitigation: it only catches the shapes you list.
Exercise 2Implement
Implement checkToolCall(policy, toolName, args). policy maps a tool name to { allowedArgs, pathPrefixes? }. Return { allowed: false, reason } when the tool is unknown, when args has a key outside allowedArgs, or when pathPrefixes is set and args.path is not a string starting with one of the prefixes. Otherwise return { allowed: true, reason: "ok" }.
starter.javascriptconst TOOL_POLICY = { readFile: { allowedArgs: ["path"], pathPrefixes: ["/docs/"] }, sendEmail: { allowedArgs: ["to", "subject"] } }; function checkToolCall(policy, toolName, args) { // Unknown tool -> not allowed. // Any args key outside allowedArgs -> not allowed. // If pathPrefixes is set, args.path must be a string that starts with one. // Otherwise allowed with reason "ok". }Reveal the reference answer
reference.javascriptconst TOOL_POLICY = { readFile: { allowedArgs: ["path"], pathPrefixes: ["/docs/"] }, sendEmail: { allowedArgs: ["to", "subject"] } }; function checkToolCall(policy, toolName, args) { const rule = policy[toolName]; if (rule === undefined) return { allowed: false, reason: "unknown tool" }; for (const key of Object.keys(args)) { if (!rule.allowedArgs.includes(key)) { return { allowed: false, reason: "unexpected argument " + key }; } } if (rule.pathPrefixes !== undefined) { const value = args.path; if (typeof value !== "string" || !rule.pathPrefixes.some((prefix) => value.startsWith(prefix))) { return { allowed: false, reason: "path outside allowed prefixes" }; } } return { allowed: true, reason: "ok" }; } console.log(JSON.stringify(checkToolCall(TOOL_POLICY, "readFile", { path: "/etc/passwd" })));Authored expected output: {"allowed":false,"reason":"path outside allowed prefixes"}
The call names a known tool with an allowed argument key, but /etc/passwd does not start with /docs/, so the gate blocks it. Note the limitation: a prefix check alone does not catch /docs/../secrets.txt, so production code must also normalize the path before the check; the predict exercise shows that gap.
Exercise 3Predict
Using checkToolCall and TOOL_POLICY, predict the JSON array logged by mockGate. Trace each call: the tool must be known, every argument key must be allowed, and a readFile path must start with /docs/. Pay attention to the second call, which escapes through a parent-directory segment.
starter.javascriptfunction mockGate(calls) { return calls.map((call) => checkToolCall(TOOL_POLICY, call.tool, call.args).allowed); } const calls = [ { tool: "readFile", args: { path: "/docs/policy.md" } }, { tool: "readFile", args: { path: "/docs/../secrets.txt" } }, { tool: "sendEmail", args: { to: "a@b.com", subject: "hi", body: "text" } }, { tool: "deleteAll", args: {} } ]; console.log(JSON.stringify(mockGate(calls)));Reveal the reference answer
reference.javascript// Predicted output: // // [true,true,false,false] // // Trace: call 1 readFile /docs/policy.md passes every check -> true. // Call 2 readFile /docs/../secrets.txt starts with "/docs/" as a raw string, // so the naive prefix check passes -> true, even though the path escapes the // directory. Call 3 sendEmail carries an unexpected argument "body" -> false. // Call 4 names an unknown tool -> false.Authored expected output: [true,true,false,false]
The third and fourth calls are blocked for the right reasons. The second call is the lesson: a raw startsWith prefix check accepts /docs/../secrets.txt, so a path-allowlist control must normalize the path before comparing prefixes. This is why a prefix check is a mitigation, not a guarantee.
Exercise 4Explain
Knowledge check: in a browser-facing AI feature, where must the provider API key live?
starter.text// Choose the correct option.Reveal the reference answer
reference.textOn the server, inside a backend proxy endpoint that the client calls. The client never receives the credential, so a leaked bundle, a curious user or a network inspector cannot extract it.Authored expected output: On the server, behind a backend proxy the client calls
Any key in client code, a public build-time variable or the system prompt is public once shipped. The other options all expose the credential to the client.
Common misconceptions
#- Myth: a key stored in a build-time environment variable is safe because it is not in source control. Fact: any value bundled into client code ships to every user, so build-time variables for the browser are public.
- Myth: the system prompt is hidden from users. Fact: the system prompt is model input and can be extracted, so it must never hold secrets or credentials.
- Myth: an allowlist of tool names is enough to make tool calls safe. Fact: an allowed tool can still be misused through crafted arguments, so argument keys, value shapes and path prefixes need their own checks.
Follow-up practice
#- ai-engineering-reliability-slo-fallbacks
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.