iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / dummy-petshop / src / calendar-push.test.tsmain at aacbc74

/**
 * The Google fake's Calendar (google-calendar.ts): an account's primary calendar is watched with
 * channels, as Google's `events.watch` makes them; the `google/calendar-change` control changes
 * the calendar and pushes to each live channel as Google does (headers alone, no body); and the
 * events are read with a sync token, as `events.list` answers one.
 */
import { expect, test, vi } from "vitest";
import { memoryPetshop } from "./memory-state.ts";
import { DEFAULT_CLIENT_ID, DEFAULT_CLIENT_SECRET } from "./state.ts";
import { handleTestControls } from "./test-controls.ts";

const ORIGIN = "https://petshop.test";
const CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar";
/** Where the channels of these tests deliver: a Cloud's address for Calendar's push. */
const RECEIVER = "https://cloud.test/clients/google/calendar-webhook";
const DAY_MS = 24 * 60 * 60_000;

test("a calendar is its account's own, read and watched only by a grant with a calendar scope", async () => {
  const petshop = memoryPetshop();
  const ada = await accessTokenOf(petshop, "Ada@petshop.test", `openid ${CALENDAR_SCOPE}.readonly`);
  const mailOnly = await accessTokenOf(petshop, "bo@petshop.test", "openid email");

  expect(await calendar(petshop, ada, "GET", "calendars/primary")).toEqual({
    status: 200,
    body: { kind: "calendar#calendar", id: "ada@petshop.test", summary: "ada@petshop.test" },
  });
  // Google refuses a grant with no calendar scope, and a request with no token of the shop's
  for (const path of ["calendars/primary", "calendars/primary/events"])
    expect(await calendar(petshop, mailOnly, "GET", path)).toMatchObject({
      status: 403,
      body: { error: { code: 403, status: "PERMISSION_DENIED" } },
    });
  expect(
    await calendar(petshop, mailOnly, "POST", "calendars/primary/events/watch", {
      id: "channel-1",
      type: "web_hook",
      address: RECEIVER,
    }),
  ).toMatchObject({ status: 403 });
  expect(await calendar(petshop, "no token", "GET", "calendars/primary")).toMatchObject({
    status: 401,
  });
});

test("a calendar's change is pushed to each live channel as Google pushes it, and no channel that was stopped or is over", async () => {
  const petshop = memoryPetshop();
  // what this test puts in the place of `fetch` and of the clock goes when it ends
  using _restored = {
    [Symbol.dispose]: () => {
      vi.unstubAllGlobals();
      vi.useRealTimers();
    },
  };
  const pushes: Request[] = [];
  vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
    pushes.push(new Request(input, init));
    return Response.json({ accepted: true });
  });
  const ada = await accessTokenOf(petshop, "ada@petshop.test", `openid ${CALENDAR_SCOPE}`);
  const watch = (body: Record<string, unknown>) =>
    calendar(petshop, ada, "POST", "calendars/primary/events/watch", body);
  const change = (body: Record<string, unknown> = {}) =>
    control(petshop, "calendar-change", { email: "ada@petshop.test", ...body });

  // no channel yet: Google pushes to nobody
  expect(await change()).toMatchObject({ status: 409, body: { error: "not_watched" } });
  // a channel names itself and where it delivers, by a web hook
  for (const wrong of [
    { type: "web_hook", address: RECEIVER },
    { id: "channel-1", type: "web_hook" },
    { id: "channel-1", type: "email", address: RECEIVER },
  ])
    expect(await watch(wrong)).toMatchObject({ status: 400, body: { error: { code: 400 } } });

  // a channel lives as long as it asks for, and a week at most
  const twoDays = Date.now() + 2 * DAY_MS;
  const first = await watch({
    id: "channel-1",
    type: "web_hook",
    address: RECEIVER,
    token: "the-cloud's-token",
    expiration: twoDays,
  });
  expect(first).toEqual({
    status: 200,
    body: {
      kind: "api#channel",
      id: "channel-1",
      resourceId: expect.stringMatching(/^[\w-]+$/),
      resourceUri: `${ORIGIN}/calendar/v3/calendars/ada@petshop.test/events?alt=json`,
      token: "the-cloud's-token",
      expiration: String(twoDays),
    },
  });
  const second = await watch({
    id: "channel-2",
    type: "web_hook",
    address: RECEIVER,
    expiration: String(Date.now() + 30 * DAY_MS),
  });
  const days = (Number(second.body.expiration) - Date.now()) / DAY_MS;
  expect(Math.round(days)).toBe(7);
  expect(second.body).not.toHaveProperty("token");

  // THE PUSH: a POST with no body to each live channel's address, which says only that the
  // calendar changed, on which channel, and its number on that channel
  const changed = await change({ summary: "iterate push test 1" });
  expect(changed).toMatchObject({
    status: 200,
    body: {
      email: "ada@petshop.test",
      event: { id: expect.any(String), status: "confirmed", summary: "iterate push test 1" },
      pushed: [
        { channelId: "channel-1", url: RECEIVER, status: 200, body: { accepted: true } },
        { channelId: "channel-2", url: RECEIVER, status: 200, body: { accepted: true } },
      ],
    },
  });
  expect(pushes).toHaveLength(2);
  const [toFirst, toSecond] = pushes as [Request, Request];
  expect([toFirst.method, toFirst.url, await toFirst.text()]).toEqual(["POST", RECEIVER, ""]);
  expect(Object.fromEntries(toFirst.headers)).toMatchObject({
    "x-goog-channel-id": "channel-1",
    "x-goog-channel-token": "the-cloud's-token",
    "x-goog-channel-expiration": new Date(twoDays).toUTCString(),
    "x-goog-resource-id": first.body.resourceId,
    "x-goog-resource-uri": first.body.resourceUri,
    "x-goog-resource-state": "exists",
    // a channel's first message is Google's `sync`, which the fake does not send
    "x-goog-message-number": "2",
  });
  // a channel with no token sends none
  expect(toSecond.headers.get("x-goog-channel-id")).toBe("channel-2");
  expect(toSecond.headers.has("x-goog-channel-token")).toBe(false);
  // the number rises on each channel by itself
  await change({ summary: "iterate push test 2" });
  expect(pushes.slice(2).map((sent) => sent.headers.get("x-goog-message-number"))).toEqual([
    "3",
    "3",
  ]);

  // A STOPPED CHANNEL gets no more pushes; one that the account does not have cannot be stopped
  const stop = (id: string) =>
    calendar(petshop, ada, "POST", "channels/stop", { id, resourceId: first.body.resourceId });
  expect(await stop("channel-1")).toEqual({ status: 204, body: null });
  expect(await stop("channel-9")).toMatchObject({ status: 404 });
  const after = await change({ summary: "iterate push test 3" });
  expect(after.body.pushed.map((sent: { channelId: string }) => sent.channelId)).toEqual([
    "channel-2",
  ]);
  // A CHANNEL THAT IS OVER gets none either: a week on, the calendar has no live channel
  vi.useFakeTimers({ now: Date.now() + 8 * DAY_MS, toFake: ["Date"] });
  expect(await change()).toMatchObject({ status: 409 });
  expect(pushes).toHaveLength(5);
});

test("the calendar's events are read with a sync token: all of them first, then what changed, and 410 for a token that is gone", async () => {
  const petshop = memoryPetshop();
  using _restored = { [Symbol.dispose]: () => vi.unstubAllGlobals() };
  vi.stubGlobal("fetch", async () => Response.json({ accepted: true }));
  const ada = await accessTokenOf(petshop, "ada@petshop.test", `openid ${CALENDAR_SCOPE}`);
  const events = (query = "") =>
    calendar(petshop, ada, "GET", `calendars/primary/events${query && `?${query}`}`);
  const change = (body: Record<string, unknown> = {}) =>
    control(petshop, "calendar-change", { email: "ada@petshop.test", ...body });
  await calendar(petshop, ada, "POST", "calendars/primary/events/watch", {
    id: "channel-1",
    type: "web_hook",
    address: RECEIVER,
  });

  // THE FIRST READ of an empty calendar: no event, and the token to read on from
  const empty = await events();
  expect(empty).toEqual({
    status: 200,
    body: { kind: "calendar#events", items: [], nextSyncToken: expect.any(String) },
  });
  // with `fields`, only those: a first read that wants the token and no event
  expect(await events("fields=nextPageToken,nextSyncToken")).toEqual({
    status: 200,
    body: { nextSyncToken: empty.body.nextSyncToken },
  });

  const one = (await change({ summary: "iterate push test 1" })).body.event as { id: string };
  const two = (await change({ summary: "iterate push test 2" })).body.event as { id: string };
  // WHAT CHANGED SINCE THE TOKEN: both events, whole
  const since = await events(`syncToken=${encodeURIComponent(empty.body.nextSyncToken)}`);
  expect(since).toEqual({
    status: 200,
    body: {
      kind: "calendar#events",
      items: [
        {
          id: one.id,
          status: "confirmed",
          summary: "iterate push test 1",
          start: { dateTime: expect.stringMatching(/^\d{4}-\d\d-\d\dT/) },
          end: { dateTime: expect.stringMatching(/^\d{4}-\d\d-\d\dT/) },
          updated: expect.stringMatching(/^\d{4}-\d\d-\d\dT/),
          htmlLink: expect.stringContaining(one.id),
          organizer: { email: "ada@petshop.test" },
        },
        expect.objectContaining({ id: two.id, summary: "iterate push test 2" }),
      ],
      nextSyncToken: expect.any(String),
    },
  });
  expect(since.body).not.toMatchObject({ nextSyncToken: empty.body.nextSyncToken });
  // nothing changed since the new token
  const now = encodeURIComponent(since.body.nextSyncToken);
  expect((await events(`syncToken=${now}`)).body).toMatchObject({ items: [] });

  // A CANCELLED EVENT comes as its id and status alone, in a read by token; a first read lists
  // only what is not cancelled
  expect(await change({ cancel: one.id })).toMatchObject({
    status: 200,
    body: { event: { id: one.id, status: "cancelled" } },
  });
  expect(await events(`syncToken=${now}`)).toEqual({
    status: 200,
    body: {
      kind: "calendar#events",
      items: [{ id: one.id, status: "cancelled" }],
      nextSyncToken: expect.any(String),
    },
  });
  expect((await events()).body.items.map((event: { id: string }) => event.id)).toEqual([two.id]);
  expect(await change({ cancel: "no-such-event" })).toMatchObject({ status: 400 });

  // a page at a time: the token comes with the last page alone
  const old = encodeURIComponent(empty.body.nextSyncToken);
  const page = await events(`syncToken=${old}&maxResults=1`);
  expect(page.body).toMatchObject({ items: [{ id: one.id }], nextPageToken: expect.any(String) });
  expect(page.body).not.toHaveProperty("nextSyncToken");
  const last = await events(`syncToken=${old}&maxResults=1&pageToken=${page.body.nextPageToken}`);
  expect(last.body).toMatchObject({ items: [{ id: two.id }], nextSyncToken: expect.any(String) });
  expect(last.body).not.toHaveProperty("nextPageToken");

  // A TOKEN THE CALENDAR DOES NOT KNOW, and every token from before a test made them gone: 410,
  // as Google answers one that expired
  expect(await events("syncToken=not-a-token-of-the-shop")).toMatchObject({
    status: 410,
    body: { error: { code: 410 } },
  });
  expect(await control(petshop, "calendar-forget-sync", { email: "ada@petshop.test" })).toEqual({
    status: 200,
    body: { email: "ada@petshop.test" },
  });
  expect(await events(`syncToken=${now}`)).toMatchObject({ status: 410 });
  // a first read after it gives a token that reads on
  const fresh = await events("fields=nextPageToken,nextSyncToken");
  await change({ summary: "iterate push test 3" });
  const read = await events(`syncToken=${encodeURIComponent(fresh.body.nextSyncToken)}`);
  expect(read.body.items).toMatchObject([{ summary: "iterate push test 3" }]);
  expect(await control(petshop, "calendar-forget-sync", {})).toMatchObject({ status: 400 });
});

const REDIRECT_URI = "https://app.test/callback";

/** `email` consents at the Google fake to `scope` for the seeded client, whose code is
 *  exchanged: its access token. */
async function accessTokenOf(
  petshop: ReturnType<typeof memoryPetshop>,
  email: string,
  scope: string,
) {
  const authorize = new URL("/o/oauth2/v2/auth", ORIGIN);
  authorize.search = new URLSearchParams({
    client_id: DEFAULT_CLIENT_ID,
    redirect_uri: REDIRECT_URI,
    email,
    scope,
  }).toString();
  const consent = await petshop.handle(new Request(authorize));
  const code = new URL(consent!.headers.get("location")!).searchParams.get("code")!;
  const exchange = await petshop.handle(
    new Request(new URL("/token", ORIGIN), {
      method: "POST",
      body: new URLSearchParams({
        grant_type: "authorization_code",
        code,
        redirect_uri: REDIRECT_URI,
        client_id: DEFAULT_CLIENT_ID,
        client_secret: DEFAULT_CLIENT_SECRET,
      }),
    }),
  );
  return ((await exchange!.json()) as { access_token: string }).access_token;
}

/** One call of the fake's Calendar API as `token`'s account: its status, and its JSON (null for
 *  an answer with no body). */
async function calendar(
  petshop: ReturnType<typeof memoryPetshop>,
  token: string,
  method: "GET" | "POST",
  path: string,
  body?: unknown,
) {
  const answer = await petshop.handle(
    new Request(`${ORIGIN}/calendar/v3/${path}`, {
      method,
      headers: { authorization: `Bearer ${token}` },
      body: body ? JSON.stringify(body) : undefined,
    }),
  );
  return {
    status: answer!.status,
    body: (await answer!.json().catch(() => null)) as Record<string, any> | null as any,
  };
}

/** One of the Google fake's test controls: its status and JSON. */
async function control(
  petshop: ReturnType<typeof memoryPetshop>,
  name: string,
  body: Record<string, unknown>,
) {
  const answer = await handleTestControls(
    new Request(`${ORIGIN}/__test-controls/google/${name}`, {
      method: "POST",
      body: JSON.stringify(body),
    }),
    petshop,
  );
  return { status: answer.status, body: (await answer.json()) as Record<string, any> };
}