Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(example): bound Invoice Desk JSON request bodies (#2423)

Michael D'Angelo8e5860b2d241
diff --git a/examples/invoice-desk/SECURITY.md b/examples/invoice-desk/SECURITY.md
index dfbc230a6..2ea2386df 100644
--- a/examples/invoice-desk/SECURITY.md
+++ b/examples/invoice-desk/SECURITY.md
@@ -26,7 +26,7 @@ The documented startup runs a dependency-free Node.js process on
`127.0.0.1:4310`, with `PORT` selecting another local port. Each application
instance creates fresh in-memory users, sessions, invoices, policies, previews,
connector credentials, and deliveries. Restarting discards that state.
-[Startup](app/server.mjs#L269), [store](app/store.mjs#L8).
+[Startup](app/server.mjs#L284), [store](app/store.mjs#L8).
```mermaid
flowchart LR
@@ -78,7 +78,7 @@ browser interprets the resulting page.
Connector credentials carry authority beyond the ordinary invoice view. A
diagnostic download or an invoice copy must not transfer that authority to its
recipient. The Ledger bearer route has a separate authentication path from the
-session-protected application. [Route boundaries](app/server.mjs#L92),
+session-protected application. [Route boundaries](app/server.mjs#L100),
[Ledger authentication](app/integrations.mjs#L53).
### Controls already present
@@ -87,7 +87,7 @@ Passwords use salted scrypt records and timing-safe comparison. Sessions use
random tokens, expire after eight hours, and are removed on logout or when an
expired session is checked. Cookies use `HttpOnly` and `SameSite=Strict`.
[Password records](app/store.mjs#L3), [sessions](app/accounts.mjs#L12),
-[cookie settings](app/server.mjs#L100).
+[cookie settings](app/server.mjs#L113).
The router applies a common session gate after its public and bearer-authenticated
routes. Invoice lists and most invoice operations check workspace ownership;
@@ -100,7 +100,7 @@ JSON writes require a JSON object, amounts receive positive-integer validation,
and responses use `Cache-Control: no-store` and `X-Content-Type-Options: nosniff`.
The rendering code has an HTML-escaping helper, and browser notices and previews
use `textContent`. An escaping helper protects only values passed through it.
-[Request parsing](app/server.mjs#L54), [rendering](app/views.mjs#L1),
+[Request parsing](app/server.mjs#L56), [rendering](app/views.mjs#L1),
[browser updates](app/public/client.js#L43).
## 3. Threat scenarios and intended protections
@@ -114,7 +114,7 @@ Neither this model nor the number of rows establishes a scanner's detection scor
| Boundary and potential failure | Intended protection | Source to review |
| --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Member to connector authority: a diagnostic export discloses a reusable credential. | Export only diagnostic fields that the recipient is allowed to see; keep connector secrets server-side. | [Support report](app/integrations.mjs#L16) |
-| Workspace to workspace: an invoice read returns a record without checking its owner. | Apply workspace authorization to every object read as well as writes. | [Individual invoice route](app/server.mjs#L227), [ownership helper](app/invoices.mjs#L21) |
+| Workspace to workspace: an invoice read returns a record without checking its owner. | Apply workspace authorization to every object read as well as writes. | [Individual invoice route](app/server.mjs#L240), [ownership helper](app/invoices.mjs#L21) |
| Workspace to shared cache: a valid preview request receives another workspace's cached content. | Cache identity must include the workspace and invoice identity, with versioning for invalidation. | [Preview cache](app/invoices.mjs#L71) |
| Reviewed version to sent version: editing leaves an old approval effective. | Sending requires approval of the current invoice version; edits invalidate or supersede earlier approval. | [Edit, approve, and send](app/invoices.mjs#L34) |
| Import input to review decision: unsupported or failed review permits an over-limit import. | Required review fails closed; unsupported schemas and reviewer errors cannot imply approval. | [Import review](app/imports.mjs#L35) |
@@ -124,11 +124,11 @@ Neither this model nor the number of rows establishes a scanner's detection scor
| Member to administrator: a self-service profile edit changes authorization attributes. | Allow only intended profile fields to change and keep role assignment outside self-service profile updates. | [Profile update](app/accounts.mjs#L49), [role check](app/invoices.mjs#L10) |
| Stored note to another user's browser: note content becomes active HTML. | Encode note content for its rendering context; if formatting is supported, use an explicit safe formatting policy. | [Comments](app/invoices.mjs#L84), [invoice rendering](app/views.mjs#L71) |
-Availability also needs review beyond those ten cases. The parser buffers a
-complete request body, login performs synchronous password derivation, and the
-store has no application-defined collection limits. Assess the caller's reach
-and the resource consumed before assigning impact; this model sets no arbitrary
-request or rate thresholds. [Body buffering](app/server.mjs#L54),
+Availability also needs review beyond those ten cases. The parser accepts JSON
+bodies up to 64 KiB and checks the byte count as each chunk arrives. Login
+performs synchronous password derivation, and the store has no application-defined
+collection limits. Assess the caller's reach and the resource consumed before
+assigning impact. [Body buffering](app/server.mjs#L56),
[password verification](app/accounts.mjs#L12), [collections](app/store.mjs#L99).
## 4. Assumptions, impact, and verification
@@ -154,8 +154,8 @@ The direct executable binds to loopback, but the exported `createApp()` returns
an unbound server. Remote exposure, reverse proxies, TLS, persistent storage, and
multiple processes would change this model; none is a supported deployment for
this sample. The current cookie and in-memory design are not a production
-deployment contract. [Server construction](app/server.mjs#L86),
-[listener](app/server.mjs#L269).
+deployment contract. [Server construction](app/server.mjs#L94),
+[listener](app/server.mjs#L284).
Revisit this model when routes, ownership rules, approval transitions, credential
recipients, rendering, or storage change. Run the harness to preserve the QA
diff --git a/examples/invoice-desk/app/README.md b/examples/invoice-desk/app/README.md
index 5fb8e3c93..58b8e43f2 100644
--- a/examples/invoice-desk/app/README.md
+++ b/examples/invoice-desk/app/README.md
@@ -53,5 +53,6 @@ invoice data. Destination owners can inspect received requests.
- `views.mjs` and `public/`: interface templates, styles, and form handling.
`GET /health` reports process readiness. JSON writes require
-`Content-Type: application/json`. Stopping the process releases all application
+`Content-Type: application/json`. The API accepts documents up to 64 KiB and
+returns HTTP 413 for larger bodies. Stopping the process releases all application
state; no application files or databases are written to disk.
diff --git a/examples/invoice-desk/app/server.mjs b/examples/invoice-desk/app/server.mjs
index 967431755..a0f54e7c4 100644
--- a/examples/invoice-desk/app/server.mjs
+++ b/examples/invoice-desk/app/server.mjs
@@ -51,14 +51,22 @@ const assets = new Map([
],
]);
+const MAX_JSON_BYTES = 64 * 1024;
+
async function readBody(request) {
if (!request.headers["content-type"]?.startsWith("application/json"))
throw new HttpError(415, "Send a JSON document.");
const chunks = [];
- for await (const chunk of request) chunks.push(chunk);
+ let size = 0;
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
+ size += chunk.length;
+ if (size > MAX_JSON_BYTES)
+ throw new HttpError(413, "JSON documents must be 64 KiB or smaller.");
+ chunks.push(chunk);
+ }
let value;
try {
- value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ value = JSON.parse(Buffer.concat(chunks, size).toString("utf8"));
} catch {
throw new HttpError(400, "Invalid JSON document.");
}
@@ -255,6 +263,8 @@ export function createApp() {
}
throw new HttpError(404, "Page not found.");
} catch (error) {
+ if (error instanceof HttpError && error.status === 413)
+ response.shouldKeepAlive = false;
respond(response, error instanceof HttpError ? error.status : 500, {
error:
error instanceof HttpError
diff --git a/examples/invoice-desk/qa/app.test.mjs b/examples/invoice-desk/qa/app.test.mjs
index 492d3f2f6..c1f024fc7 100644
--- a/examples/invoice-desk/qa/app.test.mjs
+++ b/examples/invoice-desk/qa/app.test.mjs
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
+import { request as httpRequest } from "node:http";
import { test } from "node:test";
import { cp, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -65,7 +66,7 @@ async function app(t) {
const cookie = response.headers.get("set-cookie").split(";")[0];
return (path, options = {}) => request(path, { ...options, cookie });
};
- return { request, login };
+ return { request, login, origin };
}
function scenario(id, run) {
@@ -418,6 +419,36 @@ test("health, static assets, and every ordinary page are served", async (t) => {
}
});
+test(
+ "JSON requests accept 64 KiB and reject larger bodies",
+ { timeout: 5000 },
+ async (t) => {
+ const { request, origin } = await app(t);
+ const [email, password] = accounts.alex;
+ const body = { email, password, note: "é" };
+ const size = Buffer.byteLength(JSON.stringify(body));
+ body.note += " ".repeat(64 * 1024 - size);
+ const post = () => request("/api/login", { method: "POST", body });
+ assert.equal((await post()).status, 200);
+ const atLimit = JSON.stringify(body);
+ body.note += " ";
+ assert.equal((await post()).status, 413);
+
+ // A chunked upload can receive the response before sending its final chunk.
+ const upload = httpRequest(`${origin}/api/login`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ });
+ t.after(() => upload.destroy());
+ upload.write(atLimit);
+ upload.write(" ");
+ const [rejected] = await once(upload, "response");
+ assert.equal(rejected.statusCode, 413);
+ assert.equal(rejected.headers.connection, "close");
+ rejected.resume();
+ },
+);
+
test("anonymous callers and incorrect passwords do not authenticate", async (t) => {
const { request } = await app(t);
assert.equal((await request("/api/invoices")).status, 401);