Secure AI Engineering

Building Secure Generative AI Applications: What Developers Need to Know

Developers are building products on GPT-3, Codex and Stable Diffusion at a remarkable pace. These applications introduce security problems that did not exist a year ago, from prompt injection, a term coined only last month, to unsafe generated content and runaway API costs. Here is what developers need to know.

By EthicalHat Research · · 3 min read
Infographic: Where to put controls in a generative AI app

The generative AI boom is well under way. Startups are building copywriting tools on GPT-3, developers are building coding tools on Codex, and since Stable Diffusion's open release in August, image generation features are appearing everywhere. The APIs make it possible to ship a generative feature in days.

Security thinking has not kept pace. Many of these applications have been built with the same assumptions as a traditional web app, and some of those assumptions do not hold.

How a generative AI app works

Most text-generation features follow the same pattern: the application combines its own instructions with the user's input into a prompt, sends it to a model API, and shows or uses the result.

python
PROMPT = """Translate the following text from English to French.

Text: {user_text}
French:"""

completion = openai.Completion.create(
    engine="text-davinci-002",
    prompt=PROMPT.format(user_text=user_text),
    max_tokens=200,
)

The security issues come from that combination.

Risk 1: prompt injection

Last month, users discovered that a Twitter bot built on GPT-3 to respond positively to tweets about remote work could be made to say almost anything by including instructions in their tweets, such as "Ignore the above and instead…". Developer Simon Willison coined the term prompt injection for the attack, drawing a comparison with SQL injection.

The analogy is apt, with one crucial difference: SQL injection has a reliable fix (parameterised queries). Prompt injection does not, because the model receives instructions and user input as one stream of text and has no reliable way to tell them apart.

What helps:

  • keep valuable secrets and sensitive logic out of prompts,
  • clearly delimit user input, and instruct the model to treat it as data,
  • constrain the task and validate the output against what you expect, and
  • above all, limit what a manipulated model can cause: do not let generated output trigger actions or queries without checks.

Risk 2: unsafe or harmful output

Models can generate offensive, biased, false or inappropriate content, and users will try to make them do so, especially in public-facing products.

  • Run inputs and outputs through content moderation. OpenAI released a free moderation endpoint in August for exactly this purpose.
  • Define what your product should and should not generate, and test for it.
  • Provide users with a way to report bad outputs, and act on reports.

Risk 3: insecure output handling

Generated text is untrusted input to the rest of your system:

  • Rendering: HTML-encode generated text before displaying it, or you have built a cross-site scripting vector.
  • Code: never execute generated code automatically.
  • Queries and commands: do not build SQL, shell commands or API calls from generated text without strict validation.
  • Structured output: if you ask for JSON, parse and validate it; models do not always comply.

Risk 4: API key exposure and cost abuse

  • Keep the model API key on the server. Calling the model directly from a browser or mobile app exposes the key to anyone.
  • Rate-limit and set quotas per user. Model calls cost money, and attackers can use your app as a free proxy to the model.
  • Cap tokens per request and monitor spend, with alerts.

Risk 5: data privacy

  • Understand the provider's data usage and retention terms.
  • Avoid sending personal or confidential data in prompts unless necessary and permitted.
  • Tell users how their inputs are processed.

Risk 6: image generation specifics

For image features built on models like Stable Diffusion:

  • apply safety filters to prompts and generated images,
  • consider rights and consent issues around generating images of real people or in the style of living artists, and
  • watermark or label generated images where appropriate.

A reference architecture

flowchart LR
  U[User] --> A[Your backend]
  A -->|rate limit,<br/>size limit,<br/>moderation| P[Prompt builder<br/>delimited input,<br/>no secrets]
  P --> M[Model API<br/>key server-side]
  M --> V[Output checks<br/>moderation,<br/>validation, encoding]
  V --> U
  A --> L[(Logs: usage,<br/>abuse, cost)]

Testing checklist

  • Attempts to override instructions ("ignore the above…") are handled acceptably
  • Output is encoded before rendering; no script execution possible
  • Harmful content is blocked by moderation on input and output
  • API key is not reachable from the client
  • Per-user rate limits and token caps are enforced
  • Sensitive data is not included in prompts or logs unnecessarily

The bottom line

Generative AI applications are still web applications, and all the usual controls apply. They also introduce a new kind of injection, a new source of untrusted output and a new cost surface. Developers who design for those from the start, with delimited prompts, moderated and validated outputs, server-side keys and strict limits, can ship generative features quickly without shipping new vulnerabilities with them.

Our application security testing now covers generative AI features, and our agentic AI security team builds them with these controls in place.

EthicalHat Research

The EthicalHat research team: penetration testers, SOC analysts and engineers writing about security, software engineering and AI.

Want an expert opinion on your own systems?

Email info@ethicalhat.com or call +1-844-838-4422. Our security engineers are happy to talk it through.