import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { GMAIL_SCOPES, GmailError, buildGmailAuthorizationUrl, exchangeGmailCodeForTokens, getMessage, listHistory, listMessageIds, modifyMessageLabels, refreshGmailAccessToken, resolveGmailOAuthConfig, revokeGmailToken, sendRawMessage, watchMailbox, } from "./gmailApi.js"; // VA-P23 — Gmail client unit tests. All network I/O is mocked; these pin the // request shapes (endpoints, params, bodies) and the Klartext error mapping. const CONFIG = { clientId: "cid", clientSecret: "csecret", redirectUri: "https://app.hivegrid.de/integrations/email/google/oauth/callback", pubsubTopic: "projects/hg/topics/hivegrid-gmail-sync", }; function jsonResponse(status: number, body: unknown): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); } let fetchMock: ReturnType; beforeEach(() => { fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock); }); afterEach(() => { vi.unstubAllGlobals(); }); describe("resolveGmailOAuthConfig", () => { it("returns null when any env key is missing", () => { expect(resolveGmailOAuthConfig({})).toBeNull(); expect(resolveGmailOAuthConfig({ GOOGLE_GMAIL_CLIENT_ID: "x" })).toBeNull(); }); it("resolves the full config incl. the Pub/Sub topic", () => { const env = { GOOGLE_GMAIL_CLIENT_ID: "cid", GOOGLE_GMAIL_CLIENT_SECRET: "cs", GOOGLE_GMAIL_REDIRECT_URI: "https://app.hivegrid.de/cb", GOOGLE_GMAIL_PUBSUB_TOPIC: "projects/p/topics/t", }; expect(resolveGmailOAuthConfig(env)).toEqual({ clientId: "cid", clientSecret: "cs", redirectUri: "https://app.hivegrid.de/cb", pubsubTopic: "projects/p/topics/t", }); }); }); describe("buildGmailAuthorizationUrl", () => { it("requests offline access with the restricted Gmail scopes and state", () => { const url = new URL(buildGmailAuthorizationUrl(CONFIG, "signed-state")); expect(url.origin + url.pathname).toBe("https://accounts.google.com/o/oauth2/v2/auth"); expect(url.searchParams.get("scope")).toBe(GMAIL_SCOPES.join(" ")); expect(url.searchParams.get("access_type")).toBe("offline"); expect(url.searchParams.get("state")).toBe("signed-state"); expect(url.searchParams.get("redirect_uri")).toBe(CONFIG.redirectUri); }); }); describe("token exchange + refresh", () => { it("exchanges the code and parses the token set", async () => { fetchMock.mockResolvedValueOnce( jsonResponse(200, { access_token: "at", refresh_token: "rt", expires_in: 3600, scope: "a b" }), ); const tokens = await exchangeGmailCodeForTokens(CONFIG, "the-code"); expect(tokens.accessToken).toBe("at"); expect(tokens.refreshToken).toBe("rt"); expect(tokens.scopes).toEqual(["a", "b"]); const [url, init] = fetchMock.mock.calls[0]; expect(url).toBe("https://oauth2.googleapis.com/token"); expect(String(init.body)).toContain("grant_type=authorization_code"); }); it("keeps the previous refresh token when Google omits it on refresh", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, { access_token: "at2", expires_in: 3600 })); const tokens = await refreshGmailAccessToken(CONFIG, "old-rt"); expect(tokens.refreshToken).toBe("old-rt"); }); it("maps invalid_grant to auth_token_expired", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(400, { error: "invalid_grant" })); await expect(refreshGmailAccessToken(CONFIG, "dead")).rejects.toMatchObject({ name: "GmailError", code: "auth_token_expired", }); }); it("treats an already-revoked token as idempotent success on revoke", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(400, {})); await expect(revokeGmailToken("gone")).resolves.toBeUndefined(); }); }); describe("watchMailbox", () => { it("subscribes INBOX+SENT to the shared Pub/Sub topic and parses expiry", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, { historyId: "100", expiration: "1750000000000" })); const watch = await watchMailbox("at", CONFIG.pubsubTopic); expect(watch.historyId).toBe("100"); expect(watch.expiresAt).toEqual(new Date(1750000000000)); const [url, init] = fetchMock.mock.calls[0]; expect(url).toContain("/gmail/v1/users/me/watch"); expect(JSON.parse(String(init.body))).toMatchObject({ topicName: CONFIG.pubsubTopic, labelIds: ["INBOX", "SENT"] }); }); it("maps a failed watch to watch_subscription_failed", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(403, {})); await expect(watchMailbox("at", CONFIG.pubsubTopic)).rejects.toMatchObject({ code: "watch_subscription_failed" }); }); }); describe("listHistory", () => { it("dedupes added message ids across history entries", async () => { fetchMock.mockResolvedValueOnce( jsonResponse(200, { history: [ { messagesAdded: [{ message: { id: "m1" } }, { message: { id: "m2" } }] }, { messagesAdded: [{ message: { id: "m2" } }] }, ], historyId: "222", }), ); const page = await listHistory("at", "100"); expect(page.addedMessageIds).toEqual(["m1", "m2"]); expect(page.historyId).toBe("222"); }); it("marks an expired historyId (404) as fullResyncRequired", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(404, {})); const error = await listHistory("at", "1").catch((e: unknown) => e); expect(error).toBeInstanceOf(GmailError); expect((error as GmailError).code).toBe("history_expired"); expect((error as GmailError).fullResyncRequired).toBe(true); }); }); describe("messages", () => { it("lists message ids with the initial-sync query", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, { messages: [{ id: "a" }, { id: "b" }], nextPageToken: "npt" })); const page = await listMessageIds("at", { q: "newer_than:90d", maxResults: 50 }); expect(page.messageIds).toEqual(["a", "b"]); expect(page.nextPageToken).toBe("npt"); const [url] = fetchMock.mock.calls[0]; expect(String(url)).toContain("q=newer_than%3A90d"); expect(String(url)).toContain("maxResults=50"); }); it("fetches a message with the requested format", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, { id: "m1", threadId: "t1" })); const message = await getMessage("at", "m1", "metadata"); expect(message.threadId).toBe("t1"); expect(String(fetchMock.mock.calls[0][0])).toContain("format=metadata"); }); it("sends a raw message inside a thread", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, { id: "sent1", threadId: "t9" })); const result = await sendRawMessage("at", "cmF3", "t9"); expect(result).toEqual({ id: "sent1", threadId: "t9" }); expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ raw: "cmF3", threadId: "t9" }); }); it("modifies read state via label changes", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, {})); await modifyMessageLabels("at", "m1", { removeLabelIds: ["UNREAD"] }); expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ addLabelIds: [], removeLabelIds: ["UNREAD"] }); }); it("maps 429 to rate_limit_exceeded", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(429, {})); await expect(getMessage("at", "m1")).rejects.toMatchObject({ code: "rate_limit_exceeded" }); }); });