Building with AI Safely
Chapters and transcript
Building with AI Safely Your app has a new AI feature. A customer asks a question. The app passes it to the model, and the model can call tools that reach your database. But an attacker can also put text in front of the model. So treat the model as a powerful but untrustworthy component. In this lesson, you will learn the core security habits for building AI features.
Know your AI system Before writing code, draw a simple picture of the system, and ask five questions. What goes in? Who controls that input? What can the model do? What data can it reach? And where does the output go? Any input an outsider can influence may contain prompt injection. It cannot be fully prevented, so design for when it succeeds, not if.
Untrusted output Developers learn never to trust user input. Apply the same rule to model output. Watch. The model reads a page with attacker text. Its output now carries a script. The app inserts it into a web page as raw HTML. The script runs in other users browsers. That is cross-site scripting. If the app encodes the output first, the script shows as plain text and does nothing.
Untrusted output Here are the common problems when output is trusted too much. Raw HTML gives cross-site scripting. Joining strings into a database query gives SQL injection. Passing output to a shell gives command injection. Using it as a URL your server fetches can trick the server into calling internal systems. And running AI code automatically runs unsafe code without review.
Untrusted output Safe habits. Encode output before showing it in a web page. Most frameworks do this by default, so do not switch it off. Use parameterised queries, never string building. Validate structured output against a schema, and check values are in an allowed list. And never pass model output to a shell, unless it runs in a locked down sandbox.
Validate the output Here is validation in a small Python check. The allowed actions are check status and list orders. The model output asks for a different action, delete orders, perhaps because it read attacker text. The action is not in the allowed list, so the code raises an error and refuses. Remember this line. The model suggests. Your code decides.
Least privilege When a model can call tools, each tool is a door into your systems. Least privilege means giving each part only the access it truly needs. A risky design gives the model a run SQL tool and full access. A safer design gives it one narrow tool, get order status, with read-only access, a separate service account, and no network access it does not need.
Least privilege Use the user own permissions. A customer asks the bot about order ten forty two. The model calls the order tool. Your code checks who owns that order. It belongs to another customer, so the request is denied. A prompt line like only show users their own data is a request, not a rule. Real access checks happen in your code.
Quick check Quick check. A developer protects customer data by writing, only show users their own orders, in the bot system prompt. The tool behind it can read every order in the database. Is the data protected? Take a moment, then choose.
Human in the loop Some actions are too risky to leave to a model alone. Human in the loop means a person approves them first. Require approval for sending messages to outside people, paying or moving money, deleting or changing important data, and changing permissions, settings or accounts, or running commands on real systems. For decisions about people, the model should only suggest.
Human in the loop Make the approval screen clear. This one does not just say, the assistant wants to continue. It shows the recipient and the full email text. The reviewer reads it, checks the promise is allowed, and approves. A vague approval button teaches people to click without reading.
Protect keys and data Now protect your keys. If the AI key sits in browser JavaScript, anyone can open the code and read it. The attacker copies it and uses your account. The safe design: the browser calls your backend. The backend keeps the key in a secrets manager or environment variable, and calls the AI service itself. Also keep secrets out of prompts.
Protect keys and data Three more protections. Send only the data needed. If the model only needs the order date, do not send the whole customer record. Control costs and abuse. Every call costs money, so use rate limits per user, limits on input and output length, and budget alerts. And check your supply chain. Get open models, datasets and plugins from trusted sources.
Logging and testing You need to know what your AI feature is doing. Log user requests, the tools the model called, their inputs and results, and every approval or refusal. Then monitor for warning signs. In this log, a tool call fails, and a request goes to an unusual web address. Protect these logs, because they may hold personal data.
Logging and testing Test before release. Write test cases with injection attempts, like a document with hidden instructions, and check your limits hold. Repeat the tests when you change the model, the prompt or the tools. Only test systems you own or have written permission to test. And use the OWASP Top 10 for LLM Applications, a free list from the OWASP community, as a review checklist.
Key takeaways Before you release an AI feature, confirm each point. Output is encoded and validated. Tools are narrow, with least privilege. Access checks are in code, not the prompt. Risky actions need clear human approval. No secrets in prompts or client code. Rate limits and budget alerts are on. Tool calls are logged. And injection tests run before each release.
More and more apps include an AI feature, such as a chatbot, a summary button or an assistant that can take actions. If you are a developer, this lesson gives you the core security habits for building these features. The main idea is simple: an AI model is a powerful but untrustworthy component, and you must design around that.
Know your AI system
Before writing code, draw a simple picture of the system. Ask these questions:
- What goes in? User messages, documents, web pages, emails, database records?
- Who controls that input? Your own staff, logged-in customers, or anyone on the internet?
- What can the model do? Only write text, or also call tools and APIs?
- What data can it reach? Public information only, or customer and company data?
- Where does the output go? Shown to the user, saved in a database, run as code, sent as email?
Any input that an outsider can influence must be treated as possibly containing prompt injection. You learned in an earlier lesson that this cannot be fully prevented. So your design must limit what happens when an injection succeeds, not hope that it never does.
Treat model output as untrusted input
Developers learn to never trust user input. With AI, apply the same rule to model output. The model may have read attacker text, or it may simply make a mistake.
Common problems when output is trusted too much:
| If you do this with model output | The risk |
|---|---|
| Insert it into a web page as raw HTML | Cross-site scripting (XSS), where a script runs in other users' browsers |
| Build a database query by joining strings | SQL injection |
| Pass it to a shell command | Command injection, where the attacker's command runs on your server |
| Use it as a URL your server fetches | The server may be tricked into calling internal systems |
| Run AI-generated code automatically | Unsafe or harmful code runs without review |
Safe habits:
- Encode output before showing it in a web page, the same way you handle user input. Most modern web frameworks do this by default; do not switch it off.
- Use parameterised queries, never string building, for any database call.
- Validate structured output. If you ask the model for JSON, check it against a schema and reject anything that does not match. Check that values are in an allowed list.
- Never pass model output to a shell or to functions that run code, unless it runs in a locked-down sandbox.
A small example of validation in Python:
ALLOWED_ACTIONS = {"check_status", "list_orders"}
action = model_result.get("action")
if action not in ALLOWED_ACTIONS:
raise ValueError("Model asked for an action that is not allowed")
The model suggests; your code decides.
Least privilege for AI tools
When a model can call tools, each tool is a door into your systems. Least privilege means giving each part of the system only the access it truly needs.
Practical rules:
- Give each tool a narrow job. A tool called
get_order_status(order_id)is much safer than a tool calledrun_sql(query). - Use the user's own permissions. If a customer asks the bot about orders, the tool should only return that customer's orders, checked by your code, not by the model.
- Use read-only access wherever possible.
- Use separate service accounts for the AI feature, with their own limited credentials, so you can restrict and monitor them.
- Limit network access. If the model does not need to reach the internet or internal admin systems, block it.
Never rely on the system prompt for access control. A sentence like "Only show users their own data" is a request, not a rule. Real access checks must happen in your code.
Keep a human in the loop
Some actions are too risky to leave to a model alone. Human in the loop means a person reviews and approves an action before it happens.
Require approval for actions such as:
- Sending emails or messages to outside people
- Paying, refunding or moving money
- Deleting or changing important data
- Changing permissions, settings or accounts
- Running code or commands on real systems
Make the approval screen clear. Show exactly what will happen, for example the full email text and the recipient, not just "The assistant wants to continue". A vague approval button teaches people to click without reading.
For decisions about people, such as hiring, credit or access to services, the model should at most give suggestions. A person must make and be able to explain the final decision.
Protect data, keys and costs
Keep secrets out of prompts. Do not put passwords, API keys or internal details in the system prompt. Assume users can extract it.
Keep API keys on the server. The key for your AI provider must never appear in browser JavaScript or a mobile app, where anyone can find it. Call the AI service from your backend and store the key in a secrets manager or environment variable.
Send only the data needed. Do not send whole customer records to the model if it only needs the order date. Check your AI provider's terms about data storage and training, and choose settings that fit your privacy duties.
Control costs and abuse. Every model call costs money. Attackers or bots can run up large bills or slow your service. Use rate limits per user, set limits on input and output length, and set budget alerts with your provider.
Check your supply chain. If you download open models, datasets or plugins, get them from trusted sources and check them, as you would with any software library.
Logging and testing
You need to know what your AI feature is doing.
Log the important events: user requests, which tools the model called, with what inputs, the results, and any approvals or refusals. Protect these logs, because they may contain personal data, and follow your privacy rules on how long to keep them.
Monitor for warning signs, such as many failed tool calls, requests to unusual web addresses, sudden cost increases, or outputs that contain links you did not expect.
Test before release. Write test cases that include injection attempts, for example a document with hidden instructions, and check that your limits hold. Repeat the tests when you change the model, the prompt or the tools. Only test systems you own or have written permission to test.
A useful reference is the OWASP Top 10 for LLM Applications, a free list of common security risks in apps that use language models, published by the OWASP community. Use it as a checklist when you review your design.
Developer checklist
Before you release an AI feature, confirm each point:
- All model output is encoded, validated or checked before use.
- Each tool has a narrow job and the least privilege it needs.
- Access checks are in code, not in the prompt.
- Risky actions need clear human approval.
- No secrets are in prompts or client-side code.
- Rate limits, size limits and budget alerts are in place.
- Tool calls and approvals are logged and monitored.
- Injection test cases run before each release.
Check your understanding
Answer every question correctly to complete this lesson. If you miss one, try the quiz again.
1. An app takes text written by an AI model and inserts it straight into a web page as HTML. What is the risk?
2. An AI support bot needs to look up order status. Which database permission should it have?
3. Where should an API key for an AI service be stored in a web app?
Locked: answer every quiz question above correctly to complete this lesson.
Spotted a mistake or something unclear? Report a mistake