Cotton code
301 lines · 20.3 KB · TypeScriptRaw
/** * Google Calendar's sign-in on the person's object (src/google.ts): the * consent page for the Web client, the one-shot state, the grant sealed into * a secret row, the status, and the disconnect that revokes and forgets. */import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";import { afterEach, describe, expect, it } from "vitest";import { addressOf, client, SCOPES } from "../src/google.ts";import { Refused } from "../src/http.ts";import { Store } from "../src/store.ts";import { ACCESS, connectAccount, EMAIL, FakeCalendar, GRANTED, GRANTED_READONLY, GRANTED_WIDE, google, idToken, page, primary, quiet, REFRESH, reply, revoked, tokens, tokensWith } from "./google.ts";import { ADMIN, answer, DATABASE_ID, EVENTS_OPEN, http, OWNER_PHONE, personalObject } from "./personal.ts";// A connect wakes the object's pull, which may ask Google after a test is done: it finds a calendar with nothing on it, never the network.afterEach(() => {  google(tokens, primary, quiet, revoked);});const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });describe("connecting Google Calendar", () => {  it("answers the owner Google's consent page for the Web client: the address and the calendar's events read and written (openid email calendar.events.owned, the narrowest scope that writes the primary calendar), offline, consent asked, a state naming the database", async () => {    const { owner } = await personalObject("gconnect");    const res = await http<{ authorizeUrl: string; state: string }>("gconnect", "GET", "/v1/google/connect", undefined, bearer(owner));    expect(res.status, JSON.stringify(res.body)).toBe(200);    const url = new URL(res.body.authorizeUrl);    expect(url.origin + url.pathname).toBe("https://accounts.google.com/o/oauth2/v2/auth");    expect(Object.fromEntries(url.searchParams)).toEqual({      client_id: "test-client.apps.googleusercontent.com",      redirect_uri: "https://cottondb.com/v1/google/callback",      response_type: "code",      scope: SCOPES,      access_type: "offline",      prompt: "consent",      include_granted_scopes: "false",      state: res.body.state,    });    expect(SCOPES).toBe("openid email https://www.googleapis.com/auth/calendar.events.owned");    expect(res.body.state).toMatch(new RegExp(`^${DATABASE_ID}\\.[A-Za-z0-9_-]{20,}$`));  });  it("is the owner's alone", async () => {    await personalObject("gstranger");    expect((await http("gstranger", "GET", "/v1/google/connect")).status).toBe(403);    expect((await http("gstranger", "GET", "/v1/google/status")).status).toBe(403);  });  it("refuses by name on a Worker with no Google client", () => {    let error: unknown = null;    try {      client({ ...env, GOOGLE_CLIENT_SECRET: undefined });    } catch (e) {      error = e;    }    expect(error).toBeInstanceOf(Refused);    expect((error as Refused).code).toBe("google_unavailable");  });  it("trades the code, names the account by the address in Google's ID token, seals the refresh token into a secret row and says so in plain words", async () => {    const { owner } = await personalObject("gtrade");    const calls = google(tokens, primary, quiet);    const done = await connectAccount("gtrade", owner);    expect(done.status, done.text).toBe(200);    expect(done.text).toContain("Google Calendar is connected");    expect(done.text).toContain(EMAIL);    expect(done.text).not.toContain(REFRESH);    const trade = calls.find((c) => c.form.grant_type === "authorization_code")!;    expect(trade.form).toEqual({ grant_type: "authorization_code", code: "test-code", client_id: "test-client.apps.googleusercontent.com", client_secret: "test-client-secret", redirect_uri: "https://cottondb.com/v1/google/callback" });    // The calendar itself is never asked for: calendar.events cannot read it.    expect(calls.filter((c) => c.url.pathname === "/calendar/v3/calendars/primary")).toEqual([]);    expect(calls.filter((c) => c.url.pathname === "/calendar/v3/calendars/primary/events").every((c) => c.authorization === `Bearer ${ACCESS}`)).toBe(true);    const secrets = await answer<{ secrets: { name: string; service: string; kind: string }[] }>("gtrade", owner, "list_secrets", { service: "google" });    expect(secrets.secrets).toEqual([expect.objectContaining({ name: `google.${EMAIL}`, service: "google", kind: "api_key" })]);    // S2: no part of a value is listed, the object's own tokens' either.    expect(JSON.stringify(secrets.secrets)).not.toContain(REFRESH.slice(-4));    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName("gtrade")), (_instance, state) => {      const store = new Store(state.storage.sql, () => new Date());      const row = store.list("secret", { column: "service", equals: "google" })[0]!;      expect(String(row.data.sealed)).toMatch(/^t1:/);      expect(JSON.stringify(row.data)).not.toContain(REFRESH);    });    const status = await http<{ available: boolean; accounts: Record<string, unknown>[] }>("gtrade", "GET", "/v1/google/status", undefined, bearer(owner));    expect(status.body.available).toBe(true);    expect(status.body.accounts).toEqual([expect.objectContaining({ googleEmail: EMAIL, canWrite: true, calendar: expect.objectContaining({ phase: expect.stringMatching(/^(waiting|syncing|synced)$/), lastError: null }) })]);    expect(done.text).toContain("saves the changes you make in Days back to it");  });  it("takes a grant of the wider calendar.events, asked until 24 Nov 2026, as one that writes: an account connected with it needs no new connect", async () => {    const { owner } = await personalObject("gwide");    google(tokensWith(GRANTED_WIDE), quiet, revoked);    const done = await connectAccount("gwide", owner);    expect(done.status, done.text).toBe(200);    expect(done.text).toContain("saves the changes you make in Days back to it");    const read = await http<{ accounts: { googleEmail: string; canWrite: boolean }[] }>("gwide", "GET", "/v1/google/status", undefined, bearer(owner));    expect(read.body.accounts).toEqual([expect.objectContaining({ googleEmail: EMAIL, canWrite: true })]);  });  it("keeps reading with a grant of the old read-only scope, says it cannot write, and connecting again replaces the grant with one that can", async () => {    const { owner } = await personalObject("greadonly");    google(tokensWith(GRANTED_READONLY), quiet, revoked);    const first = await connectAccount("greadonly", owner);    expect(first.status, first.text).toBe(200);    expect(first.text).not.toContain("saves the changes");    type S = { keep: boolean; accounts: { googleEmail: string; canWrite: boolean }[] };    const read = await http<S>("greadonly", "GET", "/v1/google/status", undefined, bearer(owner));    expect(read.body).toMatchObject({ keep: false, accounts: [{ googleEmail: EMAIL, canWrite: false }] });    google(tokens, quiet, revoked);    expect((await connectAccount("greadonly", owner)).status).toBe(200);    const again = await http<S>("greadonly", "GET", "/v1/google/status", undefined, bearer(owner));    expect(again.body.accounts).toEqual([expect.objectContaining({ googleEmail: EMAIL, canWrite: true })]);  });  it("reads an account kept before Days wrote (no can_write) as read-only", async () => {    const { owner } = await personalObject("glegacyacct");    google(tokens, quiet, revoked);    await connectAccount("glegacyacct", owner);    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName("glegacyacct")), (_instance, state) => {      const store = new Store(state.storage.sql, () => new Date());      const accounts = JSON.parse(store.meta("google_accounts")!) as Record<string, unknown>[];      for (const a of accounts) {        delete a.can_write;        delete a.scopes;      }      store.setMeta("google_accounts", JSON.stringify(accounts));    });    const s = await http<{ accounts: { canWrite: boolean }[] }>("glegacyacct", "GET", "/v1/google/status", undefined, bearer(owner));    expect(s.body.accounts[0]!.canWrite).toBe(false);  });  it("keeps the person's choice to keep their own Days events in Google Calendar too, and says it in the status", async () => {    const { owner } = await personalObject("gkeep");    expect((await http("gkeep", "POST", "/v1/google/settings", { keep: "yes" }, bearer(owner))).status).toBe(400);    expect((await http("gkeep", "POST", "/v1/google/settings", { keep: true })).status).toBe(403);    const on = await http("gkeep", "POST", "/v1/google/settings", { keep: true }, bearer(owner));    expect(on.body).toEqual({ keep: true });    expect((await http<{ keep: boolean }>("gkeep", "GET", "/v1/google/status", undefined, bearer(owner))).body.keep).toBe(true);    await http("gkeep", "POST", "/v1/google/settings", { keep: false }, bearer(owner));    expect((await http<{ keep: boolean }>("gkeep", "GET", "/v1/google/status", undefined, bearer(owner))).body.keep).toBe(false);  });  it("names the Cotton account the answer goes into and trades nothing until Connect is tapped (ROUTES-AUDIT 16)", async () => {    const { owner } = await personalObject("gconfirm");    const calls = google(tokens, primary, quiet);    const connect = await http<{ state: string }>("gconfirm", "GET", "/v1/google/connect", undefined, bearer(owner));    const url = `https://example.test/b/gconfirm/v1/google/callback?code=test-code&state=${encodeURIComponent(connect.body.state)}`;    const arrived = await SELF.fetch(url);    const text = await arrived.text();    expect(arrived.status).toBe(200);    expect(text).toContain("Connect Google Calendar?");    expect(text).toContain(`the Cotton account of ${"•".repeat(OWNER_PHONE.replace(/\D/g, "").length - 4)}${OWNER_PHONE.slice(-4)}`);    expect(text).not.toContain(OWNER_PHONE);    expect(calls.filter((c) => c.form.grant_type === "authorization_code"), "nothing traded on arrival").toEqual([]);    // The state is not spent by looking: the tap still connects.    const done = await page(url);    expect(done.status, done.text).toBe(200);    expect(done.text).toContain("Google Calendar is connected");    expect(calls.filter((c) => c.form.grant_type === "authorization_code")).toHaveLength(1);  });  it("spends a state once: the same answer brought back again is refused before Google is asked", async () => {    const { owner } = await personalObject("gonce");    google(tokens, primary, quiet);    const first = await connectAccount("gonce", owner);    expect(first.status).toBe(200);    const calls = google(tokens, quiet);    const again = await page(`https://example.test/b/gonce/v1/google/callback?code=test-code&state=${encodeURIComponent(first.state)}`);    expect(again.status).toBe(400);    expect(again.text).toContain("expired or was already used");    expect(calls.filter((c) => c.form.grant_type === "authorization_code")).toEqual([]);  });  it("refuses a state this object never gave", async () => {    await personalObject("gforged");    const calls = google();    const forged = await page(`https://example.test/b/gforged/v1/google/callback?code=test-code&state=${DATABASE_ID}.forged-state-value`);    expect(forged.status).toBe(400);    expect(calls).toEqual([]);  });  it("keeps nothing when the person declines, or unticks the calendar on Google's page (and gives the grant back)", async () => {    const { owner } = await personalObject("gdecline");    google();    const connect = await http<{ state: string }>("gdecline", "GET", "/v1/google/connect", undefined, bearer(owner));    const declined = await page(`https://example.test/b/gdecline/v1/google/callback?error=access_denied&state=${encodeURIComponent(connect.body.state)}`);    expect(declined.text).toContain("Google did not give Days access");    const calls = google((call) => (call.form.grant_type === "authorization_code" ? reply(200, { access_token: ACCESS, refresh_token: REFRESH, scope: "openid", expires_in: 3599 }) : null), revoked, quiet);    const unticked = await connectAccount("gdecline", owner);    expect(unticked.status).toBe(400);    expect(unticked.text).toContain("Calendar access was not ticked");    expect(calls.find((c) => c.url.pathname === "/revoke")!.form).toEqual({ token: REFRESH });    const status = await http<{ accounts: unknown[] }>("gdecline", "GET", "/v1/google/status", undefined, bearer(owner));    expect(status.body.accounts).toEqual([]);  });  it("keeps nothing when the address was unticked or Google named no verified address, and gives the grant back", async () => {    const { owner } = await personalObject("gnoemail");    const withScope = (scope: string, token: string | undefined) =>      google((call) => (call.form.grant_type === "authorization_code" ? reply(200, { access_token: ACCESS, refresh_token: REFRESH, scope, expires_in: 3599, ...(token ? { id_token: token } : {}) }) : null), revoked, quiet);    for (const [scope, token] of [      ["openid https://www.googleapis.com/auth/calendar.events.readonly", idToken({ email: "owner@example.com", email_verified: true })],      [GRANTED, undefined],      [GRANTED, idToken({ email: "owner@example.com", email_verified: false })],    ] as const) {      const calls = withScope(scope, token);      const done = await connectAccount("gnoemail", owner);      expect(done.status).toBe(400);      expect(done.text).toContain("Google did not share which account this is");      expect(calls.find((c) => c.url.pathname === "/revoke")!.form).toEqual({ token: REFRESH });    }    const status = await http<{ accounts: unknown[] }>("gnoemail", "GET", "/v1/google/status", undefined, bearer(owner));    expect(status.body.accounts).toEqual([]);  });  it("reads the address out of an ID token, lower-cased", () => {    expect(addressOf(idToken({ email: "Walk.A@Example.com", email_verified: true }))).toBe("walk.a@example.com");    expect(addressOf(idToken({ email_verified: true }))).toBeNull();    expect(addressOf("not-a-token")).toBeNull();    expect(addressOf(undefined)).toBeNull();  });  it("brings Google's answer back to the open host whichever host the connect was asked on, and finds the object by the state alone", async () => {    const { owner } = await personalObject("asha");    const entered = await SELF.fetch("https://cottondb.com/v1/admin/directory", { method: "POST", headers: { "content-type": "application/json", ...ADMIN }, body: JSON.stringify({ database_id: DATABASE_ID, slug: "asha", phone: OWNER_PHONE }) });    expect(entered.status, await entered.text()).toBe(200);    const calls = google(tokens, primary, quiet, revoked);    const res = await SELF.fetch("https://cottondb.com/v1/google/connect", { headers: bearer(owner) });    expect(res.status).toBe(200);    const connect = (await res.json()) as { authorizeUrl: string; state: string };    const redirect = "https://cottondb.com/v1/google/callback";    expect(new URL(connect.authorizeUrl).searchParams.get("redirect_uri")).toBe(redirect);    const done = await page(`${redirect}?code=test-code&state=${encodeURIComponent(connect.state)}`);    expect(done.status, done.text).toBe(200);    expect(done.text).toContain("Google Calendar is connected");    // The code is traded against the redirect it was given for.    expect(calls.find((c) => c.form.grant_type === "authorization_code")!.form.redirect_uri).toBe(redirect);    // A connect asked on another host still gets the open host's callback.    const elsewhere = await http<{ authorizeUrl: string }>("asha", "GET", "/v1/google/connect", undefined, bearer(owner));    expect(new URL(elsewhere.body.authorizeUrl).searchParams.get("redirect_uri")).toBe("https://cottondb.com/v1/google/callback");    const nobody = await page("https://cottondb.com/v1/google/callback?code=test-code&state=not-a-state");    expect(nobody.status).toBe(400);  });  it("keeps pulling with a grant made before the scope change (calendar.readonly, no address scope): nothing to connect again", async () => {    const { owner } = await personalObject("goldgrant", EVENTS_OPEN);    const cal = new FakeCalendar();    cal.put({ id: "standup", summary: "Stand-up", start: { dateTime: new Date(Date.now() + 86_400_000).toISOString() }, end: { dateTime: new Date(Date.now() + 90_000_000).toISOString() }, iCalUID: "standup@google.com" });    google(tokens, cal.route, revoked);    await connectAccount("goldgrant", owner);    // From here Google answers as for the owner's grant made by the old code: the old scope on refresh, no ID token, no address scope.    const OLD = "https://www.googleapis.com/auth/calendar.readonly";    const calls = google(      (call) => (call.url.href === "https://oauth2.googleapis.com/token" && call.form.grant_type === "refresh_token" ? reply(200, { access_token: ACCESS, expires_in: 3599, scope: OLD, token_type: "Bearer" }) : null),      cal.route,    );    cal.put({ id: "lunch", summary: "Lunch", start: { dateTime: new Date(Date.now() + 2 * 86_400_000).toISOString() }, end: { dateTime: new Date(Date.now() + 2 * 86_400_000 + 3_600_000).toISOString() }, iCalUID: "lunch@google.com" });    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("goldgrant"));    type Cal = { phase: string; lastError: string | null; eventCount: number };    const calendar = async () => (await http<{ accounts: { calendar: Cal }[] }>("goldgrant", "GET", "/v1/google/status", undefined, bearer(owner))).body.accounts[0]!.calendar;    for (let n = 0; n < 12 && (await calendar()).eventCount !== 2; n++) await runDurableObjectAlarm(stub);    expect(await calendar()).toEqual(expect.objectContaining({ phase: "synced", lastError: null, eventCount: 2 }));    expect(calls.some((c) => c.form.grant_type === "refresh_token")).toBe(true);    expect(calls.filter((c) => c.url.pathname === "/calendar/v3/calendars/primary/events").length).toBeGreaterThan(0);  });  it("disconnects: the grant revoked at Google, its secret binned, the account forgotten, and its events leave", async () => {    const { owner } = await personalObject("gdisconnect", EVENTS_OPEN);    const cal = new FakeCalendar();    cal.put({ id: "standup", summary: "Stand-up", start: { dateTime: new Date(Date.now() + 86_400_000).toISOString() }, end: { dateTime: new Date(Date.now() + 90_000_000).toISOString() }, iCalUID: "standup@google.com" });    cal.put({ id: "lunch", summary: "Lunch", start: { dateTime: new Date(Date.now() + 2 * 86_400_000).toISOString() }, end: { dateTime: new Date(Date.now() + 2 * 86_400_000 + 3_600_000).toISOString() }, iCalUID: "lunch@google.com" });    google(tokens, cal.route, revoked);    await connectAccount("gdisconnect", owner);    const pulled = async () => (await http<{ accounts: { calendar: { eventCount: number; phase: string } }[] }>("gdisconnect", "GET", "/v1/google/status", undefined, bearer(owner))).body.accounts[0]?.calendar;    for (let n = 0; n < 12 && (await pulled())?.eventCount !== 2; n++) await runDurableObjectAlarm(env.BUSINESS.get(env.BUSINESS.idFromName("gdisconnect")));    expect(await pulled()).toEqual(expect.objectContaining({ eventCount: 2 }));    // The person's own event stays.    const own = await http("gdisconnect", "POST", "/v1/admin/import", { rows: [{ verb: "put", table: "event", id: "11111111-2222-4333-8444-555555555555", data: { title: "My own dinner", starts_at: new Date(Date.now() + 86_400_000).toISOString() } }] }, ADMIN);    expect(own.status, JSON.stringify(own.body)).toBe(200);    const calls = google(tokens, quiet, revoked);    const gone = await http("gdisconnect", "POST", "/v1/google/disconnect", {}, bearer(owner));    expect(gone.status, JSON.stringify(gone.body)).toBe(200);    expect(gone.body).toEqual({ ok: true, account: EMAIL, removed: 2 });    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName("gdisconnect")), (_instance, state) => {      const store = new Store(state.storage.sql, () => new Date());      const live = [...store.scan("event")].filter((row) => !row.data.trashed_at);      expect(live.map((row) => row.data.gcal_id ?? null)).toEqual([null]);    });    expect(calls.filter((c) => c.url.pathname === "/revoke").map((c) => c.form)).toEqual([{ token: REFRESH }]);    const status = await http<{ accounts: unknown[] }>("gdisconnect", "GET", "/v1/google/status", undefined, bearer(owner));    expect(status.body.accounts).toEqual([]);    const secrets = await answer<{ secrets: unknown[] }>("gdisconnect", owner, "list_secrets", { service: "google" });    expect(secrets.secrets).toEqual([]);    expect((await http("gdisconnect", "POST", "/v1/google/disconnect", {}, bearer(owner))).status).toBe(404);  });});