Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
195 changes: 194 additions & 1 deletion pkgs/id/web/src/identity-refresh.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
import { identityNeedsRefresh } from "./identity-refresh";
import {
identityNeedsRefresh,
parseIdentityMeResponse,
parseIdentityNameResponse,
parseIdentityRegisterResponse,
} from "./identity-refresh";

const INTERVAL = 24 * 60 * 60 * 1000;
const NOW = 1_800_000_000_000;
Expand Down Expand Up @@ -34,3 +39,191 @@ describe("identityNeedsRefresh", () => {
expect(identityNeedsRefresh(String(NOW - INTERVAL * 30), NOW, INTERVAL)).toBe(true);
});
});

// Oracle for the #7839 suites below: a wrong-shape body must THROW, because
// throwing is what routes the caller through its existing error path before
// saveIdentity/updateStoredName can run — i.e. localStorage stays unchanged
// and no identity is returned. A returned value of the wrong type, or a
// coerced string, is the failure these tests pin against.
describe("parseIdentityRegisterResponse (#7839)", () => {
it("accepts a well-shaped registration", () => {
expect(parseIdentityRegisterResponse({ token: "tok", client_id: "cid", name: "Ada" })).toEqual({
Comment on lines +48 to +50

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Cover identity response invariants with property tests

The three new response parsers have meaningful validation invariants, but their tests exercise only fixed examples. Root AGENTS.md explicitly requires property-based coverage for parsers and says example-based tests do not replace it. Add generated JSON inputs with an independent acceptance predicate, checking that invalid shapes throw and valid fields are preserved without coercion; retain these examples as regression cases.

AGENTS.md reference: AGENTS.md:L41-L45

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1f01c77 — property coverage added for all three parsers (seeded generator, 2000 generated inputs per parser, independent acceptance predicates as oracle, no-coercion assertions on accepted inputs). Full detail: #8505 (comment)

token: "tok",
clientId: "cid",
name: "Ada",
});
expect(parseIdentityRegisterResponse({ token: "tok", client_id: "cid", name: null })).toEqual({
token: "tok",
clientId: "cid",
name: null,
});
expect(parseIdentityRegisterResponse({ token: "tok", client_id: "cid" })).toEqual({
token: "tok",
clientId: "cid",
name: null,
});
});

it("rejects non-object bodies", () => {
expect(() => parseIdentityRegisterResponse({})).toThrow();
expect(() => parseIdentityRegisterResponse(null)).toThrow();
expect(() => parseIdentityRegisterResponse("abc")).toThrow();
expect(() => parseIdentityRegisterResponse([])).toThrow();
});

it("rejects numeric or object token/client_id instead of coercing them", () => {
expect(() => parseIdentityRegisterResponse({ token: 123, client_id: "cid" })).toThrow();
expect(() => parseIdentityRegisterResponse({ token: {}, client_id: "cid" })).toThrow();
expect(() => parseIdentityRegisterResponse({ token: "tok", client_id: 123 })).toThrow();
expect(() => parseIdentityRegisterResponse({ token: "tok", client_id: {} })).toThrow();
expect(() => parseIdentityRegisterResponse({ token: "", client_id: "cid" })).toThrow();
expect(() => parseIdentityRegisterResponse({ token: "tok" })).toThrow();
});

it("rejects a non-string name", () => {
expect(() => parseIdentityRegisterResponse({ token: "tok", client_id: "cid", name: 123 })).toThrow();
});
});

describe("parseIdentityMeResponse (#7839)", () => {
it("accepts a rotation, a name-only update, and an empty object", () => {
expect(parseIdentityMeResponse({ token: "fresh", name: "Ada" })).toEqual({ token: "fresh", name: "Ada" });
expect(parseIdentityMeResponse({ name: null })).toEqual({ token: null, name: null });
expect(parseIdentityMeResponse({})).toEqual({ token: null, name: null });
});

it("rejects non-object bodies", () => {
expect(() => parseIdentityMeResponse(null)).toThrow();
expect(() => parseIdentityMeResponse("abc")).toThrow();
expect(() => parseIdentityMeResponse([])).toThrow();
});

it("rejects a numeric or object token instead of overwriting the stored one", () => {
expect(() => parseIdentityMeResponse({ token: 123 })).toThrow();
expect(() => parseIdentityMeResponse({ token: { evil: 1 } })).toThrow();
expect(() => parseIdentityMeResponse({ token: "" })).toThrow();
expect(() => parseIdentityMeResponse({ token: null })).toThrow();
});

it("rejects a non-string name", () => {
expect(() => parseIdentityMeResponse({ name: 123 })).toThrow();
});
});

