iterate.com / cloud

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

cloud / internal-packages / dummy-petshop / src / google.tsmain at aacbc74

/**
 * A Google-shaped fake, served on the pet shop's origin at Google's own paths,
 * so an integration pointed at this origin speaks to it exactly as to
 * accounts.google.com, oauth2.googleapis.com, www.googleapis.com and
 * gmail.googleapis.com at once:
 *
 *   GET  /.well-known/openid-configuration   the issuer is this origin (OpenID Connect sign-in)
 *   GET  /oauth2/v3/certs              the JWKS its ID tokens verify against (oidc.ts)
 *   GET  /o/oauth2/v2/auth             consent at once: redirects with a code for the account
 *                                      `&email=<e>` (else `login_hint`), minted when absent; with
 *                                      `prompt=select_account` and neither, the account picker
 *                                      (oidc.ts) asks for the address first
 *   POST /token                        authorization_code (PKCE when the code carried a
 *                                      challenge) | refresh_token; the client by HTTP Basic or
 *                                      the form. Like Google, a refresh token only for a consent
 *                                      prompt (`prompt=consent`), and an RS256 ID token echoing
 *                                      the nonce when `openid` was asked for
 *   GET  /oauth2/v2/userinfo           whose access token this is; the account's id is
 *                                      `fakeUserIdOf(email)`, like Google's numeric `sub`
 *   POST /revoke?token=                a refresh token stops refreshing
 *   GET  /gmail/v1/users/me/profile    the account's Gmail profile
 *   POST /gmail/v1/users/me/watch      { topicName } → the account's mailbox is watched for a
 *                                      week, as Gmail's `users.watch`: { historyId, expiration }
 *   POST /gmail/v1/users/me/stop       the watch ends
 *   GET  /gmail/v1/users/me/history    ?startHistoryId= → the messages that arrived since, as
 *                                      `users.history.list`: one record each, oldest first;
 *                                      `maxResults` and `pageToken` page it. 404 for a place the
 *                                      mailbox no longer has
 *   GET  /gmail/v1/users/me/messages/<id>   one message's ids, labels, snippet and headers, as
 *                                      `users.messages.get` with `format=metadata`
 *   …    /calendar/v3/…                the account's primary calendar (google-calendar.ts)
 *
 * The OAuth steps are the fakes' one authorization server (authorization-server.ts). A watched
 * mailbox gets a mail, and a calendar an event, when a test says so (`handleGoogleTestControls`).
 */
import { z } from "zod";
import {
  fakeAuthorizationServer,
  redirectTo,
  scheduledTokenFailure,
  tokenClient,
} from "./authorization-server.ts";
import {
  calendarAnswer,
  delivered,
  googleApiError,
  handleCalendarTestControls,
} from "./google-calendar.ts";
import type { GmailMessage } from "./google-records.ts";
import { accountPicker, discoveryDocument, jwks, signIdToken } from "./oidc.ts";
import { ACCESS_TOKEN_TTL_SECONDS, fakeUserIdOf, type ShopDeps } from "./state.ts";

interface GoogleGrant {
  email: string;
  scope: string;
  /** The OpenID nonce to echo in the ID token. */
  nonce?: string;
  /** The consent prompt was shown: only then does a refresh token come back. */
  consent?: boolean;
}

const googleError = (error: string, status = 400) => Response.json({ error }, { status });

/** How long Gmail keeps a watch that nobody asks for again. */
const GMAIL_WATCH_MS = 7 * 24 * 60 * 60_000;
/** The service account of the fake's push subscription: the verified address in a push's token,
 *  unless the control names another. */
export const GMAIL_PUSH_SERVICE_ACCOUNT = "gmail-push@petshop.iam.gserviceaccount.com";

