Skip to main content
Secure API Development & Guardrailing AI/LLM Endpoints
Lesson 10 of 15

Secure API Development & Guardrailing AI/LLM Endpoints

Design API endpoints with strict OpenAPI schema validation, object-level authorization, and rate limits, and enforce deterministic guardrails around AI/LLM prompts, tool calls, and outputs.

Advanced 28 min AppSec

Learning objectives

  • Enforce strict request contracts with OpenAPI schemas, object-level authorization, and resource rate limits
  • Explain why LLM system prompts are not security boundaries against direct and indirect prompt injection
  • Design deterministic server-side tool-call policies that prevent excessive agency and SSRF
  • Validate and encode LLM outputs safely before passing them to downstream parsers, databases, or browsers

Recommended first: Applying OWASP ASVS, Top 10 (2021/2025) & API Top 10Secure Authentication, Session & Authorization Design (RBAC/ABAC)Allowlist Input Validation & Context-Aware Output Encoding

#Why this matters

Modern backends expose JSON APIs to web clients, mobile apps, and automated partners, and many now wrap Large Language Models (LLMs) to summarize records, answer questions, or invoke backend tools. That architecture combines classic API risks from the OWASP API Security Top 10 (2023) with AI-specific threats from the OWASP Top 10 for Large Language Model Applications.

Because an LLM processes system instructions, user messages, and retrieved documents in a single token stream, the model cannot reliably separate trusted policy from untrusted data. Security controls must therefore live in deterministic API code surrounding the model rather than inside prompt text alone.

#Hardening the API contract and resource boundaries

Before a single token reaches an LLM, the surrounding HTTP API must enforce the authorization and validation fundamentals covered in earlier lessons:

  • Schema-first validation (OpenAPI): Validate types, string lengths, numeric ranges, enums, and additionalProperties: false at the API gateway or framework layer. Rejecting unknown fields prevents mass assignment and Broken Object Property Level Authorization (API3:2023).
  • Object-level and function-level authorization (API1:2023, API5:2023): Derive caller identity and tenant scope strictly from the verified JWT or session on the server. Never trust client-supplied user_id, tenant_id, or role fields, and verify ownership on every record read or modified.
  • Rate limiting and resource caps (API4:2023): An LLM inference call consumes orders of magnitude more CPU, GPU, and money than a database lookup. Apply sliding-window rate limits per user and API key, enforce small request body caps, and set hard max_tokens and timeout limits on every model call.
OpenAPI 3.1 strict request contract for an AI summary route
paths:
  /api/v1/tickets/summarize:
    post:
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [ticket_id, style]
              properties:
                ticket_id:
                  type: string
                  pattern: "^TCK-[0-9]{4,8}$"
                style:
                  type: string
                  enum: ["brief", "bullets"]

Notice how additionalProperties: false, the strict regex on ticket_id, and the fixed enum leave no room for unexpected fields or arbitrary prompt stuffing on this route.

#Prompt injection and the trust boundary

Direct prompt injection happens when a caller submits instructions inside a user prompt to override developer rules or extract hidden system instructions. Indirect prompt injection is even more dangerous in enterprise apps: malicious instructions sit inside external data the model reads, such as a support ticket, a shared document, a web page, or a RAG knowledge-base chunk.

Treat the LLM as an untrusted data-plane component, never as a policy enforcement point. A system prompt such as "Never call admin tools or reveal secrets" is useful guidance for normal quality, not an access-control boundary.

Indirect prompt injection blocked by deterministic tool policyIndirect prompt injection blocked by deterministic tool policyUserAPITicketDBLLMPolicyGatePOST /api/v1/tickets/summarize (ticket_id=TCK-4021)Load TCK-4021 if owner == current_userTicket text (contains hidden injected instruction)System instructions + untrusted ticket textTool request: export_users(format="csv")Check route allow-list & user scopesReject (export_users not permitted on summarize route)200 OK safe summary or controlled refusalSecurity decision stays in deterministic server code

The same untrusted mindset applies to insecure output handling. Never pass raw LLM output directly into eval(), shell execution, raw SQL strings, or unescaped HTML (innerHTML). If an attacker poisons a retrieved document, model output becomes a carrier for Cross-Site Scripting (XSS) or injection in your own backend.

#Guardrailing tool calls and excessive agency

Many AI endpoints expose function-calling or tool-use capabilities so the model can fetch records, query APIs, or update state. Excessive agency occurs when the model has access to more tools, broader permissions, or more autonomous side effects than the endpoint requires.

Threat surface Weak pattern Deterministic guardrail
Tool selection Bind all application tools to every chat route Per-route allow-list exposing only minimal, task-specific tools
Tenant & user scope Let the model pass user_id into get_orders(user_id) Bind current_user.id in server code; omit identity parameters from tool schemas
External URL fetch Expose fetch_url(url) directly to the model Allow-list approved domains, block private IP ranges (10.0.0.0/8, 169.254.169.254), and disable redirects (API7:2023)
State changes Allow the model to delete accounts or send external emails directly Require a separate confirmed user action with a signed one-time token
Data leakage Return raw tool JSON or unredacted logs Filter fields by role, enforce structured output schemas, and redact secrets before logging

The Python handler below shows how a deterministic policy gate wraps a model's requested tool call before any backend function runs:

Deterministic tool-call dispatcher for an AI endpoint
ALLOWED_TOOLS = {
    "get_ticket_summary": {"roles": {"support", "admin"}, "mutating": False},
}

def dispatch_tool_call(tool_name, args, current_user):
    policy = ALLOWED_TOOLS.get(tool_name)
    if policy is None:
        raise PermissionError("Tool not permitted on this endpoint")
    if current_user.role not in policy["roles"]:
        raise PermissionError("Caller role lacks tool scope")
    if not isinstance(args, dict):
        raise ValueError("Tool arguments must be a JSON object")

    ticket_id = args.get("ticket_id", "")
    if not ticket_id.startswith("TCK-") or not ticket_id[4:].isdigit():
        raise ValueError("Invalid ticket_id format")

    # Enforce tenant ownership on the server, never from model args
    return fetch_scoped_ticket(ticket_id=ticket_id, tenant_id=current_user.tenant_id)

Notice three protections working together: the route only registers get_ticket_summary, the caller's verified current_user controls both role and tenant_id, and ticket_id is validated before hitting the data store.

#Common mistakes

  • Treating instructions in a system prompt ("Never reveal internal data") as an enforceable access control instead of building server-side authorization checks.
  • Trusting identifiers such as user_id or tenant_id supplied by either the HTTP JSON body or the LLM's generated tool arguments.
  • Giving an LLM agent a general-purpose SQL execution tool or unrestricted curl/HTTP fetch tool, turning prompt injection into SQL injection or Server-Side Request Forgery (SSRF).
  • Omitting rate limits, concurrency caps, and token budgets on AI endpoints, exposing the service to compute exhaustion and runaway billing.
  • Writing unredacted prompts, retrieved RAG chunks, and model responses into centralized logs where secrets or personal data become exposed.

#Summary

  • Harden AI-backed APIs at the HTTP boundary first with strict OpenAPI schemas (additionalProperties: false), verified server-side object authorization, and rate/token limits.
  • Assume direct and indirect prompt injection can steer the model; treat the LLM as untrusted and enforce every security rule in deterministic code outside the model.
  • Prevent excessive agency by binding per-route tool allow-lists, enforcing caller ownership in server code, validating tool arguments strictly, and requiring human confirmation for state-changing actions.
  • Treat LLM outputs as untrusted data and apply context-aware encoding and schema checks before rendering in a browser or passing to downstream systems.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge