diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index 2d9d5d17..5811f0d6 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -1,4 +1,5 @@ import { clearGoogleCookie, finishGooglePassword, finishGoogleSignIn, googleEnabled, googlePending, googleUsernameAvailable, redeemGoogleCallback, requestGoogleEmail, startGoogleSignIn, verifyGoogleEmail, type GoogleIdentity } from "./google-sign-in"; +import { GoogleCallbackFailure, reportGoogleCallbackFailure } from "./google-callback-diagnostics"; import { usernameSchema } from "./usernames"; import { integrationConsentLabels } from "./agent-api"; import { ACCESS_SCOPES } from "./access-tokens"; @@ -288,19 +289,26 @@ export async function googleSignInCallback(request: Request, env: Env) { const redirect = (target: string) => new Response(null, { status: 303, headers: { Location: new URL(target, env.APP_ORIGIN).href, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", } }); - if (request.headers.has("Authorization")) return redirect("/auth/login?google=failed"); + if (request.headers.has("Authorization")) { + reportGoogleCallbackFailure(request, "authorization_header"); + return redirect("/auth/login?google=failed"); + } try { const result = await redeemGoogleCallback(request, env); if ("status" in result) return redirect(result.status === 409 ? "/auth/login?google=collision" : result.status === 403 ? "/auth/login?google=account" : "/auth/login?google=failed"); if ("pending" in result) return redirect("/auth/google"); const signed = await completeInteractiveSignIn(request, env, result.identity, result.returnTo, result.connection); - if (!signed.ok) return redirect("/auth/login?google=connection"); + if (!signed.ok) { + reportGoogleCallbackFailure(request, "connection_unavailable"); + return redirect("/auth/login?google=connection"); + } const { returnTo } = loginSuccess.parse(await signed.json()); const response = redirect(returnTo); response.headers.append("Set-Cookie", signed.headers.get("Set-Cookie")!); response.headers.append("Set-Cookie", clearGoogleCookie(env)); return response; - } catch { + } catch (error) { + reportGoogleCallbackFailure(request, error instanceof GoogleCallbackFailure ? error.code : "session_completion"); // Never reflect provider errors, authorization codes, or token data. return redirect("/auth/login?google=failed"); } diff --git a/packages/api/src/google-callback-diagnostics.ts b/packages/api/src/google-callback-diagnostics.ts new file mode 100644 index 00000000..2c449fd0 --- /dev/null +++ b/packages/api/src/google-callback-diagnostics.ts @@ -0,0 +1,40 @@ +type FailureCode = + | "authorization_header" + | "callback_input" + | "provider_denied" + | "attempt_unavailable" + | "attempt_store" + | "token_transport" + | "token_rejected" + | "token_invalid_client" + | "token_invalid_grant" + | "token_response" + | "id_token_shape" + | "id_token_claims" + | "google_signing_key" + | "id_token_signature" + | "account_store" + | "account_unavailable" + | "account_collision" + | "connection_unavailable" + | "session_completion"; + +export class GoogleCallbackFailure extends Error { + constructor(readonly code: FailureCode) { super(code); } +} + +/** Replace exceptions from a stage with a fixed code, never forwarding their contents. */ +export async function googleCallbackStage(code: FailureCode, run: () => T | Promise): Promise { + try { return await run(); } + catch (error) { + if (error instanceof GoogleCallbackFailure) throw error; + throw new GoogleCallbackFailure(code); + } +} + +/** Do not log request URLs, provider response bodies, exceptions, or identity data. */ +export function reportGoogleCallbackFailure(request: Request, code: FailureCode) { + const ray = request.headers.get("CF-Ray"); + const rayId = ray && /^[0-9a-fA-F]{16}(?:-[A-Z]{3})?$/.test(ray) ? ray : undefined; + console.warn("factorize.google_callback_failed", { code, ...(rayId ? { rayId } : {}) }); +} diff --git a/packages/api/src/google-sign-in.ts b/packages/api/src/google-sign-in.ts index 9e9b5cde..b63008d8 100644 --- a/packages/api/src/google-sign-in.ts +++ b/packages/api/src/google-sign-in.ts @@ -1,3 +1,4 @@ +import { GoogleCallbackFailure, googleCallbackStage, reportGoogleCallbackFailure } from "./google-callback-diagnostics"; import { serialize } from "hono/utils/cookie"; import { z } from "zod"; import { hashPassword, normalizeEmail, tokenDigest, verifyPassword } from "./auth"; @@ -70,7 +71,9 @@ const jwtClaims = z.object({ iat: z.number().int(), nbf: z.number().int().optional(), email: z.string().email().max(320), - email_verified: z.literal(true), + // Google documents Boolean true, but its signed-token example for the + // authorization-code flow also shows the exact JSON string "true". + email_verified: z.union([z.literal(true), z.literal("true")]), hd: z.string().min(1).max(253).optional(), }); function decodePart(input: string) { @@ -79,30 +82,41 @@ function decodePart(input: string) { return Uint8Array.from(atob(padded), char => char.charCodeAt(0)); } async function exchangeGoogleCode(env: Env, attempt: Attempt, code: string) { - const token = await fetch(tokenUrl, { + const token = await googleCallbackStage("token_transport", () => fetch(tokenUrl, { method: "POST", redirect: "error", signal: AbortSignal.timeout(10_000), body: new URLSearchParams({ grant_type: "authorization_code", code, client_id: env.GOOGLE_SIGN_IN_CLIENT_ID!, client_secret: env.GOOGLE_SIGN_IN_CLIENT_SECRET!, redirect_uri: redirectUri(env), code_verifier: attempt.verifier!, }), + })); + if (!token.ok) { + const { error } = await token.json().then(value => z.object({ error: z.unknown().optional() }).parse(value)).catch(() => ({ error: undefined })); + throw new GoogleCallbackFailure(error === "invalid_client" ? "token_invalid_client" : error === "invalid_grant" ? "token_invalid_grant" : "token_rejected"); + } + const { id_token } = await googleCallbackStage("token_response", async () => z.object({ id_token: z.string().min(1).max(16384) }).parse(await token.json())); + const { header, claims, parts } = await googleCallbackStage("id_token_shape", () => { + const parts = id_token.split("."); + if (parts.length !== 3) throw new Error("Invalid Google identity token."); + const decoder = new TextDecoder("utf-8", { fatal: true }); + return { + header: jwtHeader.parse(JSON.parse(decoder.decode(decodePart(parts[0])))), + claims: jwtClaims.parse(JSON.parse(decoder.decode(decodePart(parts[1])))), + parts, + }; }); - if (!token.ok) throw new Error("Google sign-in was not verified."); - const { id_token } = z.object({ id_token: z.string().min(1).max(16384) }).parse(await token.json()); - const parts = id_token.split("."); - if (parts.length !== 3) throw new Error("Invalid Google identity token."); - const decoder = new TextDecoder("utf-8", { fatal: true }); - const header = jwtHeader.parse(JSON.parse(decoder.decode(decodePart(parts[0])))); - const claims = jwtClaims.parse(JSON.parse(decoder.decode(decodePart(parts[1])))); const now = Math.floor(Date.now() / 1000); if (claims.aud !== env.GOOGLE_SIGN_IN_CLIENT_ID || (claims.azp && claims.azp !== claims.aud) || claims.nonce !== attempt.nonce || - claims.exp <= now || claims.exp <= claims.iat || claims.iat > now + 30 || claims.iat < now - maxAge || (claims.nbf ?? 0) > now + 30) throw new Error("Invalid Google sign-in claims."); - const resolveKey = createJwksResolver({ jwksUri }); - const jwk = await resolveKey(header.kid, false); - if (jwk?.kty !== "RSA" || (jwk.alg && jwk.alg !== "RS256")) throw new Error("Google signing key unavailable."); - const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]); - if (!await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, decodePart(parts[2]), encoder.encode(parts[0] + "." + parts[1]))) { - throw new Error("Google identity signature invalid."); + claims.exp <= now || claims.exp <= claims.iat || claims.iat > now + 30 || claims.iat < now - maxAge || (claims.nbf ?? 0) > now + 30) { + throw new GoogleCallbackFailure("id_token_claims"); } + const key = await googleCallbackStage("google_signing_key", async () => { + const jwk = await createJwksResolver({ jwksUri })(header.kid, false); + if (jwk?.kty !== "RSA" || (jwk.alg && jwk.alg !== "RS256")) throw new Error("Google signing key unavailable."); + return crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]); + }); + const validSignature = await googleCallbackStage("id_token_signature", () => + crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, decodePart(parts[2]), encoder.encode(parts[0] + "." + parts[1]))); + if (!validSignature) throw new GoogleCallbackFailure("id_token_signature"); const email = normalizeEmail(claims.email); return { subject: claims.sub, email, authoritativeEmail: email.endsWith("@gmail.com") || !!claims.hd, issuedAt: claims.iat }; } @@ -170,25 +184,34 @@ async function syncGoogleRecovery(sql: DatabaseClient, userId: string, google: { } export async function redeemGoogleCallback(request: Request, env: Env) { + const result = await redeemGoogleCallbackAttempt(request, env); + if ("status" in result) { + reportGoogleCallbackFailure(request, result.status === 409 ? "account_collision" : result.status === 403 ? "account_unavailable" : "attempt_unavailable"); + } + return result; +} + +async function redeemGoogleCallbackAttempt(request: Request, env: Env) { const parsed = new URL(request.url); const state = z.uuid().safeParse(parsed.searchParams.get("state")); const code = parsed.searchParams.get("code"); const digest = await digestFor(request, env); - if (!googleEnabled(env) || !state.success || !code || code.length > 4096 || !digest || parsed.searchParams.has("error")) return expired(); + if (parsed.searchParams.has("error")) throw new GoogleCallbackFailure("provider_denied"); + if (!googleEnabled(env) || !state.success || !code || code.length > 4096 || !digest) throw new GoogleCallbackFailure("callback_input"); const db = databaseFor(env); - const attempt = await db.transaction(async sql => { + const attempt = await googleCallbackStage("attempt_store", () => db.transaction(async sql => { const row = (await sql.query(`SELECT * FROM app.google_sign_in_attempts WHERE id=$1 AND browser_digest=$2 AND verifier IS NOT NULL AND expires_at>clock_timestamp() FOR UPDATE`, [state.data, digest])).rows[0]; if (row) await sql.query("UPDATE app.google_sign_in_attempts SET verifier=NULL WHERE id=$1", [row.id]); return row; - }); - if (!attempt) return expired(); + })); + if (!attempt) throw new GoogleCallbackFailure("attempt_unavailable"); const google = await exchangeGoogleCode(env, attempt, code); - const linked = (await db.pool.query<{ user_id: string }>(`SELECT user_id FROM app.auth_accounts - WHERE provider='google' AND provider_account_id=$1`, [google.subject])).rows[0]; + const linked = (await googleCallbackStage("account_store", () => db.pool.query<{ user_id: string }>(`SELECT user_id FROM app.auth_accounts + WHERE provider='google' AND provider_account_id=$1`, [google.subject]))).rows[0]; if (attempt.password_user_id && linked?.user_id !== attempt.password_user_id) return fail(403, "Use the Google account linked to your Factorize account."); if (linked) { - return db.transaction(async sql => { + return googleCallbackStage("account_store", () => db.transaction(async sql => { // Lock attempt before user, consistent with both password setup and linking. const active = (await sql.query("SELECT id FROM app.google_sign_in_attempts WHERE id=$1 AND expires_at>clock_timestamp() FOR UPDATE", [attempt.id])).rows.length; if (!active) return expired(); @@ -203,12 +226,14 @@ export async function redeemGoogleCallback(request: Request, env: Env) { } await sql.query("DELETE FROM app.google_sign_in_attempts WHERE id=$1", [attempt.id]); return { identity, returnTo: attempt.return_to, connection: attempt.connection_id ?? undefined }; - }); + })); } - const existing = (await db.pool.query<{ id: string }>("SELECT id FROM app.auth_users WHERE lower(email)=$1", [google.email])).rows[0]; - const updated = await db.pool.query(`UPDATE app.google_sign_in_attempts SET google_subject=$2,email=$3,existing_user_id=$4,email_confirmed=$5,provider_managed_email=$5,provider_observed_at=$6 - WHERE id=$1 AND expires_at>clock_timestamp() RETURNING id`, [attempt.id, google.subject, google.email, existing?.id ?? null, google.authoritativeEmail, google.issuedAt]); - return updated.rowCount ? { pending: true as const } : expired(); + return googleCallbackStage("account_store", async () => { + const existing = (await db.pool.query<{ id: string }>("SELECT id FROM app.auth_users WHERE lower(email)=$1", [google.email])).rows[0]; + const updated = await db.pool.query(`UPDATE app.google_sign_in_attempts SET google_subject=$2,email=$3,existing_user_id=$4,email_confirmed=$5,provider_managed_email=$5,provider_observed_at=$6 + WHERE id=$1 AND expires_at>clock_timestamp() RETURNING id`, [attempt.id, google.subject, google.email, existing?.id ?? null, google.authoritativeEmail, google.issuedAt]); + return updated.rowCount ? { pending: true as const } : expired(); + }); } async function pendingAttempt(db: DatabaseClient, digest: string, lock = false) { diff --git a/packages/api/test/google-callback-diagnostics.test.ts b/packages/api/test/google-callback-diagnostics.test.ts new file mode 100644 index 00000000..8b9c7d69 --- /dev/null +++ b/packages/api/test/google-callback-diagnostics.test.ts @@ -0,0 +1,91 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { googleSignInCallback } from "../src/auth-api"; +import type { Env } from "../src/types"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const origin = "https://factorize.test"; +const endpoint = origin + "/oauth/google/sign-in/callback"; +const ray = "1234567890abcdef-YYZ"; +const state = "90bb650a-cd15-4091-be4a-52b080819115"; +const nonce = "test-nonce"; +const clientId = "test-client-id"; + +function callback(headers: Record = { "CF-Ray": ray }) { + return new Request(endpoint + "?" + new URLSearchParams({ state, code: "private-fixture-code" }), { + headers: { Cookie: "__Host-factorize_google_attempt=" + "a".repeat(43), ...headers }, + }); +} + +function environment(attempt: boolean) { + const query = vi.fn(async (text: string) => { + if (text.startsWith("SELECT * FROM app.google_sign_in_attempts")) { + return { rows: attempt ? [{ id: state, nonce, verifier: "private-fixture-verifier" }] : [] }; + } + return { rows: [], rowCount: 1 }; + }); + return { + APP_ORIGIN: origin, SESSION_SIGNING_SECRET: "test-only-secret", GOOGLE_SIGN_IN_CLIENT_ID: clientId, + GOOGLE_SIGN_IN_CLIENT_SECRET: "private-fixture-client-secret", + DATABASE: { pool: { query }, transaction: async (run: (sql: { query: typeof query }) => T) => run({ query }) }, + } as unknown as Env; +} + +async function fixtureToken(emailVerified: unknown) { + const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); + const key = await crypto.subtle.exportKey("jwk", pair.publicKey); + const now = Math.floor(Date.now() / 1000); + const payload = { iss: "https://accounts.google.com", aud: clientId, sub: "private-fixture-subject", nonce, + iat: now, exp: now + 3600, email: "fixture@gmail.com", email_verified: emailVerified }; + const part = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); + const signingInput = part({ alg: "RS256", kid: "fixture-key" }) + "." + part(payload); + const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(signingInput)); + return { token: signingInput + "." + Buffer.from(signature).toString("base64url"), key }; +} + +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + +describe("Google callback compatibility and diagnostics", () => { + it.each([true, "true"])("continues for the exact signed email verification value %j", async emailVerified => { + const { token, key } = await fixtureToken(emailVerified); + const diagnostics = vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.stubGlobal("fetch", async (url: string) => { + if (url === "https://oauth2.googleapis.com/token") return Response.json({ id_token: token }); + if (url === "https://www.googleapis.com/oauth2/v3/certs") return Response.json({ keys: [{ ...key, kid: "fixture-key" }] }); + throw new Error("Unexpected fixture outbound request"); + }); + const response = await googleSignInCallback(callback(), environment(true)); + expect(response.status).toBe(303); + expect(response.headers.get("Location")).toBe(origin + "/auth/google"); + expect(diagnostics).not.toHaveBeenCalled(); + }); + + it.each([false, "false", "TRUE", 1])("rejects signed unverified or noncanonical email value %j", async emailVerified => { + const { token } = await fixtureToken(emailVerified); + const diagnostics = vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.stubGlobal("fetch", async () => Response.json({ id_token: token })); + const response = await googleSignInCallback(callback(), environment(true)); + expect(response.headers.get("Location")).toBe(origin + "/auth/login?google=failed"); + expect(diagnostics).toHaveBeenCalledExactlyOnceWith("factorize.google_callback_failed", { code: "id_token_shape", rayId: ray }); + }); + + it("distinguishes an unavailable attempt without retaining arbitrary correlation headers", async () => { + const diagnostics = vi.spyOn(console, "warn").mockImplementation(() => {}); + const noNetwork = vi.fn(); + vi.stubGlobal("fetch", noNetwork); + const response = await googleSignInCallback(callback({ "CF-Ray": "arbitrary-sensitive-value" }), environment(false)); + expect(response.headers.get("Location")).toBe(origin + "/auth/login?google=failed"); + expect(diagnostics).toHaveBeenCalledExactlyOnceWith("factorize.google_callback_failed", { code: "attempt_unavailable" }); + expect(noNetwork).not.toHaveBeenCalled(); + }); + + it("records only an allowlisted exchange rejection and Ray ID, without changing the public error", async () => { + const diagnostics = vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.stubGlobal("fetch", async () => Response.json({ error: "invalid_client", error_description: "private-fixture-provider-detail" }, { status: 401 })); + const response = await googleSignInCallback(callback(), environment(true)); + expect(response.headers.get("Location")).toBe(origin + "/auth/login?google=failed"); + expect(diagnostics).toHaveBeenCalledExactlyOnceWith("factorize.google_callback_failed", { code: "token_invalid_client", rayId: ray }); + expect(JSON.stringify(diagnostics.mock.calls)).not.toContain("private-fixture-"); + }); +});