describe("parseIdentityNameResponse (#7839)", () => {
it("accepts a string or null name", () => {
expect(parseIdentityNameResponse({ name: "Ada" })).toEqual({ name: "Ada" });
expect(parseIdentityNameResponse({ name: null })).toEqual({ name: null });
});

it("rejects a non-string name and non-object bodies", () => {
expect(() => parseIdentityNameResponse({ name: 123 })).toThrow();
expect(() => parseIdentityNameResponse({ name: {} })).toThrow();
expect(() => parseIdentityNameResponse({})).toThrow();
expect(() => parseIdentityNameResponse(null)).toThrow();
expect(() => parseIdentityNameResponse("abc")).toThrow();
});
});

// ---------------------------------------------------------------------------
// Property coverage for the three parsers (#7839, Codex P1 on PR #8505).
// Oracle: the independent acceptance predicates below, written directly from
// the endpoint contracts — they share no code with the parsers. Generator: a
// seeded PRNG builds random JSON-shaped values (random field subsets, random
// value types), so a failure reproduces from the seed alone.
// ---------------------------------------------------------------------------

function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}

const SCALARS: unknown[] = ["tok", "cid", "Ada", "", 123, 0, true, false, null, { evil: 1 }, ["x"]];

function randomIdentityPayload(rand: () => number): unknown {
if (rand() < 0.15) return SCALARS[Math.floor(rand() * SCALARS.length)];
const record: Record<string, unknown> = {};
for (const field of ["token", "client_id", "name", "extra"]) {
if (rand() < 0.6) record[field] = SCALARS[Math.floor(rand() * SCALARS.length)];
}
return record;
}

function isPlainRecord(v: unknown): v is Record<string, unknown> {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
function nonEmptyString(v: unknown): v is string {
return typeof v === "string" && v.length > 0;
}
function nameOk(v: unknown): boolean {
return v === undefined || v === null || typeof v === "string";
}

// Independent acceptance predicates (the oracle).
function registerAccepts(v: unknown): boolean {
return isPlainRecord(v) && nonEmptyString(v.token) && nonEmptyString(v.client_id) && nameOk(v.name);
}
function meAccepts(v: unknown): boolean {
return isPlainRecord(v) && (v.token === undefined || nonEmptyString(v.token)) && nameOk(v.name);
}
function nameAccepts(v: unknown): boolean {
return isPlainRecord(v) && "name" in v && nameOk(v.name);
}

describe("identity response parsers — property coverage (#7839)", () => {
const ITERATIONS = 2000;

it("parseIdentityRegisterResponse agrees with its predicate on generated inputs, without coercion", () => {
const rand = mulberry32(0x7839a);
for (let i = 0; i < ITERATIONS; i++) {
const input = randomIdentityPayload(rand);
if (registerAccepts(input)) {
const rec = input as Record<string, unknown>;
expect(parseIdentityRegisterResponse(input)).toEqual({
token: rec.token,
clientId: rec.client_id,
name: typeof rec.name === "string" ? rec.name : null,
});
} else {
expect(() => parseIdentityRegisterResponse(input)).toThrow();
}
}
});

it("parseIdentityMeResponse agrees with its predicate on generated inputs, without coercion", () => {
const rand = mulberry32(0x7839b);
for (let i = 0; i < ITERATIONS; i++) {
const input = randomIdentityPayload(rand);
if (meAccepts(input)) {
const rec = input as Record<string, unknown>;
expect(parseIdentityMeResponse(input)).toEqual({
token: typeof rec.token === "string" ? rec.token : null,
name: typeof rec.name === "string" ? rec.name : null,
});
} else {
expect(() => parseIdentityMeResponse(input)).toThrow();
}
}
});

it("parseIdentityNameResponse agrees with its predicate on generated inputs, without coercion", () => {
const rand = mulberry32(0x7839c);
for (let i = 0; i < ITERATIONS; i++) {
const input = randomIdentityPayload(rand);
if (nameAccepts(input)) {
const rec = input as Record<string, unknown>;
expect(parseIdentityNameResponse(input)).toEqual({
name: typeof rec.name === "string" ? rec.name : null,
});
} else {
expect(() => parseIdentityNameResponse(input)).toThrow();
}
}
});
});
91 changes: 91 additions & 0 deletions pkgs/id/web/src/identity-refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,94 @@ export function identityNeedsRefresh(refreshedAt: string | null, now: number, in
if (elapsed < 0) return true;
return elapsed >= intervalMs;
}

// ============================================================================
// Identity endpoint response validation (#7839)
// ============================================================================

/** Validated `/api/identity/me` response: a rotated token and/or the current display name. */
export interface IdentityMeResponse {
token: string | null;
name: string | null;
}

/** Validated `/api/identity/register` response: the newly issued identity. */
export interface IdentityRegisterResponse {
token: string;
clientId: string;
name: string | null;
}

/** Validated `/api/identity/name` response: the stored display name. */
export interface IdentityNameResponse {
name: string | null;
}

function asIdentityRecord(payload: unknown, endpoint: string): Record<string, unknown> {
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
throw new Error(`malformed ${endpoint} response (expected an object)`);
}
return payload as Record<string, unknown>;
}

