cloud / internal-packages / dummy-petshop / src / gmail-push.test.tsmain at aacbc74
/**
* The Google fake's Gmail push (google.ts): an account's mailbox is watched with the account's own
* token, and the `google/gmail-push` control then delivers a change of it as Google's Pub/Sub
* pushes one: its envelope, and a token that the shop's certs verify. The change is one message,
* which the mailbox's history and Gmail's message route then answer.
*/
import { expect, test, vi } from "vitest";
import { GMAIL_PUSH_SERVICE_ACCOUNT } from "./google.ts";
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";
/** Where the subscription of these tests delivers: a Cloud's address for Gmail's push. */
const SUBSCRIBER = "https://cloud.test/clients/google/webhook";
const TOPIC = "projects/petshop/topics/gmail-push";
test("a watched mailbox's change is pushed as Pub/Sub pushes it, with a token the shop's certs verify", 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");
const gmail = (path: string, token: string, body?: unknown) =>
petshop.handle(
new Request(`${ORIGIN}/gmail/v1/users/me/${path}`, {
method: "POST",
headers: { authorization: `Bearer ${token}` },
body: body ? JSON.stringify(body) : undefined,
}),
);
const push = async (body: Record<string, unknown>) => {
const answer = await handleTestControls(
new Request(`${ORIGIN}/__test-controls/google/gmail-push`, {
method: "POST",
body: JSON.stringify(body),
}),
petshop,
);
return { status: answer.status, body: (await answer.json()) as Record<string, any> };
};
// nobody watches the mailbox yet: nothing is pushed
expect(await push({ email: "ada@petshop.test", url: SUBSCRIBER })).toMatchObject({
status: 409,
body: { error: "not_watched" },
});
// a watch is the account's own call, and names a topic in full
expect(await gmail("watch", "no token of the shop's", { topicName: TOPIC })).toMatchObject({
status: 401,
});
expect(await gmail("watch", ada, { topicName: "gmail-push" })).toMatchObject({ status: 400 });
const watched = await gmail("watch", ada, { topicName: TOPIC });
const watch = (await watched!.json()) as { historyId: string; expiration: string };
expect(watch).toEqual({
historyId: expect.stringMatching(/^\d+$/),
expiration: expect.stringMatching(/^\d+$/),
});
// Gmail ends a watch a week after it was last asked for
const days = (Number(watch.expiration) - Date.now()) / (24 * 60 * 60_000);
expect(Math.round(days)).toBe(7);
// THE PUSH: Pub/Sub's envelope around Gmail's notification, to the subscription's address
const fired = await push({ email: "Ada@Petshop.test", url: SUBSCRIBER });
expect(fired).toMatchObject({
status: 200,
body: { email: "ada@petshop.test", topicName: TOPIC, status: 200, body: { accepted: true } },
});
expect(pushes).toHaveLength(1);
const [sent] = pushes;
expect([sent!.method, sent!.url]).toEqual(["POST", SUBSCRIBER]);
const envelope = (await sent!.json()) as {
message: { data: string; messageId: string; publishTime: string };
subscription: string;
};
expect(envelope).toMatchObject({
message: { messageId: fired.body.messageId },
subscription: "projects/petshop/subscriptions/gmail-push",
});
expect(new Date(envelope.message.publishTime).getTime()).toBeGreaterThan(0);
// the mailbox moved on from the history id its watch answered
const notification = JSON.parse(atob(envelope.message.data));
expect(notification).toEqual({
emailAddress: "ada@petshop.test",
historyId: Number(watch.historyId) + 1,
});
// THE TOKEN is the subscription's: signed by the shop, for the address the push went to (or the
// audience the control names), in the name of the subscription's service account
const bearer = sent!.headers.get("authorization")!.replace(/^Bearer /, "");
expect(await claimsOf(petshop, bearer)).toMatchObject({
iss: ORIGIN,
aud: SUBSCRIBER,
email: GMAIL_PUSH_SERVICE_ACCOUNT,
email_verified: true,
});
// a subscription that somebody else made: the control signs for whatever it is told
await push({
email: "ada@petshop.test",
url: SUBSCRIBER,
audience: "https://elsewhere.test",
serviceAccount: "push@another-project.iam.gserviceaccount.com",
});
const others = pushes[1]!.headers.get("authorization")!.replace(/^Bearer /, "");
expect(await claimsOf(petshop, others)).toMatchObject({
aud: "https://elsewhere.test",
email: "push@another-project.iam.gserviceaccount.com",
});
// the account's profile names the mailbox's newest history id
const profile = await petshop.handle(
new Request(`${ORIGIN}/gmail/v1/users/me/profile`, {
headers: { authorization: `Bearer ${ada}` },
}),
);
expect(await profile!.json()).toMatchObject({
emailAddress: "ada@petshop.test",
historyId: String(Number(watch.historyId) + 2),
});
// a watch that nobody renewed for a week is over, and a stopped one too
vi.useFakeTimers({ now: Date.now() + 8 * 24 * 60 * 60_000, toFake: ["Date"] });
expect(await push({ email: "ada@petshop.test", url: SUBSCRIBER })).toMatchObject({
status: 409,
});
// the account's token of a week ago is over too
const later = await accessTokenOf(petshop, "ada@petshop.test");
await gmail("watch", later, { topicName: TOPIC });
expect(await push({ email: "ada@petshop.test", url: SUBSCRIBER })).toMatchObject({
status: 200,
});
expect(await gmail("stop", later)).toMatchObject({ status: 204 });
expect(await push({ email: "ada@petshop.test", url: SUBSCRIBER })).toMatchObject({
status: 409,
});
expect(pushes).toHaveLength(3);
});
test("a pushed change is one message of the mailbox, which its history lists once and Gmail's message route answers", 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");
const bo = await accessTokenOf(petshop, "bo@petshop.test");
/** One GET of Gmail's API as `token`'s account: its status and JSON. */
const gmail = async (path: string, token = ada) => {
const answer = await petshop.handle(
new Request(`${ORIGIN}/gmail/v1/users/me/${path}`, {
headers: { authorization: `Bearer ${token}` },
}),
);
return { status: answer!.status, body: (await answer!.json()) as Record<string, any> };
};
const control = async (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> };
};
const push = (message?: Record<string, unknown>) =>
control("gmail-push", { email: "ada@petshop.test", url: SUBSCRIBER, message });
const watched = await petshop.handle(
new Request(`${ORIGIN}/gmail/v1/users/me/watch`, {
method: "POST",
headers: { authorization: `Bearer ${ada}` },
body: JSON.stringify({ topicName: TOPIC }),
}),
);
const { historyId: start } = (await watched!.json()) as { historyId: string };
// nothing came since the watch: Gmail answers the mailbox's history id and no record
expect(await gmail(`history?startHistoryId=${start}`)).toEqual({
status: 200,
body: { historyId: start },
});
const first = await push({
from: "Grace <grace@petshop.test>",
subject: "Friday",
snippet: "Shall we meet on Friday?",
});
const second = await push();
expect(first).toMatchObject({
status: 200,
body: { historyId: String(Number(start) + 1), gmailMessageId: expect.stringMatching(/^\w+$/) },
});
const [m1, m2] = [first.body.gmailMessageId, second.body.gmailMessageId] as [string, string];
expect(m2).not.toBe(m1);
// THE HISTORY since the watch: one record for each message, oldest first, with the message's
// ids and labels and no more (Gmail's `users.history.list`)
const history = await gmail(`history?startHistoryId=${start}&historyTypes=messageAdded`);
expect(history).toEqual({
status: 200,
body: {
history: [
{
id: String(Number(start) + 1),
messagesAdded: [{ message: { id: m1, threadId: m1, labelIds: ["INBOX", "UNREAD"] } }],
},
{
id: String(Number(start) + 2),
messagesAdded: [{ message: { id: m2, threadId: m2, labelIds: ["INBOX", "UNREAD"] } }],
},
],
historyId: String(Number(start) + 2),
},
});
// from a later place there is less, and a kind of change the fake never makes lists nothing
expect(
(await gmail(`history?startHistoryId=${Number(start) + 1}`)).body.history.map(
(record: { id: string }) => record.id,
),
).toEqual([String(Number(start) + 2)]);
expect(await gmail(`history?startHistoryId=${start}&historyTypes=labelAdded`)).toMatchObject({
body: { historyId: String(Number(start) + 2) },
});
// a page at a time
const page = await gmail(`history?startHistoryId=${start}&maxResults=1`);
expect(page.body).toMatchObject({
history: [{ id: String(Number(start) + 1) }],
nextPageToken: expect.any(String),
});
const next = await gmail(
`history?startHistoryId=${start}&maxResults=1&pageToken=${page.body.nextPageToken}`,
);
expect(next.body.history).toMatchObject([{ id: String(Number(start) + 2) }]);
expect(next.body).not.toHaveProperty("nextPageToken");
// THE MESSAGE, as Gmail's `users.messages.get` answers its metadata: only the headers asked for
expect(
await gmail(`messages/${m1}?format=metadata&metadataHeaders=From&metadataHeaders=subject`),
).toEqual({
status: 200,
body: {
id: m1,
threadId: m1,
labelIds: ["INBOX", "UNREAD"],
snippet: "Shall we meet on Friday?",
internalDate: expect.stringMatching(/^\d+$/),
historyId: String(Number(start) + 1),
payload: {
headers: [
{ name: "From", value: "Grace <grace@petshop.test>" },
{ name: "Subject", value: "Friday" },
],
},
},
});
// with no header named, all five; the default mail is one to the mailbox
const whole = await gmail(`messages/${m2}`);
expect(whole.body.payload.headers.map((header: { name: string }) => header.name)).toEqual([
"From",
"To",
"Subject",
"Date",
"Message-ID",
]);
expect(whole.body.payload.headers[1]).toEqual({ name: "To", value: "ada@petshop.test" });
expect(await gmail("messages/no-such-message")).toMatchObject({
status: 404,
body: { error: { code: 404 } },
});
// a mailbox is its account's own: another account's token reads none of it, and no token none
expect(await gmail(`history?startHistoryId=${start}`, bo)).toMatchObject({
status: 200,
body: { historyId: "1" },
});
expect(await gmail(`messages/${m1}`, bo)).toMatchObject({ status: 404 });
expect(await gmail(`history?startHistoryId=${start}`, "no token")).toMatchObject({ status: 401 });
expect(await gmail("history")).toMatchObject({ status: 400 });
// THE FAKE KEEPS THE NEWEST FIFTY RECORDS. A place before them is gone, as at Gmail: 404.
for (let n = 0; n < 50; n += 1) await push();
expect(await gmail(`history?startHistoryId=${start}`)).toMatchObject({
status: 404,
body: { error: { code: 404, status: "NOT_FOUND" } },
});
const kept = await gmail(`history?startHistoryId=${Number(start) + 2}&maxResults=500`);
expect(kept.body.history).toHaveLength(50);
expect(await gmail(`messages/${m1}`)).toMatchObject({ status: 404 });
// a test makes the whole history gone: every earlier place answers 404, the newest answers
const forgotten = await control("gmail-forget-history", { email: "ada@petshop.test" });
expect(forgotten).toEqual({
status: 200,
body: { email: "ada@petshop.test", historyId: String(Number(start) + 52) },
});
expect(await gmail(`history?startHistoryId=${Number(start) + 51}`)).toMatchObject({
status: 404,
});
expect(await gmail(`history?startHistoryId=${Number(start) + 52}`)).toEqual({
status: 200,
body: { historyId: String(Number(start) + 52) },
});
expect(await control("gmail-forget-history", {})).toMatchObject({ status: 400 });
});
const REDIRECT_URI = "https://app.test/callback";
/** `email` consents at the Google fake for the seeded client, whose code is exchanged: its
* access token. */
async function accessTokenOf(petshop: ReturnType<typeof memoryPetshop>, email: string) {
const authorize = new URL("/o/oauth2/v2/auth", ORIGIN);
authorize.search = new URLSearchParams({
client_id: DEFAULT_CLIENT_ID,
redirect_uri: REDIRECT_URI,
email,
}).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;
}
/** The claims of `token`, once the key that the shop's certs address publishes verified it. */
async function claimsOf(petshop: ReturnType<typeof memoryPetshop>, token: string) {
const certs = await petshop.handle(new Request(`${ORIGIN}/oauth2/v3/certs`));
const { keys } = (await certs!.json()) as { keys: (JsonWebKey & { kid: string })[] };
const [header, payload, signature] = token.split(".") as [string, string, string];
const { kid } = JSON.parse(Buffer.from(header, "base64url").toString()) as { kid: string };
const key = await crypto.subtle.importKey(
"jwk",
keys.find((each) => each.kid === kid)!,
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
false,
["verify"],
);
const verified = await crypto.subtle.verify(
"RSASSA-PKCS1-v1_5",
key,
Buffer.from(signature, "base64url"),
new TextEncoder().encode(`${header}.${payload}`),
);
if (!verified) throw new Error("the shop's certs do not verify this token");
return JSON.parse(Buffer.from(payload, "base64url").toString()) as Record<string, unknown>;
}