Cotton code
99 lines · 6.2 KB · TypeScriptRaw
/** * THE ADMIN DOOR (NEXT-ADMIN-KEYS part 1, 27 Nov 2026; src/admin_door.ts). With token scopes off, an owner `ctn_` token * ran every admin route without its own check. Now on live every /v1/admin route takes the admin token alone; on the * dev and test Workers an invented account's owner token reaches the builder's few routes and nothing else. */import { describe, expect, it } from "vitest";import { ADMIN_ROUTES, DEV_OWNER_ROUTES, ownerReaches } from "../src/admin_door.ts";import SOURCE from "../src/business.ts?raw";import { ADMIN, http, mint, personalObject } from "./personal.ts";/** The object's admin router, from its first line to its last refusal. */const ROUTER = SOURCE.slice(SOURCE.indexOf("private async admin(request: Request, path: string)"), SOURCE.indexOf("nothing answers ${method} /v1/admin${path}"));describe("the admin route table", () => {  it("names every path the router answers, and no path it does not", () => {    expect(ROUTER.length).toBeGreaterThan(1000);    const answered = new Set([...ROUTER.matchAll(/path === "(\/[^"]+)"/g)].map((m) => m[1]!));    const tabled = new Set(ADMIN_ROUTES.map((r) => r.split(" ")[1]!));    expect([...answered].filter((p) => !tabled.has(p)), "routes the table misses").toEqual([]);    expect([...tabled].filter((p) => !answered.has(p)), "routes the router no longer answers").toEqual([]);    // A method the router names beside a path is the table's method.    for (const m of ROUTER.matchAll(/method === "([A-Z]+)" && \(?((?:path === "\/[^"]+"(?: \|\| )?)+)/g)) {      for (const p of m[2]!.matchAll(/path === "(\/[^"]+)"/g)) expect(ADMIN_ROUTES, `${m[1]} ${p[1]}`).toContain(`${m[1]} ${p[1]}`);    }    for (const r of DEV_OWNER_ROUTES) expect(ADMIN_ROUTES).toContain(r);  });  it("on live, no route lets an owner token through: production, or a Worker with no label", () => {    for (const route of ADMIN_ROUTES) {      const [method, path] = route.split(" ") as [string, string];      expect(ownerReaches({ ENV_LABEL: "production" }, method, path), route).toBe(false);      expect(ownerReaches({}, method, path), route).toBe(false);      expect(ownerReaches({ ENV_LABEL: "staging" }, method, path), route).toBe(false);    }  });  it("requireAdmin lets a non-admin through at one place, and only where the door says so", () => {    const gate = SOURCE.slice(SOURCE.indexOf("private async requireAdmin("), SOURCE.indexOf("private tokenAct("));    expect(gate.match(/return false/g)).toHaveLength(1);    // ADMIN KEYS 4 (63c39cc981): a key that carries a list reaches no admin route, dev included.    expect(gate).toContain("if (adminDoor.ownerReaches(this.env, request.method, path) && !this.tokenScopesOn() && !mcp.allow) return false;");  });});/** * The routes in groups of GROUP, each group a test of its own on an account of its own: the whole table in one test * flaked once under the whole suite's load (coordinator, 27 Nov). The wipe is in the last group, last. */const GROUP = 8;const ORDERED = [...ADMIN_ROUTES].sort((a, b) => Number(a === "POST /reset") - Number(b === "POST /reset"));const GROUPS = Array.from({ length: Math.ceil(ORDERED.length / GROUP) }, (_, i) => ORDERED.slice(i * GROUP, (i + 1) * GROUP));/** Generous for a loaded machine: a group is about thirty requests and one sign-in. */const GROUP_MS = 120_000;describe("an owner token at the admin door (the test Worker, token scopes off)", () => {  it("covers every route in its groups", () => {    expect(GROUPS.flat().sort()).toEqual([...ADMIN_ROUTES].sort());  });  GROUPS.forEach((group, i) => {    it(`group ${i + 1}: refused to an owner token but the builder's, to a read token and a phone's credential; the admin token through (${group.join(", ")})`, async () => {      const slug = `admin-door-owner-${i + 1}`;      const { credential } = await personalObject(slug);      const owner = { authorization: `Bearer ${await mint(slug, credential, "Invented assistant", ["owner"])}` };      const reader = { authorization: `Bearer ${await mint(slug, credential, "Invented reader", ["read"], 7)}` };      const phone = { authorization: `Bearer ${credential}` };      for (const route of group) {        const [method, path] = route.split(" ") as [string, string];        const body = method === "GET" ? undefined : {};        for (const [who, headers] of [["read token", reader], ["phone credential", phone]] as const) {          const r = await http<{ code: string }>(slug, method, `/v1/admin${path}`, body, headers);          expect([r.status, r.body.code], `${who}: ${route}`).toEqual([403, "admin_only"]);        }        const r = await http<{ code: string }>(slug, method, `/v1/admin${path}`, body, owner);        if (DEV_OWNER_ROUTES.has(route)) expect(r.body.code, `owner, the builder's: ${route}`).not.toBe("admin_only");        else expect([r.status, r.body.code], `owner: ${route}`).toEqual([403, "admin_only"]);      }      // The admin token is through the door (what each answers past it is its own); the wipe and the erase are left.      for (const route of group) {        if (route === "POST /reset" || route === "POST /account/erase-now") continue;        const [method, path] = route.split(" ") as [string, string];        const r = await http<{ code: string }>(slug, method, `/v1/admin${path}`, method === "GET" ? undefined : {}, ADMIN);        expect(r.body.code, `admin: ${route}`).not.toBe("admin_only");      }    }, GROUP_MS);  });  it("an owner token never adds another phone as owner, nor reads the export, once named on the live list", async () => {    // The reviewer's sharpest two: POST /person and GET /export. Person is the admin's everywhere; export is a builder's    // route on dev only (ownerReaches is false for it on live, above).    const slug = "admin-door-person";    const { credential } = await personalObject(slug);    const owner = { authorization: `Bearer ${await mint(slug, credential, "Invented assistant", ["owner"])}` };    const r = await http<{ code: string }>(slug, "POST", "/v1/admin/person", { phone: "+919000000123", role: "owner" }, owner);    expect([r.status, r.body.code]).toEqual([403, "admin_only"]);    expect(ownerReaches({ ENV_LABEL: "production" }, "GET", "/export")).toBe(false);  });});