function identityNameField(value: unknown, endpoint: string): string | null {
if (value === undefined || value === null) return null;
if (typeof value !== "string") {
throw new Error(`malformed ${endpoint} response (name must be a string or null)`);
}
return value;
}

function requiredIdentityString(value: unknown, field: string, endpoint: string): string {
if (typeof value !== "string" || value.length === 0) {
throw new Error(`malformed ${endpoint} response (${field} must be a non-empty string)`);
}
return value;
}

/**
* Validate a `/api/identity/me` payload at the fetch boundary (#7839).
*
* The token is optional (present only when the server rotates it) and the
* name is optional, but either one, when present, must be a non-empty
* string / a string-or-null. Anything else throws, so the caller's error
* path leaves the stored identity untouched: without this check a
* wrong-shape 200 overwrote a valid stored token with the coerced string
* "[object Object]".
*/
export function parseIdentityMeResponse(payload: unknown): IdentityMeResponse {
const record = asIdentityRecord(payload, "/api/identity/me");
const token =
record.token === undefined ? null : requiredIdentityString(record.token, "token", "/api/identity/me");
return { token, name: identityNameField(record.name, "/api/identity/me") };
}

/**
* Validate a `/api/identity/register` payload at the fetch boundary
* (#7839). Both `token` and `client_id` are required non-empty strings:
* anything else throws before the caller can persist a fake identity
* (the unvalidated cast stored the literal strings "undefined" /
* "[object Object]" in localStorage as token/client_id).
*/
export function parseIdentityRegisterResponse(payload: unknown): IdentityRegisterResponse {
const record = asIdentityRecord(payload, "/api/identity/register");
return {
token: requiredIdentityString(record.token, "token", "/api/identity/register"),
clientId: requiredIdentityString(record.client_id, "client_id", "/api/identity/register"),
name: identityNameField(record.name, "/api/identity/register"),
};
}

/**
* Validate a `/api/identity/name` payload at the fetch boundary (#7839).
* The response's only field is the stored display name, so it must be
* present and a string or null; anything else throws and the caller
* leaves the stored name unchanged.
*/
export function parseIdentityNameResponse(payload: unknown): IdentityNameResponse {
const record = asIdentityRecord(payload, "/api/identity/name");
if (!("name" in record)) {
throw new Error("malformed /api/identity/name response (name must be a string or null)");
}
return { name: identityNameField(record.name, "/api/identity/name") };
}
23 changes: 14 additions & 9 deletions pkgs/id/web/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ import { AutoSaveManager, type SaveResult } from "./auto-save";
import { buildCollabWsUrl, type CollabConnection, initCollab } from "./collab";
import { type EditorInstance, getEditorState } from "./editor";
import { updateHeaderSubtitle } from "./header-subtitle";
import { identityNeedsRefresh } from "./identity-refresh";
import {
identityNeedsRefresh,
parseIdentityMeResponse,
parseIdentityNameResponse,
parseIdentityRegisterResponse,
} from "./identity-refresh";
import { clientIdForDisplay } from "./settings-identity";
import { closeImageBrowser } from "./image-browser";
import { createNavigation } from "./navigation";
Expand Down Expand Up @@ -145,16 +150,16 @@ async function ensureIdentity(): Promise<IdentityState | null> {
try {
const resp = await fetch(`/api/identity/me?token=${encodeURIComponent(stored.token)}`);
if (resp.ok) {
const data = await resp.json();
const data = parseIdentityMeResponse(await resp.json());
// Server returns a refreshed token on each validation, resetting the
// 30-day expiry clock. Save it so the client stays authenticated as
// long as they visit within every 30 days.
if (data.token) {
stored.token = data.token;
saveIdentity(stored.token, stored.clientId, data.name || null);
saveIdentity(stored.token, stored.clientId, data.name);
}
// Update name from server (may have changed via another tab/session)
const serverName = data.name || null;
const serverName = data.name;
if (serverName !== stored.name) {
updateStoredName(serverName);
stored.name = serverName;
Expand Down Expand Up @@ -182,11 +187,11 @@ async function ensureIdentity(): Promise<IdentityState | null> {
console.error("[id] Identity registration failed:", resp.status);
return null;
}
const data = await resp.json();
const data = parseIdentityRegisterResponse(await resp.json());
const identity: IdentityState = {
token: data.token,
clientId: data.client_id,
name: data.name || null,
clientId: data.clientId,
name: data.name,
};
saveIdentity(identity.token, identity.clientId, identity.name);
console.log("[id] New identity registered:", identity.clientId);
Expand All @@ -212,8 +217,8 @@ async function updateDisplayName(token: string, name: string | null): Promise<st
console.error("[id] Name update failed:", resp.status);
return null;
}
const data = await resp.json();
const updatedName = data.name || null;
const data = parseIdentityNameResponse(await resp.json());
const updatedName = data.name;
updateStoredName(updatedName);
console.log("[id] Display name updated:", updatedName);
return updatedName;
Expand Down
Loading