Skip to main content
DigiTransact AI Learning Centre

Level 4 of 7 · 15 lessons

Large language model security

How text becomes an attack surface, and the controls that hold: least privilege, output validation and defence in depth. Follows OWASP guidance.

Suggested study time: 15 hours, including the lesson checks.

0 of 15 lessons marked done in this level. Progress stays in this browser.

Lessons

Open a lesson, read the short explanation, then answer the check. Each lesson links onward at the bottom of the level.

1. The LLM attack surface
A model application has more doors than the chat box suggests.

An LLM application includes the model, the system prompt, the user input, retrieved documents, tool calls, memory, plugins, the hosting API and the surrounding application code. Each is an entry point. The model itself is not the only target, and often not the easiest one.

Map the flow before testing. What text reaches the model, from where, with what privileges, and what can the output trigger? OWASP publishes a Top 10 for LLM applications that is a practical checklist for this mapping.

Take away
  • Map every text path into and out of the model.
  • Tools and retrieval widen the surface.
  • Use the OWASP LLM Top 10 as a checklist.
Check yourself: Which component is part of the attack surface?

2. Direct prompt injection
A user types instructions that compete with the system prompt, and the model has no hard boundary.

In direct injection, the user asks the model to ignore its rules, reveal hidden instructions or take an action it should refuse. The model is trained to follow instructions, so a carefully phrased request can outweigh a system prompt. This is OWASP LLM01.

There is no filter that closes this completely. Reduce impact instead: give the model the least privilege, require confirmation for actions, validate outputs, and keep secrets out of the prompt. Treat any instruction from a user as untrusted even when it sounds like an administrator.

Take away
  • System prompts are guidance, not a security boundary.
  • Limit what the model can do, not only what it can say.
  • Never place secrets in the prompt.
Check yourself: What is the most reliable mitigation for prompt injection?

3. Indirect prompt injection
The attack arrives inside a document, web page or email the model is asked to read.

Indirect injection hides instructions in content the model processes: a CV, a web page, a support ticket, a calendar invite or a code comment. The user is innocent. The model treats the content as data but also as text it can follow, and the payload may steer the answer or a tool call.

Treat all external content as untrusted. Separate data from instructions in the prompt design, strip or neutralise active content, summarise in a sandbox without tools, and require human approval before any action that writes, sends or pays.

Take away
  • Retrieved content can carry instructions.
  • Keep the tool-using step separate from the reading step.
  • Require approval for actions triggered by external text.
Check yourself: Where does indirect injection hide?

4. Jailbreaking and guardrail bypass
Jailbreaks are role play, framing and incremental pressure that erode a model's refusal.

Jailbreaks persuade a model to produce content its policy would otherwise refuse. Techniques include fictional framing, appeals to authority, splitting a request into harmless pieces, and long conversations that drift. They target the model's behaviour rather than your application logic.

Guardrails help but are probabilistic. For high-risk features, combine a classifier or rule check on inputs and outputs, a restricted tool surface, and monitoring for repeated attempts. Log refusals and near-misses, and review them weekly. Do not rely on a single vendor filter.

Take away
  • Jailbreaks are a behaviour problem, not only a wording problem.
  • Layer input and output checks.
  • Watch for repeated attempts from one account.
Check yourself: Why is a single content filter insufficient?

5. Sensitive information disclosure
A model can repeat what it was trained on, or what your application put in its context.

Disclosure happens when a model reveals personal data, credentials, internal documents or another user's content. Causes include training data memorisation, long context windows shared between users, verbose error messages and logs that store full prompts. This is OWASP LLM02.

Minimise what enters the context. Keep secrets out of prompts and logs. Isolate sessions so one user's data cannot appear in another's answer. Mask personal data before sending it to a third-party model, and confirm retention terms with the provider in writing.

Take away
  • Send the minimum data needed for the task.
  • Isolate sessions and scrub logs.
  • Confirm provider retention in writing.
Check yourself: What is the first control for personal data sent to a model?

6. System prompt exposure
Assume the prompt will be revealed, and design as if it already has been.

System prompts leak through direct requests, error output, client-side code, logs and support tickets. OWASP added system prompt leakage as LLM07 because teams were storing keys, internal URLs and business rules in the prompt and treating it as hidden.

Write prompts as if customers can read them. Keep secrets in environment variables and fetch them server side. Encode business rules in code where they can be enforced. If the prompt contains something you would not publish, move it.

Take away
  • Never store credentials or internal URLs in a prompt.
  • Enforce rules in code, not only in wording.
  • Review prompts before release as public content.
Check yourself: Where should an API key used by an AI feature live?

7. Insecure output handling
Model output is untrusted input to whatever consumes it next.

If an application renders model output as HTML, executes it as code, passes it to a shell or writes it into a database without checks, the model becomes a delivery route for injection. This is OWASP LLM05. The classic case is generated markup that contains a script.

Encode output for its destination, not for the screen alone. Allowlist the structures you accept, such as a strict JSON schema. Reject anything outside it. Never pass generated text to a shell or database query without parameterisation, and render in a sandbox when previewing generated pages.

Take away
  • Sanitise per destination: HTML, SQL, shell, file.
  • Validate generated JSON against a schema.
  • Render generated pages in a sandbox.
Check yourself: Model output is inserted into a web page. What is required?

8. Excessive agency
A model with broad tools can be talked into using them.