/** Google's paths on this origin, or null when the request is not one of them. */
export async function handleGoogleRequest(
  request: Request,
  deps: ShopDeps,
): Promise<Response | null> {
  const url = new URL(request.url);
  const key = `${request.method} ${url.pathname}`;
  const google = fakeAuthorizationServer<GoogleGrant>(deps, "google", (grant) => grant.email);
  if (key === "GET /.well-known/openid-configuration")
    return Response.json(
      discoveryDocument(url.origin, {
        authorization: "/o/oauth2/v2/auth",
        token: "/token",
        jwks: "/oauth2/v3/certs",
        userinfo: "/oauth2/v2/userinfo",
      }),
    );
  if (key === "GET /oauth2/v3/certs") return Response.json(await jwks(deps));
  if (key === "GET /o/oauth2/v2/auth") {
    const query = Object.fromEntries(url.searchParams);
    const refusal = await google.authorizeRefusal(query.client_id || "", query.redirect_uri || "");
    if (refusal) return refusal;
    // `prompt` is a space-separated list (`select_account consent`)
    const prompts = (query.prompt || "").split(" ");
    if (prompts.includes("select_account") && !query.email && !query.login_hint)
      return accountPicker(url, ["email"]);
    const code = await google.code({
      clientId: query.client_id!,
      redirectUri: query.redirect_uri!,
      codeChallenge: query.code_challenge,
      grant: {
        email:
          query.email || query.login_hint || `user-${crypto.randomUUID().slice(0, 8)}@petshop.test`,
        scope: query.scope || "openid email profile",
        nonce: query.nonce,
        consent: prompts.includes("consent"),
      },
    });
    return redirectTo(query.redirect_uri!, { code, state: query.state });
  }
  if (key === "POST /token") {
    const form = Object.fromEntries(new URLSearchParams(await request.text()));
    const client = await tokenClient(deps, request, form);
    if (!client || client.client.public) return googleError("invalid_client", 401);
    const failed = await scheduledTokenFailure(deps, client.clientId);
    if (failed) return failed;
    let grant: GoogleGrant;
    if (form.grant_type === "authorization_code") {
      const redeemed = await google.redeemCode(form.code || "", {
        ...client,
        redirectUri: form.redirect_uri,
        codeVerifier: form.code_verifier,
      });
      if ("refused" in redeemed)
        return googleError(
          redeemed.refused === "redirect_uri mismatch" ? "redirect_uri_mismatch" : "invalid_grant",
        );
      grant = redeemed.grant;
    } else if (form.grant_type === "refresh_token") {
      const refresh = await google.openRefreshToken(form.refresh_token || "", client.clientId);
      if (!refresh) return googleError("invalid_grant");
      // a refresh answers no new refresh token, nor an ID token's nonce
      grant = { email: refresh.grant.email, scope: refresh.grant.scope };
    } else return googleError("unsupported_grant_type");
    return Response.json({
      access_token: await google.accessToken(client.clientId, grant, ACCESS_TOKEN_TTL_SECONDS),
      expires_in: ACCESS_TOKEN_TTL_SECONDS,
      scope: grant.scope,
      token_type: "Bearer",
      ...(grant.consent && { refresh_token: await google.refreshToken(client.clientId, grant) }),
      ...(grant.scope.split(" ").includes("openid") && {
        id_token: await signIdToken(deps, {
          issuer: url.origin,
          clientId: client.clientId,
          claims: {
            sub: String(fakeUserIdOf(grant.email)),
            email: grant.email,
            email_verified: true,
            name: grant.email.split("@")[0],
            nonce: grant.nonce || undefined,
          },
        }),
      }),
    });
  }
  if (key === "POST /revoke") {
    const token = url.searchParams.get("token") || "";
    const known = (await google.revokeRefreshToken(token)) || (await google.openAccessToken(token));
    return known ? Response.json({}) : googleError("invalid_token");
  }
  const gmailPath = /^\/gmail\/v1\/users\/me\/(.+)$/.exec(url.pathname)?.[1];
  const calendarPath = /^\/calendar\/v3\/(.+)$/.exec(url.pathname)?.[1];
  if (key !== "GET /oauth2/v2/userinfo" && !gmailPath && !calendarPath) return null;
  const bearer = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
  const access = await google.openAccessToken(bearer || "");
  if (!access) return googleApiError(401, "UNAUTHENTICATED", "Invalid Credentials");
  const { email } = access.grant;
  if (calendarPath) return calendarAnswer(request, deps, access.grant, calendarPath);
  if (gmailPath) return gmailAnswer(request, deps, email, gmailPath);
  return Response.json({ id: String(fakeUserIdOf(email)), email, name: email.split("@")[0] });
}

/** A request under `/gmail/v1/users/me/` (`path` is what follows), as the account `email`. */
async function gmailAnswer(
  request: Request,
  deps: ShopDeps,
  email: string,
  path: string,
): Promise<Response> {
  const url = new URL(request.url);
  const address = email.toLowerCase();
  const route = `${request.method} ${path}`;
  if (route === "POST stop") {
    await deps.state.changeGmailMailbox(address, { watch: null });
    return new Response(null, { status: 204 });
  }
  if (route === "POST watch") {
    const { topicName } = ((await request.json().catch(() => null)) || {}) as {
      topicName?: unknown;
    };
    if (typeof topicName !== "string" || !/^projects\/[^/]+\/topics\/[^/]+$/.test(topicName))
      return googleApiError(
        400,
        "INVALID_ARGUMENT",
        "Invalid topicName does not match projects/{project}/topics/{topic}",
      );
    // a watch asked for again is the same watch, for another week
    const expiration = Date.now() + GMAIL_WATCH_MS;
    const { mailbox } = await deps.state.changeGmailMailbox(address, {
      watch: { topicName, expiration },
    });
    return Response.json({
      historyId: String(mailbox.historyId),
      expiration: String(expiration),
    });
  }
  const mailbox = (await deps.state.gmailMailbox(address)) || {
    historyId: 1,
    historyFrom: 1,
    history: [],
  };
  if (route === "GET profile")
    return Response.json({
      emailAddress: email,
      messagesTotal: mailbox.history.length,
      historyId: String(mailbox.historyId),
    });
  if (route === "GET history") {
    const start = url.searchParams.get("startHistoryId") || "";
    if (!/^\d+$/.test(start))
      return googleApiError(400, "INVALID_ARGUMENT", "Missing required field: startHistoryId");
    // a place before the records the mailbox still has: Gmail says it is gone
    if (Number(start) < mailbox.historyFrom)
      return googleApiError(404, "NOT_FOUND", "Requested entity was not found.");
    // every record of the fake is a message that arrived
    const kinds = url.searchParams.getAll("historyTypes");
    const after = Number(url.searchParams.get("pageToken") || start);
    const records =
      kinds.length === 0 || kinds.includes("messageAdded")
        ? mailbox.history.filter((record) => record.id > after)
        : [];
    const size = Math.min(Math.max(Number(url.searchParams.get("maxResults")) || 100, 1), 500);
    const page = records.slice(0, size);
    // Gmail names no `history` when nothing changed
    return Response.json({
      ...(page.length > 0 && {
        history: page.map(({ id, message }) => ({
          id: String(id),
          messagesAdded: [
            { message: { id: message.id, threadId: message.id, labelIds: message.labelIds } },
          ],
        })),
      }),
      ...(records.length > size && { nextPageToken: String(page.at(-1)!.id) }),
      historyId: String(mailbox.historyId),
    });
  }
  const record = mailbox.history.find(({ message }) => route === `GET messages/${message.id}`);
  if (!record) return googleApiError(404, "NOT_FOUND", "Requested entity was not found.");
  const { message } = record;
  // with `metadataHeaders`, only the headers named, whatever their case
  const named = url.searchParams.getAll("metadataHeaders").map((name) => name.toLowerCase());
  return Response.json({
    id: message.id,
    threadId: message.id,
    labelIds: message.labelIds,
    snippet: message.snippet,
    internalDate: String(message.internalDate),
    historyId: String(record.id),
    payload: {
      headers: message.headers.filter(
        ({ name }) => named.length === 0 || named.includes(name.toLowerCase()),
      ),
    },
  });
}

