Cotton code
145 lines · 11.6 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import BOOK from "../../../crates/cotton-core/kits/personal/tables/book.json";import { ADMIN, DATABASE_ID, http, mint, openTables, personalObject, tool, BOOKS_OPEN } from "./personal.ts";const SLUG = "front";/** RULE (owner, 25 Oct 2026): the personal database is an object on the Worker and Cotton MCP is served from it; the object checks the token at its front door before any row is read. */describe("Cotton MCP at the personal object's front door", () => {  let credential = "";  let owner = "";  it("is made like the real one: onboarded, the owner signed in by phone, an owner token minted by an act", async () => {    ({ credential, owner } = await personalObject(SLUG, BOOKS_OPEN));    const me = await http<{ business: { kind: string; database_id: string } }>(SLUG, "GET", "/v1/me", undefined, { authorization: `Bearer ${credential}` });    expect(me.body.business).toMatchObject({ kind: "personal", database_id: DATABASE_ID });  });  it("answers JSON over POST only, and initialize names the database", async () => {    const get = await http(SLUG, "GET", "/mcp", undefined, { authorization: `Bearer ${owner}` });    expect(get.status).toBe(405);    expect(get.body).toEqual({ error: "send JSON-RPC over POST; there is no SSE stream", code: "method_not_allowed" });    const init = await http<{ result: { protocolVersion: string; serverInfo: { name: string }; instructions: string } }>(SLUG, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "initialize", params: {} }, { authorization: `Bearer ${owner}`, accept: "application/json, text/event-stream" });    expect(init.body.result.protocolVersion).toBe("2025-06-18");    expect(init.body.result.serverInfo.name).toBe("cotton");    expect(init.body.result.instructions.split("\n")[0]).toBe(JSON.stringify({ database: { id: DATABASE_ID, name: "Personal" }, app: "Cotton" }));    const note = await http(SLUG, "POST", "/mcp", { jsonrpc: "2.0", method: "notifications/initialized" }, { authorization: `Bearer ${owner}` });    expect(note.status).toBe(202);    const batch = await http<unknown[]>(SLUG, "POST", "/mcp", [{ jsonrpc: "2.0", id: 1, method: "ping" }, { jsonrpc: "2.0", id: 2, method: "nope" }], { authorization: `Bearer ${owner}` });    expect(batch.body).toEqual([{ jsonrpc: "2.0", id: 1, result: {} }, { jsonrpc: "2.0", id: 2, error: { code: -32601, message: 'unsupported method "nope"' } }]);    // AUDIT C 5: a batch holds at most 20 messages.    const flood = await http(SLUG, "POST", "/mcp", Array.from({ length: 21 }, (_, i) => ({ jsonrpc: "2.0", id: i, method: "ping" })), { authorization: `Bearer ${owner}` });    expect(flood.body).toEqual({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "a batch holds at most 20 messages; this one has 21" } });  });  it("refuses a missing, foreign or unknown token with the Rust sentences", async () => {    const none = await http(SLUG, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" });    expect(none).toEqual({ status: 401, body: { error: "a Cotton MCP token is required in the Authorization header", code: "unauthorized" } });    for (const token of ["test-admin-token", `ctn_${DATABASE_ID}_nothing`, credential]) {      const r = await http(SLUG, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, { authorization: `Bearer ${token}` });      expect(r).toEqual({ status: 401, body: { error: "unknown token", code: "unauthorized" } });    }  });  it("answers an unknown tool as a tool result, not a protocol error", async () => {    const r = await tool(SLUG, owner, "no_such_tool");    expect(r).toEqual({ content: [{ type: "text", text: 'unknown tool "no_such_tool"' }], isError: true });  });  it("lets the owner mint and revoke; a revoked token is unknown, and only an owner token acts", async () => {    const reader = await mint(SLUG, credential, "a reader", ["read"]);    expect((await http(SLUG, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "ping" }, { authorization: `Bearer ${reader}` })).status).toBe(200);    const asReader = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "mint_token", args: { name: "x", scopes: ["owner"] } }, { authorization: `Bearer ${reader}` });    expect(asReader.status).toBe(403);    // ADMIN KEYS 1b: an owner token mints a lane token and nothing else (lane-start); the owner's device mints any.    const byToken = await http<{ token?: string }>(SLUG, "POST", "/v1/act", { act: "mint_token", args: { name: "lane widgets", scopes: ["read", "lane:widgets"], expires_in_days: 7 } }, { authorization: `Bearer ${owner}` });    expect(byToken.status, JSON.stringify(byToken.body)).toBe(200);    expect(byToken.body.token).toMatch(/^ctn_/);    const wider = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "mint_token", args: { name: "wider", scopes: ["read", "write"], expires_in_days: 7 } }, { authorization: `Bearer ${owner}` });    expect(wider.body.code).toBe("access_act");    const byPhone = await http<{ token?: string }>(SLUG, "POST", "/v1/act", { act: "mint_token", args: { name: "lane widgets", scopes: ["read", "lane:widgets"], expires_in_days: 7 } }, { authorization: `Bearer ${credential}` });    expect(byPhone.status, JSON.stringify(byPhone.body)).toBe(200);    expect(byPhone.body.token).toMatch(/^ctn_/);    const lanes = await http<{ code: string; message: string }>(SLUG, "POST", "/v1/act", { act: "mint_token", args: { name: "lane", scopes: ["read", "lane:x"] } }, { authorization: `Bearer ${credential}` });    expect(lanes.body.message).toBe("a lane token lives at most 7 days");    const tokens = await http<{ rows: { table: string; id: string; data: { name: string } }[] }>(SLUG, "GET", "/v1/admin/export", undefined, ADMIN);    const row = tokens.body.rows.find((r) => r.table === "mcp_token" && r.data.name === "a reader")!;    // The secret is everything after `ctn_<databaseId>_`: base64url holds `_` too, so its last    // `_`-segment can be one character and match a timestamp. The whole 43-character secret cannot.    const secret = reader.slice(reader.indexOf("_", "ctn_".length) + 1);    expect(secret.length, reader).toBeGreaterThanOrEqual(43);    expect(JSON.stringify(row.data)).not.toContain(secret);    const revoked = await http(SLUG, "POST", "/v1/act", { act: "revoke_token", args: { id: row.id } }, { authorization: `Bearer ${credential}` });    expect(revoked.status).toBe(200);    const after = await http(SLUG, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "ping" }, { authorization: `Bearer ${reader}` });    expect(after).toEqual({ status: 401, body: { error: "unknown token", code: "unauthorized" } });  });  it("serves MCP only on the personal object", async () => {    await http("plainbiz", "PUT", "/v1/admin/business", { name: "Biz" }, ADMIN);    await http("plainbiz", "PUT", "/v1/admin/definitions", { tools: [], tables: [{ id: "t", columns: [] }] }, ADMIN);    const r = await http("plainbiz", "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "ping" });    expect(r).toEqual({ status: 404, body: { code: "not_found", message: "nothing answers POST /mcp" } });  });});const ARCHIVE_ID = "22222222-2222-4222-8222-222222222222";/** RULE (Rust parity): one endpoint reaches the owner's other databases by `database`; a row made there stays there, and a lane token's one write holds there too. */describe("a call naming another of the owner's databases", () => {  const slug = "fronthome";  const archive = "frontarchive";  let owner = "";  let lane = "";  it("runs in that object as the same caller", async () => {    const made = await personalObject(slug, BOOKS_OPEN);    owner = made.owner;    lane = await mint(slug, made.credential, "lane widgets", ["read", "lane:widgets"], 7);    expect((await http(archive, "PUT", "/v1/admin/business", { name: "Archive", kind: "personal", database_id: ARCHIVE_ID }, ADMIN)).status).toBe(200);    expect((await http(archive, "PUT", "/v1/admin/definitions", { tools: [], tables: [{ ...BOOK, seal: null }] }, ADMIN)).status).toBe(200);    // Books are sealed by the kit: this test is of the call reaching another object, so its books are open.    await http(archive, "GET", "/v1/definitions");    await openTables(archive, ["book"]);    expect((await http(slug, "PUT", "/v1/admin/business", { siblings: [{ id: ARCHIVE_ID, name: "Archive", slug: archive }] }, ADMIN)).status).toBe(200);    const createdRaw = await tool(slug, owner, "create_record", { table: "book", data: { title: "Synthetic Atlas" }, database: ARCHIVE_ID });    expect(createdRaw.isError, createdRaw.content[0]!.text).toBe(false);    const listed = JSON.parse((await tool(slug, lane, "list_records", { table: "book", database: "Archive" })).content[0]!.text) as { records: { data: { title: string } }[]; databaseId: string };    expect(listed.records.map((r) => r.data.title)).toEqual(["Synthetic Atlas"]);    // Home holds a book table of its own (the kit's), and the Archive's rows stay in the Archive.    const home = await tool(slug, owner, "list_records", { table: "book" });    expect(home.isError, home.content[0]!.text).toBe(false);    expect((JSON.parse(home.content[0]!.text) as { records: unknown[] }).records).toEqual([]);    const other = await tool(slug, lane, "create_record", { table: "book", data: { title: "Forged" }, database: ARCHIVE_ID });    expect(other.content[0]!.text).toBe("this is lane widgets's token: it reads, and writes only its session log — `create_record` is not log_session");  });  it("refuses a database this endpoint does not reach, and no outside request reaches /internal/", async () => {    const r = await tool(slug, owner, "list_records", { table: "book", database: "33333333-3333-4333-8333-333333333333" });    expect(r).toEqual({ isError: true, content: [{ type: "text", text: "database_mismatch" }], structuredContent: { code: "database_mismatch" } });    const sneak = await http(archive, "POST", "/internal/mcp-call", { caller: { tokenId: "x", name: "x", scopes: ["owner"], lane: null }, tool: "list_records", args: { table: "book" } });    expect(sneak.status).toBe(404);  });  it("AUDIT C 5: paces each key, at /mcp and at /v1; another key and the owner's own device are not held back", async () => {    const slug = "front-paced";    const made = await personalObject(slug, BOOKS_OPEN);    // This object's own pace, small enough to cross in a test (live: 300 a minute).    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance) => (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store.setMeta("key_calls_per_minute", "3"));    const other = await mint(slug, made.credential, "another key", ["owner"]);    const ping = (token: string) => http<{ code?: string }>(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "ping" }, { authorization: `Bearer ${token}` });    // A minute boundary between the calls would reset the count: start just after one.    while (new Date().getSeconds() > 50) await new Promise((r) => setTimeout(r, 1000));    for (let i = 0; i < 3; i++) expect((await ping(made.owner)).status).toBe(200);    const fourth = await ping(made.owner);    expect([fourth.status, fourth.body.code]).toEqual([429, "too_many_calls"]);    expect((await http(slug, "GET", "/v1/me", undefined, { authorization: `Bearer ${made.owner}` })).status).toBe(429);    expect((await ping(other)).status).toBe(200);    expect((await http(slug, "GET", "/v1/me", undefined, { authorization: `Bearer ${made.credential}` })).status).toBe(200);    // Up to 10 s waiting for a minute's start, beside the object's making: past the default 5 s whenever it starts late in    // a minute, or the suite is busy.  }, 30_000);});