AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 51

    Application Security: OWASP Top 10 and API Protection

    Northwind's reminder route was authenticated, tenant-scoped, and still one bug away from a bad week.

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 51 · Full-Stack Security, Testing and Deployment

    Lesson Overview

    Northwind's reminder route was authenticated, tenant-scoped, and still one bug away from a bad week. The enrollment export accepted a JSON body, copied every field onto the query, and honored limit: 1000000. The same handler logged the Authorization header when the export threw. A connector prototype fetched whatever URL a staff note contained, including a link to an internal address the application could reach and the learner could not. None of these were model bugs. They were API bugs with names on the OWASP lists.

    Lesson 48 identifies the caller. Lesson 49 binds the tenant. Lesson 50 keeps model output from becoming authority. This lesson maps the rest of the request path to the OWASP Top 10 (2021) and the OWASP API Security Top 10 (2023), and it implements the route guard TechLearningPro can test: schema that drops forged fields, an action check, a bound query, a rate limit, and an outbound host allowlist.

    Planning assumptions:

    • Lists are cited by the years above. Re-read the current OWASP pages when you file a review, and update the matrix if an item moves.
    • The lab package is packages/api-guard/. It uses in-memory ports. No live credential, no internal network call, and no exploit script.
    • AI routes are ordinary routes plus lesson 50. They do not get a weaker schema because a model is involved.
    • Budgets in the lab are small on purpose: 30 requests per minute per principal for the export, limit at most 100.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Map each OWASP Top 10 (2021) item to a TechLearningPro control or to a later lesson that owns it.
    2. Map each OWASP API Security Top 10 (2023) item the same way.
    3. Distinguish broken object-level authorization from broken function-level authorization with enrollment and reminder examples.
    4. Parse a request body so role, organizationId, and unknown fields cannot be assigned.
    5. Require a principal and an action before a handler runs, and return not_found for an object outside the tenant.
    6. Keep SQL parameters bound when an id contains punctuation.
    7. Cap page size and apply a per-principal rate limit so one export cannot exhaust the database or the model budget.
    8. Allow outbound connector URLs only for https hosts on a reviewed list, with no userinfo and no raw address literal.
    9. Omit Authorization, Cookie, and request bodies from error logs.
    10. Treat security headers and CORS as server configuration, not as a client promise.
    11. Name dependency review and lockfile pinning as the control for vulnerable components.
    12. Explain unsafe consumption of APIs: timeouts, schema checks, and no privilege on the far side's words.
    13. Keep an OpenAPI inventory that matches routes you actually ship.
    14. Test mass assignment, a cross-tenant id, an oversized limit, a disallowed host, and a log line that lacks the bearer token.
    15. Leave secrets rotation, retention, and compliance evidence to lesson 52.

    Prerequisites

    What is Application Security: OWASP Top 10 and API Protection?

    Application security here means the controls on TechLearningPro's HTTP API: who may call a function, which object they may touch, which fields they may set, how large the request may be, where the server may connect, and what gets written down when it fails. The OWASP Top 10 is a ranked awareness list for web application risks. The OWASP API Security Top 10 is the companion list for APIs, where object ids and machine clients are the normal case. Neither list is a compliance certificate. Both are a review agenda so a team does not "finish security" by turning on HTTPS and stopping.

    The purpose of walking the lists in this product is to attach each name to a function you can fail in a unit test. A slide that says "prevent injection" does not stop a string-built query. boundQuery does, and the test passes an id that contains a quote character to prove the quote stays in the parameter array.

    OWASP updates the lists on a multi-year cadence. The 2021 web list and the 2023 API list are the ones this lesson names. If you are reading this after a new publication, keep the controls and refresh the identifiers.

    TermMeaning in this lesson
    BOLABroken object level authorization. The id is someone else's object
    BFLABroken function level authorization. The caller lacks the action
    BOPLABroken object property level authorization. Extra fields are honored
    GuardprotectApi, which runs before the handler
    Allowlisted hostA connector destination the catalog already named
    InventoryThe OpenAPI document that matches shipped routes

    Why Do We Need It?

    text
    Authenticated instructor
    |
    +--> body.organizationId honored --------> wrong tenant
    +--> limit unbounded --------------------> database and model bill
    +--> staff note contains a URL ----------> server fetches an internal host
    +--> error log includes Authorization ---> credential in the log vendor
    |
    v
    protectApi: schema, action, tenant, limit, rate
    outboundHost: https and catalog only
    logLine: method, route, reason, no headers

    Lessons 48 through 50 close identity, tenant, and model agency. APIs still fail on property assignment, resource consumption, outbound requests, logging, and forgotten routes. The OWASP API list leads with object-level authorization because that is how real APIs leak. The web list leads with broken access control for the same reason. Injection remains on both lists wherever a string is concatenated into SQL, HTML, or a shell. This product's SQL path is parameterized. This product does not build shell commands from request fields.

    Real World Example

    TechLearningPro's export, reminder, enrollment read, and connector fetch are the four routes a reviewer will ask about. A bank's statement download has the same shape as the export: the customer is authenticated, and the account id still has to match the session. An e-commerce order API has the same mass-assignment bug when price or role arrives in JSON and the ORM saves it. A healthcare integration has the same SSRF shape when a "callback URL" field is fetched by the server. Amazon, Google, and Microsoft publish API gateways that rate-limit and authenticate. The gateway does not know that organizationId in the body must be ignored. That rule stays in parseExportRequest.

    The model does not get a special exemption. A tool argument that includes a URL is data for outboundHost, not a reason to skip it. Lesson 44's catalog is the allowlist of operations. This lesson is the allowlist of hosts.

    Internal Working

    1. The framework has already resolved the lesson 48 principal, or it passes null. protectApi treats null as unauthenticated and does not call the handler.
    2. The route names an action. authorize from lesson 48 runs. A learner calling the export receives forbidden.
    3. The body parser accepts only declared fields. role, organizationId, and any unknown key produce invalid_body and are not copied forward.
    4. limit must be an integer from 1 to 100. A missing limit becomes 20. A string or a huge number is invalid_body.
    5. The rate-limit port keys on principal.userId plus the route name. Over the budget, the result is rate_limited and the handler does not run.
    6. Object reads go through the lesson 49 helper. A foreign organization is not_found.
    7. SQL is a statement plus a parameter array. The organization id and the object id are parameters even when the id contains quotes or comment characters.
    8. Outbound URLs parse as https, reject userinfo, reject address literals, and require a host in ALLOWED_HOSTS. Anything else is blocked_host and no socket is opened by this package.
    9. Upstream responses are bytes until a schema port accepts them. A status page or an unexpected JSON shape is bad_upstream, not a tool instruction.
    10. logLine records method, route template, status, organization id when known, and reason. It has no slot for headers or bodies.

    Architecture

    flowchart TB
      subgraph edge [Edge]
        Req[HTTP request]
        Headers[Security headers]
      end
    
      subgraph guard [protectApi]
        Session[Principal or 401]
        Schema[Declared fields only]
        Action[Action matrix]
        Rate[Rate limit]
      end
    
      subgraph data [Data and egress]
        Sql[Bound SQL and tenant]
        Host[HTTPS host allowlist]
        Up[Upstream schema check]
      end
    
      subgraph obs [Operations]
        Log[logLine without secrets]
        Spec[OpenAPI inventory]
      end
    
      Req --> Headers
      Headers --> Session
      Session --> Schema
      Schema --> Action
      Action --> Rate
      Rate --> Sql
      Rate --> Host
      Host --> Up
      Session --> Log
      Req --> Spec
    text
    Request
    -> principal? no -> unauthenticated
    -> schema accepts body? no -> invalid_body
    -> action allowed? no -> forbidden
    -> rate limit open? no -> rate_limited
    -> object in tenant? no -> not_found
    -> outbound host allowlisted? no -> blocked_host
    -> handler
    -> logLine

    Trust boundaries: the client is untrusted, including a staff member's note and a model's tool arguments. PostgreSQL is reached with bound parameters and the tenant predicate. The public internet is reached only at allowlisted hosts. Upstream payloads are untrusted. Logs are a data store. The OpenAPI file is the inventory only if deployment fails closed when a route is missing from it. This lesson records that operational rule. It does not ship a gateway.

    Deep Dive

    Web list, mapped

    OWASP Top 10 2021TechLearningPro control
    A01 Broken Access ControlLesson 48 matrix, lesson 49 predicate, not_found on foreign ids
    A02 Cryptographic FailuresHTTPS, HttpOnly session cookies, password hashes behind CredentialPort, no secrets in git
    A03 InjectionBound SQL parameters. Model and user text never concatenated into SQL. Lesson 50 for prompt channels
    A04 Insecure DesignAction per route, approval for refunds and mail, tenant required
    A05 Security MisconfigurationSecurity headers, CORS limited to the app origin, errors without stack traces, app role without BYPASSRLS
    A06 Vulnerable ComponentsLockfile, review of dependency advisories, no unpinned "latest" in production
    A07 Identification and Authentication FailuresLesson 48: server sessions, generic sign-in errors, CSRF on cookie writes
    A08 Software and Data Integrity FailuresLockfile and review for builds. Model output is data, not code to eval
    A09 Logging and Monitoring FailureslogLine with reason and ids, without cookies or bodies. Alerts live with the platform, not in this package
    A10 SSRFoutboundHost allowlist. No fetch of a URL taken from a note

    API list, mapped

    OWASP API 2023TechLearningPro control
    API1 BOLAObject id plus organization id, learner owner check
    API2 Broken AuthenticationLesson 48. A client-supplied role is not authentication
    API3 BOPLAParser drops role, organizationId, price, and unknown keys
    API4 Unrestricted Resource ConsumptionMax limit 100, rate limit, lesson 50 token cap, lesson 46 step budgets
    API5 BFLARoute action, such as reminder.approve, checked against the role
    API6 Unrestricted Access to Sensitive Business FlowsReminder start and export are rate-limited. Refunds stay on a human ticket
    API7 SSRFHost allowlist on connector fetches
    API8 Security MisconfigurationHeaders, CORS, no verbose errors, no debug authentication header in production
    API9 Improper Inventory ManagementOpenAPI matches the routes. Old /v0 handlers are removed, not left undocumented
    API10 Unsafe Consumption of APIsTimeouts, response schema, no elevation because upstream JSON said role: admin

    API6 is the business-flow twin of the rate limit. A valid instructor must not enqueue a million reminders because each call is individually authorized. The capstone already pauses on approval. This guard adds a budget so the approval queue itself cannot be flooded from one principal.

    Headers and CORS

    The composition root sets:

    HeaderValue in this design
    Strict-Transport-SecurityLong max-age on the deployed HTTPS host
    X-Content-Type-Optionsnosniff
    Referrer-Policyno-referrer on API responses
    Content-Security-PolicyApp origin for the HTML host. API responses are JSON
    Frame embeddingDenied for the app shell

    CORS allows the TechLearningPro web origin and does not reflect an arbitrary Origin with credentials. A browser demo that sets Access-Control-Allow-Origin: * together with cookies is misconfiguration, not a convenience. Exact header values belong in the deployed config and should be re-checked against current browser guidance. This package tests the decisions it owns: schema, authz, rate, host, and log shape.

    Unsafe consumption

    Lesson 44's connectors call other companies' APIs. Those responses can be wrong, large, or hostile in the same way a prompt is hostile. The adapter sets a timeout, limits bytes, and parses a schema. A field named role or organizationId in upstream JSON does not change the principal. HTML error pages become bad_upstream inside the adapter, which lesson 46 already expects. The model never receives the raw upstream body as a system message. If a summary is required, it is a tool_result piece under lesson 50.

    Inventory

    Every route you ship appears in the OpenAPI document from lesson 10, including AI routes. A handler that exists only in a file someone deployed is API9. The review rule is: a route without an operation id does not ship, and an operation id whose path 404s in the contract test is deleted from the spec. Versioned paths (/v1) are explicit. Leaving /internal/export-all reachable without the spec is both inventory failure and BFLA.

    Code Examples

    Simple example: body schema

    packages/api-guard/src/schema.ts

    typescript
    export const API_GUARD_VERSION = "api-guard-v1";
    export const MAX_LIMIT = 100;
    export const DEFAULT_LIMIT = 20;
    export interface ExportRequest {
    courseId: string;
    limit: number;
    }
    const ALLOWED_KEYS = new Set(["courseId", "limit"]);
    export function parseExportRequest(
    body: unknown,
    ): { ok: true; value: ExportRequest } | { ok: false; reason: "invalid_body" } {
    if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, reason: "invalid_body" };
    const record = body as Record<string, unknown>;
    for (const key of Object.keys(record)) {
    if (!ALLOWED_KEYS.has(key)) return { ok: false, reason: "invalid_body" };
    }
    if (typeof record.courseId !== "string" || record.courseId.trim().length === 0) {
    return { ok: false, reason: "invalid_body" };
    }
    const limit = record.limit === undefined ? DEFAULT_LIMIT : record.limit;
    if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
    return { ok: false, reason: "invalid_body" };
    }
    return { ok: true, value: { courseId: record.courseId.trim(), limit } };
    }

    role and organizationId are unknown keys, so they fail the request. They are not stripped and ignored silently. A silent strip hides client bugs. A 400 makes the contract obvious. The course id is still untrusted as a tenant. The query binds the principal's organization beside it.

    Intermediate example: the route guard and the log

    packages/api-guard/src/protect.ts

    typescript
    import { parseExportRequest, type ExportRequest } from "./schema.js";
    export type Role = "learner" | "instructor" | "support" | "support_lead" | "admin";
    export interface Principal {
    userId: string;
    organizationId: string;
    role: Role;
    }
    export type Action = "export.completions" | "reminder.start" | "enrollment.read_tenant";
    const MATRIX: Record<Role, readonly Action[]> = {
    learner: [],
    instructor: ["export.completions", "reminder.start", "enrollment.read_tenant"],
    support: ["enrollment.read_tenant"],
    support_lead: ["export.completions", "reminder.start", "enrollment.read_tenant"],
    admin: ["export.completions", "reminder.start", "enrollment.read_tenant"],
    };
    export type GuardFailure =
    | "unauthenticated"
    | "forbidden"
    | "invalid_body"
    | "rate_limited"
    | "not_found";
    export interface RateLimitPort {
    take(key: string): Promise<{ ok: true } | { ok: false; reason: "rate_limited" }>;
    }
    export interface LogLine {
    method: string;
    route: string;
    reason: string;
    organizationId?: string;
    }
    export function logLine(input: {
    method: string;
    route: string;
    reason: string;
    principal: Principal | null;
    }): LogLine {
    return {
    method: input.method,
    route: input.route,
    reason: input.reason,
    organizationId: input.principal?.organizationId,
    };
    }
    export async function protectExport(
    principal: Principal | null,
    body: unknown,
    rate: RateLimitPort,
    ): Promise<{ ok: true; principal: Principal; request: ExportRequest } | { ok: false; reason: GuardFailure }> {
    if (!principal) return { ok: false, reason: "unauthenticated" };
    const parsed = parseExportRequest(body);
    if (!parsed.ok) return parsed;
    if (!MATRIX[principal.role].includes("export.completions")) return { ok: false, reason: "forbidden" };
    const ticket = await rate.take(`${principal.userId}:export.completions`);
    if (!ticket.ok) return ticket;
    return { ok: true, principal, request: parsed.value };
    }

    The log helper's input type has nowhere to put an authorization header. Callers that want to "just add headers" have to change the type, which is the review you want.

    Enterprise example: bound query and outbound host

    packages/api-guard/src/egress.ts

    typescript
    export interface BoundQuery {
    text: string;
    params: readonly unknown[];
    }
    export function enrollmentsQuery(organizationId: string, courseId: string, limit: number): BoundQuery {
    return {
    text: "SELECT id, status FROM enrollments WHERE organization_id = $1 AND course_id = $2 ORDER BY created_at DESC LIMIT $3",
    params: [organizationId, courseId, limit],
    };
    }
    export const ALLOWED_HOSTS = ["catalog.techlearningpro.test"] as const;
    export function outboundHost(raw: string): { ok: true; host: string } | { ok: false; reason: "blocked_host" } {
    let url: URL;
    try {
    url = new URL(raw);
    } catch {
    return { ok: false, reason: "blocked_host" };
    }
    if (url.protocol !== "https:") return { ok: false, reason: "blocked_host" };
    if (url.username.length > 0 || url.password.length > 0) return { ok: false, reason: "blocked_host" };
    const host = url.hostname.toLowerCase();
    if (host.length === 0 || host === "localhost") return { ok: false, reason: "blocked_host" };
    const looksLikeAddress = /^\d{1,3}(\.\d{1,3}){3}$/.test(host) || host.includes(":");
    if (looksLikeAddress) return { ok: false, reason: "blocked_host" };
    if (!(ALLOWED_HOSTS as readonly string[]).includes(host)) return { ok: false, reason: "blocked_host" };
    return { ok: true, host };
    }
    export function upstreamRoleIgnored(payload: Record<string, unknown>): { courseId: string } | { reason: "bad_upstream" } {
    if (typeof payload.courseId !== "string") return { reason: "bad_upstream" };
    return { courseId: payload.courseId };
    }

    outboundHost does not open a socket. The composition root may call fetch only after ok: true, with a timeout and a byte cap. Address literals and localhost are rejected so a note cannot aim the server at a numeric internal address or the loopback name. DNS and redirect behavior belong in the HTTP client: follow no redirects unless the next hop is checked with this same function. This lesson states that rule and does not implement a custom DNS resolver.

    upstreamRoleIgnored returns courseId only. A role field on the payload is not part of the result type.

    Tests

    packages/api-guard/src/guard.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { enrollmentsQuery, outboundHost } from "./egress.js";
    import { logLine, protectExport, type Principal } from "./protect.js";
    const instructor: Principal = { userId: "usr_i", organizationId: "northwind", role: "instructor" };
    test("rejects a body that tries to set role and tenant", async () => {
    const result = await protectExport(
    instructor,
    { courseId: "pgvector", limit: 20, role: "admin", organizationId: "contoso" },
    { async take() { return { ok: true }; } },
    );
    assert.deepEqual(result, { ok: false, reason: "invalid_body" });
    });
    test("learners cannot export", async () => {
    const result = await protectExport(
    { userId: "usr_l", organizationId: "northwind", role: "learner" },
    { courseId: "pgvector" },
    { async take() { return { ok: true }; } },
    );
    assert.deepEqual(result, { ok: false, reason: "forbidden" });
    });
    test("quote characters stay in the parameter array", () => {
    const query = enrollmentsQuery("northwind", "course'id", 20);
    assert.equal(query.text.includes("course'id"), false);
    assert.deepEqual(query.params, ["northwind", "course'id", 20]);
    });
    test("blocks hosts that are not on the catalog list", () => {
    assert.equal(outboundHost("https://catalog.techlearningpro.test/lessons").ok, true);
    assert.deepEqual(outboundHost("http://catalog.techlearningpro.test/lessons"), { ok: false, reason: "blocked_host" });
    assert.deepEqual(outboundHost("https://169.254.169.254/latest"), { ok: false, reason: "blocked_host" });
    assert.deepEqual(outboundHost("https://user:pass@catalog.techlearningpro.test/"), { ok: false, reason: "blocked_host" });
    });
    test("log lines have no header slot", () => {
    const line = logLine({
    method: "POST",
    route: "/api/exports",
    reason: "invalid_body",
    principal: instructor,
    });
    assert.equal("authorization" in line, false);
    assert.equal("cookie" in line, false);
    assert.equal(line.organizationId, "northwind");
    });

    Add a rate-limit test that does not need a second assertion about the handler, because the handler is not invoked when protectExport returns rate_limited. Add a limit: 1000000 case. The address in the blocked URL is a well-known metadata address used here as a negative fixture. The test must not perform HTTP. outboundHost only parses.

    Architecture Diagram

    text
    Browser or partner
    -> security headers and CORS at the edge
    -> protectExport or sibling guards
    principal, schema, action, rate
    -> repository with bound SQL and tenant
    -> connector only if outboundHost succeeds
    -> upstream schema, role field discarded
    -> logLine
    -> OpenAPI is the route inventory
    sequenceDiagram
      participant C as Client
      participant G as protectExport
      participant D as Database
      C->>G: JSON body
      G->>G: schema, action, rate
      G->>D: parameterized select
      D-->>C: page of at most 100

    Real-Time Enterprise Example

    Northwind's instructor requests a completion export for the pgvector course with limit omitted. The parser applies 20. The query parameters are Northwind, the course id, and 20. Contoso rows are absent because the predicate is Northwind. A learner's copy of the same request is forbidden before SQL. A body that adds organizationId: "contoso" is invalid_body before SQL.

    A support tool that summarizes a catalog page may fetch https://catalog.techlearningpro.test/... after the host check, with a timeout. A ticket body that contains a different host never reaches fetch. The upstream JSON may include extra fields. The adapter keeps courseId and drops the idea that upstream can set a role. The error log for a bad body contains the route and invalid_body. The bearer token the client sent is not a field on that line.

    The OpenAPI operation exportCompletions documents the two accepted fields and the 401, 400, 403, and 429 responses. A route shipped without that operation fails the contract check your pipeline should run. Lesson 56 will wire the pipeline. This lesson names the inventory rule so the spec is not an afterthought.

    Performance Optimization

    • Reject oversized limits and unauthenticated calls before SQL and before any model call.
    • Rate limits are cheap counters. Put them in front of exports and reminder starts, which are the expensive business flows.
    • Indexes from lesson 49 keep the bound query on (organization_id, course_id). The guard does not fix a missing index, and a missing index is how a "small" limit still hurts.
    • Do not hold a transaction open while you call an allowlisted host. Fetch outside the SQL unit of work.
    • Cap upstream bytes in the adapter. An allowlisted host can still return a huge payload. That cap is API4 and API10 together.
    • Log lines stay small. Logging bodies "for performance debugging" both slows the request and stores data you did not mean to keep.

    Illustrative: a forbidden learner export performs no query. A blocked host performs no DNS requirement inside this package because the string check fails first. Production still re-checks the address it connects to, per the redirect rule above.

    Security

    • Authentication and session cookies stay in lesson 48. This guard consumes a principal.
    • Authorization is both the action matrix and the tenant predicate. Either one alone is incomplete.
    • Mass assignment fails closed on unknown keys, including role and organizationId.
    • Injection into SQL is addressed by parameters. Injection into prompts is lesson 50. Injection into a shell is avoided by not having a shell step.
    • SSRF is addressed by an https host allowlist, a ban on userinfo and address literals, and a redirect rule for the client.
    • Cryptographic controls are HTTPS, cookie flags, and password hashing in the credential port. This lesson does not invent a cipher.
    • Components stay on a lockfile. An AI SDK is a dependency like any other. Pin it and read its advisory channel.
    • Integrity: do not eval model output, and do not treat upstream JSON as a new principal.
    • Logging omits credentials and bodies. Monitoring alerts on forbidden spikes and blocked_host spikes belong in the platform runbook.
    • Resource consumption covers database rows, outbound calls, and model tokens. The last of those is lesson 50's cap, enforced on AI routes that pass this guard first.

    Common Mistakes

    1. Copying the whole JSON body onto an update. Symptom: a client sets role or organizationId. Cause: the ORM saved unknown fields. Fix: parseExportRequest and an allowlist of keys.
    2. Checking the role and forgetting the object. Symptom: any instructor reads any academy's enrollment by id. Cause: BFLA passed and BOLA was skipped. Fix: the lesson 49 predicate beside the matrix.
    3. Returning 403 with a foreign object's details. Symptom: id probing. Cause: the row was loaded and then described. Fix: not_found with an empty body.
    4. Building SQL with a template string. Symptom: punctuation in an id changes the statement. Cause: the id was interpolated. Fix: enrollmentsQuery parameters, asserted by a test.
    5. Fetching a URL from a ticket or a tool argument. Symptom: the server calls an internal host. Cause: SSRF as a feature. Fix: outboundHost and the lesson 44 catalog.
    6. Following redirects without re-checking the host. Symptom: an allowlisted URL redirects somewhere else. Cause: the client followed by default. Fix: disable redirects or run outboundHost on each hop. This package does not fetch.
    7. Logging headers on error. Symptom: session cookies in the log vendor. Cause: the error middleware dumped req.headers. Fix: logLine.
    8. Leaving a debug header that sets the user. Symptom: production accepts the test learner header from lesson 9. Cause: the stub shipped. Fix: production resolves lesson 48 only.
    9. Rate-limiting by IP only. Symptom: one stolen session still exports as fast as it wants, or a shared NAT locks out a campus. Cause: the key ignored the principal. Fix: key the expensive routes by user id and route, and keep a coarser IP limit on sign-in.
    10. Trusting role inside upstream JSON. Symptom: a partner response promotes the caller. Cause: unsafe consumption. Fix: upstreamRoleIgnored and the session principal.
    11. Shipping /v0 beside /v1 without the spec. Symptom: an old export without the limit cap stays reachable. Cause: inventory drift. Fix: delete the handler or document it and put it behind the same guard.
    12. Disabling the limit because an instructor asked for "all rows". Symptom: one call becomes a full table read. Cause: API4 was treated as a product inconvenience. Fix: page with the keyset from lesson 49. The cap stays.

    Best Practices

    1. Keep API_GUARD_VERSION next to the parsers.
    2. Resolve the principal before parsing trust into the handler.
    3. Name an action on every mutating and exporting route.
    4. Allowlist JSON keys.
    5. Reject unknown keys rather than storing them.
    6. Cap limit and choose a small default.
    7. Rate-limit exports, reminder starts, and sign-in.
    8. Bind every SQL value.
    9. Pair every object read with the organization id.
    10. Use not_found for objects outside the tenant.
    11. Allowlist outbound hosts.
    12. Require https and reject userinfo.
    13. Re-check redirects.
    14. Schema-check upstream bodies.
    15. Ignore upstream role fields.
    16. Set security headers and a tight CORS policy at the edge.
    17. Keep stack traces out of client responses.
    18. Pin dependencies and review advisories.
    19. Publish OpenAPI for every shipped route.
    20. Log reasons and ids, not cookies or bodies.
    21. Put model routes through the same guard before lesson 50.
    22. Keep refunds and mail on the approval ticket.
    23. Test mass assignment, BFLA, bound parameters, blocked hosts, and log shape.
    24. Re-read the OWASP pages when you refresh the control matrix.

    Interview Questions & Answers

    Beginner

    1. What is the OWASP Top 10? A community list of the most serious web application risks, updated every few years. Teams use it as a review agenda. Passing a slide about the list is not a control. A test that fails a forged role field is a control.

    2. What is broken object level authorization? The caller is signed in and allowed to use the function, but the object id belongs to another user or another tenant. The fix is to query by the session's organization and, for learners, the session's user id.

    3. Why are parameters safer than string concatenation for SQL? The database receives the statement and the values separately. Punctuation in a course id stays in the value. It does not become part of the statement. The test asserts the text does not contain the course id.

    Intermediate

    1. How do BOLA, BFLA, and BOPLA differ? BFLA is the wrong function for the role, such as a learner exporting completions. BOLA is the right function and the wrong object. BOPLA is the right object and a field the client must not set, such as organizationId or role.

    2. What is your SSRF control? Parse the URL, require https, reject userinfo and address literals, and accept only hosts in the catalog. Do not fetch until that check returns. Re-check redirects. A model tool argument uses the same function.

    3. What belongs in an API error log? Method, route template, reason, and organization id when you have a principal. Not the authorization header, not the cookie, not the body, and not a stack trace sent back to the client.

    Senior

    1. How do you limit a sensitive business flow that is individually authorized? Rate-limit by principal and route, cap page size, and keep a human approval ticket for mail and refunds. Authorization answers "may this person ever do this?" The budget answers "how often, and how large?"

    2. What is unsafe consumption of a partner API? Trusting the partner's JSON as if it were your session, skipping timeouts, or forwarding the raw body into a system prompt. Parse a schema, ignore role fields, and if the model must see a summary, label it as a tool result.

    3. How does the API list relate to the LLM list from lesson 50? Prompt injection and excessive agency are the model-shaped versions of injection and broken access control. The route guard still runs first. Lesson 50 does not replace protectExport.

    Architect

    1. Where do you enforce this if a gateway already authenticates? The gateway can reject missing tokens and apply coarse rate limits. It cannot know that organizationId is illegal in the body or that a course id must be parameterized. Keep protectExport in the application. Do not split the rules across two consoles with no test.

    2. How do you keep inventory honest? Generate or lint the OpenAPI document in CI against the route table. Fail the build when a handler has no operation id. Remove old versions on purpose. An AI route is not exempt because it is "internal."

    3. What is your dependency stance for AI SDKs? Pin the version, review advisories, and keep the SDK behind the port from lesson 23 so feature code does not grow a second HTTP client that skips outboundHost.

    4. Why reject unknown JSON keys instead of stripping them? Stripping lets a privileged field ride along unnoticed until a future edit spreads the object into an update. Rejection makes the contract fail in the client's tests. Either choice is better than saving the field. This product rejects.

    5. How do security headers fit a JSON API? Transport and content-type headers still matter. CSP matters on the HTML origin that calls the API. CORS must not credential an arbitrary origin. The guard tests do not replace a config review of those headers.

    6. What alert would you page on? A spike of blocked_host, a spike of forbidden on reminder.approve, or a rate-limit storm on exports. A single invalid_body is a client bug. The runbook says to check whether a new client started sending role.

    7. How do you test SSRF controls without calling a network? outboundHost is a pure function. Fixtures cover a good host, plain HTTP, an address literal, and userinfo. An integration test may point at a local fake only when the host is on a test allowlist. This lesson's unit test does not open a socket.

    8. What does API8 look like in this codebase? A production deploy that still honors the lesson 9 test identity header, a wildcard CORS policy, a database role that bypasses RLS, or a stack trace in a 500 body. The fix is configuration review plus a boot check that the debug header is absent.

    9. Why is limit a security field? Unbounded reads are how one tenant becomes a noisy neighbor and how a mistake in the predicate returns a larger leak. Capping at 100 does not replace the predicate. It bounds the blast radius.

    10. Who owns cryptographic design? Lesson 48 owns password hashing and session cookies. The platform owns TLS. This lesson refuses to add a custom cipher and refuses to log material those controls protect. Lesson 52 owns retention of whatever you did store.

    11. What will you re-verify when OWASP publishes a new list? The identifiers and the order. The product controls — principal, tenant, schema, parameters, host allowlist, budgets, and quiet logs — stay until a new item describes a path you actually have. Map the new name to a function or write the function.

    Knowledge Check

    1. What problem does this capability solve?

    It gives TechLearningPro's API a single guard for forged fields, disallowed actions, oversized reads, illegal outbound hosts, and logs that keep credentials. OWASP names become tests instead of a poster.

    2. What alternatives exist, and when would you choose each?

    Keep this application guard even if a gateway authenticates. Use the gateway for TLS, coarse limits, and bot filtering. Use lesson 50 for model channels. Use a WAF signature as a supplement, not as the mass-assignment control. A document-only review fits an audit meeting and does not fail the build.

    3. Which data, identity, and trust boundaries matter?

    The principal is identity. The organization predicate is the object boundary. The JSON allowlist is the property boundary. The host allowlist is the egress boundary. Upstream JSON is untrusted. Logs and the OpenAPI file are part of the system: one can leak, the other can lie if it drifts.

    4. What can fail, and how should the system respond?

    Missing principals are unauthenticated. Bad bodies are invalid_body. Disallowed roles are forbidden. Foreign objects are not_found. Over-budget callers are rate_limited. Illegal URLs are blocked_host. Upstream shapes that lack the fields you expect are bad_upstream. None of these echo the bearer token.

    5. How would you test quality, security, performance, and cost?

    Tests cover mass assignment, a learner export, a parameterized id with a quote, blocked hosts, and log shape. Security review checks CORS, headers, and the absence of the debug identity header. Performance review checks that forbidden and invalid requests skip SQL. Cost review checks the limit cap and the rate key so one instructor cannot scan the whole table or flood reminders.

    Practical Exercise

    Implement parseExportRequest, protectExport, enrollmentsQuery, outboundHost, and logLine. Do not send traffic to a real host and do not commit a token.

    1. Draw the guard in front of SQL and in front of any connector fetch.
    2. Implement the tests in this lesson plus limit: 1000000 and a rate_limited result.
    3. Show an upstream payload { courseId, role } and the parsed result that contains only courseId.
    4. Write six rows: control, owner, evidence. Include the schema, the action, the bound query, the host allowlist, the log shape, and the OpenAPI inventory rule.
    5. Map one web-list item and one API-list item that your tests already fail closed.
    6. Explain why a gateway that checks JWTs does not remove parseExportRequest.

    Challenge. A model tool argument includes https://catalog.techlearningpro.test/a and https://catalog.techlearningpro.test.evil.example/a. Show that only the first host passes outboundHost, and that neither call happens inside the unit test. State the redirect rule in one sentence.

    Deliverable and Rubric

    Submit the diagram, the source, the test output, the six-row control table, and the two OWASP mappings.

    AreaWeight
    Conceptual accuracy and architecture20%
    Working implementation and code quality25%
    Security, privacy, and responsible AI20%
    Testing, reliability, and observability20%
    Documentation and decision rationale15%

    Production checklist:

    • Every export and reminder route runs a guard.
    • Unknown JSON keys fail the body.
    • Actions come from the lesson 48 matrix.
    • Object reads include the organization id.
    • SQL values are parameters.
    • Page size and rate limits are constants.
    • Outbound hosts are allowlisted https names.
    • Redirects are re-checked.
    • Upstream JSON cannot set a role.
    • Logs omit cookies and authorization headers.
    • OpenAPI lists the routes you ship.
    • AI routes pass this guard before lesson 50.
    • Dependencies are pinned.
    • The debug identity header is absent in production.

    Key Takeaways

    1. The OWASP lists are a review agenda tied to functions.
    2. BOLA, BFLA, and BOPLA are three different bugs.
    3. The body parser allowlists fields.
    4. The action matrix and the tenant predicate both run.
    5. SQL parameters stay parameters when ids contain punctuation.
    6. Limits and rate keys bound sensitive flows.
    7. Egress is an https host allowlist.
    8. Upstream payloads are untrusted.
    9. Logs store reasons, not credentials.
    10. Headers and CORS are configuration you still review.
    11. Lockfiles and OpenAPI are part of security.
    12. Model routes are API routes.
    13. Lesson 50 remains the prompt boundary.
    14. A gateway does not replace the application guard.
    15. Refresh OWASP identifiers without dropping the controls.

    Summary

    Lesson 51 puts TechLearningPro's API on the OWASP web and API lists with controls you can run: a strict body, an action check, a bound tenant query, a rate limit, an outbound host check, and a log line that cannot hold a bearer token. Identity, isolation, and prompt defense from the previous three lessons stay in force. The next lesson is what you do with secrets, personal data, and retention once these routes exist.

    Next Lesson Preview

    Secrets, Privacy, Data Retention and Compliance Basics covers where credentials live, how long prompts and exports may be stored, and which fields must never enter a log or a model. The guards in this lesson already refuse to log the cookie. Lesson 52 decides how the rest of the data ages out.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.