/**
 * The Google fake's test controls (the Calendar's are google-calendar.ts
 * `handleCalendarTestControls`):
 *
 *   POST /__test-controls/google/gmail-push   { email, url, audience?, serviceAccount?,
 *        message?: { from?, to?, subject?, snippet?, labelIds? } } → ONE MAIL ARRIVES in that
 *        mailbox (by default one to the mailbox, with the labels INBOX and UNREAD): the
 *        mailbox's history id moves on by one, and its history has one record more, which holds
 *        the message. The change is POSTed to `url` as Google's Pub/Sub pushes a Gmail
 *        notification to a push subscription: the envelope `{ message: { data, messageId,
 *        publishTime }, subscription }`, where `data` is base64 of `{ emailAddress, historyId }`,
 *        and `authorization: Bearer <token>`. The token is signed with the key the certs address
 *        publishes (`/oauth2/v3/certs`), its issuer is this origin, its audience is `audience`
 *        (else `url`), and its verified address is `serviceAccount` (else
 *        `GMAIL_PUSH_SERVICE_ACCOUNT`). The answer names the mail's id at Gmail
 *        (`gmailMessageId`) beside Pub/Sub's `messageId`. 409 when nobody watches the mailbox:
 *        Gmail publishes only what `users.watch` asked for.
 *   POST /__test-controls/google/gmail-forget-history   { email } → that mailbox's history is
 *        gone: every place before its newest history id answers 404, as at Gmail after a week.
 */
export async function handleGoogleTestControls(
  request: Request,
  deps: ShopDeps,
): Promise<Response | null> {
  const url = new URL(request.url);
  const key = `${request.method} ${url.pathname}`;
  if (key === "POST /__test-controls/google/gmail-forget-history") {
    const input = z
      .object({ email: z.string().min(3) })
      .safeParse(await request.json().catch(() => null));
    if (!input.success)
      return Response.json(
        { error: "invalid_request", error_description: "email is required" },
        { status: 400 },
      );
    const email = input.data.email.toLowerCase();
    const { mailbox } = await deps.state.changeGmailMailbox(email, { forget: true });
    return Response.json({ email, historyId: String(mailbox.historyId) });
  }
  if (key !== "POST /__test-controls/google/gmail-push")
    return handleCalendarTestControls(request, deps);
  const input = GmailPush.safeParse(await request.json().catch(() => null));
  if (!input.success)
    return Response.json(
      { error: "invalid_request", error_description: "email and an absolute url are required" },
      { status: 400 },
    );
  const email = input.data.email.toLowerCase();
  const id = [...crypto.getRandomValues(new Uint8Array(8))]
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");
  const mail = input.data.message || {};
  const arrives: GmailMessage = {
    id,
    labelIds: mail.labelIds || ["INBOX", "UNREAD"],
    snippet: mail.snippet || "A mail from the pet shop.",
    internalDate: Date.now(),
    headers: [
      { name: "From", value: mail.from || "The pet shop <shop@petshop.test>" },
      { name: "To", value: mail.to || email },
      { name: "Subject", value: mail.subject || "A mail from the pet shop" },
      { name: "Date", value: new Date().toUTCString() },
      { name: "Message-ID", value: `<${id}@petshop.test>` },
    ],
  };
  const { mailbox, done } = await deps.state.changeGmailMailbox(email, { arrives });
  if (!done || !mailbox.watch)
    return Response.json(
      { error: "not_watched", error_description: `nobody watches ${email}` },
      { status: 409 },
    );
  // Pub/Sub's message id: digits
  const messageId = String(crypto.getRandomValues(new BigUint64Array(1))[0]);
  const token = await signIdToken(deps, {
    issuer: url.origin,
    clientId: input.data.audience || input.data.url,
    claims: {
      email: input.data.serviceAccount || GMAIL_PUSH_SERVICE_ACCOUNT,
      email_verified: true,
    },
  });
  return Response.json({
    email,
    topicName: mailbox.watch.topicName,
    historyId: String(mailbox.historyId),
    messageId,
    gmailMessageId: id,
    url: input.data.url,
    ...(await delivered(input.data.url, {
      headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
      body: JSON.stringify({
        message: {
          data: btoa(JSON.stringify({ emailAddress: email, historyId: mailbox.historyId })),
          messageId,
          publishTime: new Date().toISOString(),
        },
        subscription: mailbox.watch.topicName.replace("/topics/", "/subscriptions/"),
      }),
    })),
  });
}

const GmailPush = z.object({
  email: z.string().min(3),
  url: z.url(),
  audience: z.string().min(1).optional(),
  serviceAccount: z.string().min(1).optional(),
  message: z
    .object({
      from: z.string().min(1).max(200).optional(),
      to: z.string().min(1).max(200).optional(),
      subject: z.string().min(1).max(200).optional(),
      snippet: z.string().min(1).max(200).optional(),
      labelIds: z.array(z.string().min(1).max(64)).max(10).optional(),
    })
    .optional(),
});