Excessive agency means the model can take actions beyond what the task needs: sending email, deleting files, moving money, changing permissions. OWASP LLM06. The risk grows when tools are broad, long-lived or shared across users.

Give narrow tools, scoped per user and per task. Prefer read over write. Require confirmation for destructive or financial actions. Expire tokens quickly, log every tool call with its arguments, and let a human stop the run. Test what happens when the model is asked, politely, to exceed its brief.

Take away
  • Narrow tools beat broad ones.
  • Require confirmation for irreversible actions.
  • Log every tool call with arguments.
Check yourself: Which design reduces agency risk most?

9. Handling untrusted external content
Anything from outside your boundary may be written to influence the model.

Web pages, emails, PDFs, spreadsheets, API responses and user uploads all carry text an attacker may control. When that text enters a context window, it competes with your instructions. Encoding alone does not help, because the model reads meaning, not markup.

Fence external content clearly, label it as data, and state that instructions inside it must be ignored. Where possible, process it with a tool-free model call and pass only a structured summary onward. Validate file types and sizes, and strip active content before storage.

Take away
  • Label external content as data, not instruction.
  • Summarise without tools before acting.
  • Validate uploads and strip active content.
Check yourself: What helps most when a model must read an untrusted document?

10. Retrieval-augmented generation security
RAG adds a knowledge base and a new way in.

Retrieval systems fetch documents and place them in the prompt. That improves accuracy and introduces risk: poisoned documents, documents from the wrong tenant, stale content and hidden instructions. Access control must be applied at retrieval, not after generation.

Filter by tenant and by user permission before the model sees anything. Keep provenance metadata, rank by trust as well as similarity, and expire documents. Test with a document containing an instruction to see whether the answer follows it.

Take away
  • Enforce access control at retrieval time.
  • Keep provenance with every chunk.
  • Test with documents that contain instructions.
Check yourself: Where must tenant isolation be enforced in a RAG system?

11. Vector database security
Embeddings are data, and the store needs the same controls as any database.

A vector store holds chunks and embeddings used for retrieval. Weaknesses include missing authorisation, shared namespaces, stale or deleted content still retrievable, and embedding inversion that can approximate the original text. OWASP LLM08 covers vector and embedding weaknesses.

Authenticate every client, scope namespaces per tenant, encrypt at rest, and apply deletion to embeddings as well as source documents. Log queries, rate limit them, and avoid storing secrets or unnecessary personal data in chunk metadata.

Take away
  • Scope namespaces and enforce authorisation.
  • Delete embeddings when the source is deleted.
  • Do not store secrets in metadata.
Check yourself: A document is deleted from the source system. What else must happen?

12. Model denial of service and cost abuse
Long inputs and runaway loops burn money before they break availability.

Unbounded consumption, OWASP LLM10, covers attacks that exhaust tokens, time or budget. A user can send huge inputs, force long outputs, open many parallel requests or trigger recursive tool loops. The first symptom is often an invoice.

Set input and output limits, per-user quotas, timeouts and concurrency caps. Cache repeated requests. Alert on cost anomalies and on sudden drops in average response quality. Put a hard spending limit in the provider console as a backstop.

Take away
  • Limit input size, output size and concurrency.
  • Set quotas per account and per day.
  • Alert on cost anomalies as well as errors.
Check yourself: Which control limits cost abuse most directly?

13. Securing AI APIs
The endpoint in front of the model needs the same care as any public API.

AI endpoints face credential theft, key abuse, injection, scraping and enumeration. Common mistakes include keys in client code, no authentication, verbose errors, unrestricted CORS and no rate limit. Some providers also support request signing or scoped keys, which are worth using.

Authenticate callers, authorise per feature, validate input size and schema, return generic errors, log request identifiers, and rotate keys. Keep model keys on the server. Monitor for unusual volumes and for prompts that look like extraction attempts.

Take away
  • Keys stay server side and rotate on a schedule.
  • Authenticate and authorise every caller.
  • Return generic errors, log detail internally.
Check yourself: Which mistake exposes an AI provider key most directly?

14. Guardrails and content validation
Guardrails reduce harm. They do not prove safety.

Guardrails are checks before and after generation: classifiers, allowlists, schema validation, redaction and rate limits. They catch known patterns and reduce obvious abuse. They are probabilistic and can be bypassed by novel phrasing, so they sit alongside permissions and monitoring.

Design for graceful failure. If a guardrail blocks, say why in plain language and offer a safe route. Log the decision, measure false positives weekly, and keep the rules reviewable by a person rather than buried in a vendor console.

Take away
  • Guardrails are one layer, not the wall.
  • Validate structure, redact personal data, log decisions.
  • Review false positives so the guardrail stays usable.
Check yourself: What is the right role for a content guardrail?

15. Testing an AI application
Test the system around the model, with the same rigour as any application.

Good testing covers injection, data leakage, tool misuse, output handling, cost limits and access control. Use a test set of prompts that includes hidden instructions in documents and requests to exceed scope. Record the expected behaviour before you run it.

Repeat tests after every prompt or model change, because behaviour shifts. Keep a regression suite and a sample of past incidents. Independent review helps, since the team that built the prompt tends to test what it expected.

Take away
  • Test injection, leakage, tools, output and cost.
  • Re-run after every model or prompt change.
  • Bring in a reviewer who did not write the prompt.
Check yourself: When should AI security tests be repeated?