// @vitest-environment node import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ KwpConnectError: class KwpConnectError extends Error { readonly code: string; readonly diagnosticCode?: string; constructor(code: string, options?: { diagnosticCode?: string }) { super(code); this.name = "KwpConnectError"; this.code = code; this.diagnosticCode = options?.diagnosticCode; } }, ProviderOAuthCallbackAccessError: class ProviderOAuthCallbackAccessError extends Error { readonly failureCode: "session_mismatch" | "membership_inactive"; constructor(failureCode: "session_mismatch" | "membership_inactive") { super("Provider OAuth callback access denied"); this.name = "ProviderOAuthCallbackAccessError"; this.failureCode = failureCode; } }, context: { tenantId: "tenant-1", userId: "user-1", permissions: ["integrations.connect"], hasModule: true, }, loadIntegrationsContext: vi.fn(), requireIntegrationsPermission: vi.fn(), beginKwpOAuthConnection: vi.fn(), cancelKwpOAuthConnectionAttempt: vi.fn(), completeKwpOAuthConnection: vi.fn(), loadKwpMandantSelection: vi.fn(), finalizeKwpOAuthConnection: vi.fn(), consumeChallenge: vi.fn(), runAuthenticatedProviderOAuthCallback: vi.fn(), validateCSRFToken: vi.fn(), getUserInfo: vi.fn(), getMyTenants: vi.fn(), requireKwpIntegrationModule: vi.fn(), loggerWarn: vi.fn(), })); vi.mock("~/components/auth/AuthShell", () => ({ AuthShell: () => null })); vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: () => Promise.resolve({ t: (key: string) => key }), })); vi.mock("~/modules/kwp/services/KwpConnectionService.server", () => ({ KwpConnectError: mocks.KwpConnectError, beginKwpOAuthConnection: mocks.beginKwpOAuthConnection, cancelKwpOAuthConnectionAttempt: mocks.cancelKwpOAuthConnectionAttempt, completeKwpOAuthConnection: mocks.completeKwpOAuthConnection, loadKwpMandantSelection: mocks.loadKwpMandantSelection, finalizeKwpOAuthConnection: mocks.finalizeKwpOAuthConnection, })); vi.mock("~/modules/kwp/services/kwpOAuthChallenge.server", () => ({ consumeKwpOAuthChallenge: mocks.consumeChallenge, })); vi.mock("~/modules/kwp/routes/kwpAccess.server", () => ({ requireKwpIntegrationModule: mocks.requireKwpIntegrationModule, })); vi.mock("~/utils/integrations/integrationsAccess.server", () => ({ loadIntegrationsContext: mocks.loadIntegrationsContext, notFoundResponse: () => new Response("Not Found", { status: 404 }), requireIntegrationsPermission: mocks.requireIntegrationsPermission, })); vi.mock("~/utils/integrations/providerOAuthCallbackAccess.server", () => ({ ProviderOAuthCallbackAccessError: mocks.ProviderOAuthCallbackAccessError, runAuthenticatedProviderOAuthCallback: mocks.runAuthenticatedProviderOAuthCallback, })); vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken, getUserInfo: mocks.getUserInfo, })); vi.mock("~/utils/db/tenants.db.server", () => ({ getMyTenants: mocks.getMyTenants })); vi.mock("~/utils/logger.server", () => ({ createScopedLogger: () => ({ warn: mocks.loggerWarn }), })); import { loader as callbackLoader } from "./integrations.kwp.oauth.callback"; import { action as setupAction, loader as setupLoader } from "./integrations.kwp.setup"; const CHALLENGE = { tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", connectionId: "connection-1", connectionVersion: "2026-07-20T12:00:00.000Z", customerCode: "geerkens2", state: "a".repeat(64), nonce: "b".repeat(64), codeVerifier: "v".repeat(64), codeChallenge: "c".repeat(43), createdAt: 1_725_000_000_000, } as const; async function captureRejection(promise: Promise): Promise { try { await promise; } catch (error) { return error; } throw new Error("Expected promise to reject"); } beforeEach(() => { vi.clearAllMocks(); mocks.loadIntegrationsContext.mockResolvedValue(mocks.context); mocks.requireIntegrationsPermission.mockImplementation((context: unknown) => context); mocks.requireKwpIntegrationModule.mockImplementation(async (context: unknown) => context); mocks.beginKwpOAuthConnection.mockResolvedValue({ authorizationUrl: "https://id.kwp-online.de/realms/kwp-federated/protocol/openid-connect/auth?state=signed", setCookie: "__Host-hivegrid_kwp_oauth_challenge=signed; Secure; HttpOnly", }); mocks.cancelKwpOAuthConnectionAttempt.mockResolvedValue(undefined); mocks.completeKwpOAuthConnection.mockResolvedValue({ tenantId: "tenant-1", tenantSlug: "acme", connectionId: "connection-1", }); mocks.loadKwpMandantSelection.mockResolvedValue({ connectionId: "connection-1", customerCode: "geerkens2", version: "2026-07-20T12:01:00.000Z", mode: "available", options: [ { id: 1, code: "001", label: "Geerkens GmbH" }, { id: 2, code: "002", label: "Geerkens Service GmbH" }, ], }); mocks.finalizeKwpOAuthConnection.mockResolvedValue({ tenantId: "tenant-1", tenantSlug: "acme", connectionId: "connection-1", }); mocks.consumeChallenge.mockResolvedValue({ ok: true, payload: CHALLENGE, clearCookie: "__Host-hivegrid_kwp_oauth_challenge=; Max-Age=0; Secure; HttpOnly", }); mocks.runAuthenticatedProviderOAuthCallback.mockImplementation(async ({ callback }: { callback: () => Promise }) => callback()); mocks.validateCSRFToken.mockResolvedValue(undefined); mocks.getUserInfo.mockResolvedValue({ userId: "user-1" }); mocks.getMyTenants.mockResolvedValue([{ id: "tenant-1", name: "Acme", slug: "acme" }]); }); describe("KWP OAuth setup route", () => { it("starts only from a CSRF-protected POST and emits the host-only challenge cookie", async () => { const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "csrf-token", customerCode: "geerkens2" }), }); const response = await setupAction({ request } as never); expect(response.status).toBe(302); expect(response.headers.get("location")).toContain("https://id.kwp-online.de/realms/kwp-federated/"); expect(response.headers.get("set-cookie")).toContain("__Host-hivegrid_kwp_oauth_challenge="); expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() }); expect(mocks.loadIntegrationsContext).toHaveBeenCalledWith({ request, params: { tenant: "acme" }, requireModule: true, }); expect(mocks.requireIntegrationsPermission).toHaveBeenCalledWith(mocks.context, "integrations.connect"); expect(mocks.requireKwpIntegrationModule).toHaveBeenCalledWith(mocks.context); expect(mocks.runAuthenticatedProviderOAuthCallback).toHaveBeenCalledWith({ request, tenantId: "tenant-1", userId: "user-1", callback: expect.any(Function), }); expect(mocks.beginKwpOAuthConnection).toHaveBeenCalledWith({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "geerkens2", }); }); it("starts with the tenant fallback from the submitted form when the query string is absent", async () => { const request = new Request("https://app.example.test/integrations/kwp/setup", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "csrf-token", tenant: "acme", customerCode: "geerkens2", }), }); const response = await setupAction({ request } as never); expect(response.status).toBe(302); expect(response.headers.get("location")).toContain("https://id.kwp-online.de/realms/kwp-federated/"); expect(mocks.loadIntegrationsContext).toHaveBeenCalledWith({ request, params: { tenant: "acme" }, requireModule: true, }); expect(mocks.beginKwpOAuthConnection).toHaveBeenCalledWith( expect.objectContaining({ tenantSlug: "acme", customerCode: "geerkens2" }), ); }); it("rejects bad CSRF before tenant access and provider work", async () => { mocks.validateCSRFToken.mockRejectedValueOnce(new Error("invalid csrf")); const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "bad" }), }); await expect(setupAction({ request } as never)).rejects.toThrow("invalid csrf"); expect(mocks.loadIntegrationsContext).not.toHaveBeenCalled(); expect(mocks.beginKwpOAuthConnection).not.toHaveBeenCalled(); }); it("keeps setup GET read-only and offers tenant selection", async () => { const request = new Request("https://app.example.test/integrations/kwp/setup"); const response = await setupLoader({ request } as never); await expect(response.json()).resolves.toMatchObject({ title: "integrations.kwp.oauth.title | HiveGrid Test", vm: { status: "ready", data: { mode: "entry", authenticated: true, loginHref: "/login?redirectTo=%2Fintegrations%2Fkwp%2Fsetup", tenants: [ { id: "tenant-1", name: "Acme", slug: "acme", setupHref: "/integrations/kwp/setup?tenant=acme", }, ], feedback: null, }, }, }); expect(mocks.beginKwpOAuthConnection).not.toHaveBeenCalled(); }); it("offers only tenants with KWP connect access on the entry page", async () => { const deniedContext = { ...mocks.context, tenantId: "tenant-2", permissions: [] }; mocks.getMyTenants.mockResolvedValueOnce([ { id: "tenant-1", name: "Acme", slug: "acme" }, { id: "tenant-2", name: "Blocked", slug: "blocked" }, ]); mocks.loadIntegrationsContext.mockImplementation(async ({ params }: { params: { tenant: string } }) => params.tenant === "blocked" ? deniedContext : mocks.context ); mocks.requireIntegrationsPermission.mockImplementation((context: typeof mocks.context) => { if (context.tenantId === "tenant-2") { throw new CatalogError(foundationErrors.notFound, { permission: "integrations.connect" }); } return context; }); const request = new Request("https://app.example.test/integrations/kwp/setup"); const response = await setupLoader({ request } as never); await expect(response.json()).resolves.toMatchObject({ vm: { status: "ready", data: { mode: "entry", authenticated: true, tenants: [ { id: "tenant-1", name: "Acme", slug: "acme", setupHref: "/integrations/kwp/setup?tenant=acme", }, ], }, }, }); expect(mocks.requireKwpIntegrationModule).toHaveBeenCalledTimes(2); expect(mocks.requireIntegrationsPermission).toHaveBeenCalledTimes(2); expect(mocks.beginKwpOAuthConnection).not.toHaveBeenCalled(); }); it("does not hide unexpected entry access failures", async () => { mocks.requireKwpIntegrationModule.mockRejectedValueOnce(new Error("database unavailable")); const request = new Request("https://app.example.test/integrations/kwp/setup"); await expect(setupLoader({ request } as never)).rejects.toThrow("database unavailable"); }); it("returns a real 404 response for a denied direct setup GET", async () => { mocks.requireIntegrationsPermission.mockImplementationOnce(() => { throw new CatalogError(foundationErrors.notFound, { permission: "integrations.connect" }); }); const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme"); const error = await captureRejection(setupLoader({ request } as never)); expect(error).toBeInstanceOf(Response); expect((error as Response).status).toBe(404); expect(mocks.beginKwpOAuthConnection).not.toHaveBeenCalled(); }); it("loads the staged mandant selection without exposing credentials", async () => { const request = new Request( "https://app.example.test/integrations/kwp/setup?tenant=acme&connection=connection-1", ); const response = await setupLoader({ request } as never); const body = await response.json(); expect(body).toMatchObject({ title: "integrations.kwp.oauth.title | HiveGrid Test", vm: { status: "ready", data: { mode: "mandant", tenantSlug: "acme", settingsHref: "/acme/settings/integrations/kwp", connectionId: "connection-1", connectionVersion: "2026-07-20T12:01:00.000Z", customerCode: "geerkens2", discoveryMode: "available", mandants: [ { id: 1, code: "001", label: "Geerkens GmbH" }, { id: 2, code: "002", label: "Geerkens Service GmbH" }, ], feedback: null, }, }, }); expect(mocks.loadKwpMandantSelection).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1", }); expect(mocks.runAuthenticatedProviderOAuthCallback).toHaveBeenCalledWith({ request, tenantId: "tenant-1", userId: "user-1", callback: expect.any(Function), }); expect(JSON.stringify(body)).not.toMatch(/access[_-]?token|refresh[_-]?token|client[_-]?secret/i); }); it("confirms the selected mandant and activates the staged connection", async () => { const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "confirm-mandant", csrf: "csrf-token", connectionId: "connection-1", connectionVersion: "2026-07-20T12:01:00.000Z", selectionKind: "selected", mandantCode: "001", }), }); const response = await setupAction({ request } as never); expect(response.status).toBe(303); expect(response.headers.get("location")).toBe("/acme/settings/integrations/kwp?kwp=connected"); expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() }); expect(mocks.finalizeKwpOAuthConnection).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1", version: "2026-07-20T12:01:00.000Z", mandantBinding: { kind: "selected", code: "001" }, }); expect(mocks.runAuthenticatedProviderOAuthCallback).toHaveBeenCalledWith({ request, tenantId: "tenant-1", userId: "user-1", callback: expect.any(Function), }); }); it("supports an explicit no-mandant binding", async () => { const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "confirm-mandant", csrf: "csrf-token", connectionId: "connection-1", connectionVersion: "2026-07-20T12:01:00.000Z", selectionKind: "none", }), }); const response = await setupAction({ request } as never); expect(response.status).toBe(303); expect(mocks.finalizeKwpOAuthConnection).toHaveBeenCalledWith( expect.objectContaining({ mandantBinding: { kind: "none" } }), ); }); it("cancels the staged selection through a CSRF-protected POST and restores reconnect state", async () => { const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "cancel-mandant", csrf: "csrf-token", connectionId: "connection-1", connectionVersion: "2026-07-20T12:01:00.000Z", }), }); const response = await setupAction({ request } as never); expect(response.status).toBe(303); expect(response.headers.get("location")).toBe("/acme/settings/integrations/kwp"); expect(mocks.cancelKwpOAuthConnectionAttempt).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1", version: "2026-07-20T12:01:00.000Z", }); expect(mocks.finalizeKwpOAuthConnection).not.toHaveBeenCalled(); }); it("returns selection errors to the staged connection without activating it", async () => { mocks.finalizeKwpOAuthConnection.mockRejectedValueOnce(new mocks.KwpConnectError("invalid_selection")); const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "confirm-mandant", csrf: "csrf-token", connectionId: "connection-1", connectionVersion: "2026-07-20T12:01:00.000Z", selectionKind: "selected", mandantCode: "999", }), }); const response = await setupAction({ request } as never); expect(response.status).toBe(303); expect(response.headers.get("location")).toBe( "/integrations/kwp/setup?tenant=acme&connection=connection-1&kwp=selection-error", ); }); it("restarts setup when the staged selection has expired", async () => { mocks.finalizeKwpOAuthConnection.mockRejectedValueOnce(new mocks.KwpConnectError("selection_expired")); const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "confirm-mandant", csrf: "csrf-token", connectionId: "connection-1", connectionVersion: "2026-07-20T12:01:00.000Z", selectionKind: "selected", mandantCode: "001", }), }); const response = await setupAction({ request } as never); expect(response.status).toBe(303); expect(response.headers.get("location")).toBe( "/integrations/kwp/setup?tenant=acme&kwp=selection-expired", ); }); it("restarts setup when loading a staged selection reports expiry", async () => { mocks.loadKwpMandantSelection.mockRejectedValueOnce(new mocks.KwpConnectError("selection_expired")); const request = new Request( "https://app.example.test/integrations/kwp/setup?tenant=acme&connection=connection-1", ); const response = await setupLoader({ request } as never); expect(response.status).toBe(303); expect(response.headers.get("location")).toBe( "/integrations/kwp/setup?tenant=acme&kwp=selection-expired", ); }); it("returns a real 404 response for a denied setup POST before OAuth starts", async () => { mocks.requireIntegrationsPermission.mockImplementationOnce(() => { throw new CatalogError(foundationErrors.notFound, { permission: "integrations.connect" }); }); const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "csrf-token" }), }); const error = await captureRejection(setupAction({ request } as never)); expect(error).toBeInstanceOf(Response); expect((error as Response).status).toBe(404); expect(mocks.loggerWarn).toHaveBeenCalledWith( { op: "kwp.oauth.setup.failed", failureCode: "tenant_access_denied", }, "KWP OAuth setup failed before provider authorization", ); expect(mocks.runAuthenticatedProviderOAuthCallback).not.toHaveBeenCalled(); expect(mocks.beginKwpOAuthConnection).not.toHaveBeenCalled(); }); it("logs a stable identity bucket and returns 404 when setup revalidation fails", async () => { mocks.runAuthenticatedProviderOAuthCallback.mockRejectedValueOnce( new mocks.ProviderOAuthCallbackAccessError("session_mismatch"), ); const request = new Request("https://app.example.test/integrations/kwp/setup?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "csrf-token", customerCode: "geerkens2", }), }); const error = await captureRejection(setupAction({ request } as never)); expect(error).toBeInstanceOf(Response); expect((error as Response).status).toBe(404); expect(mocks.loggerWarn).toHaveBeenCalledWith( { op: "kwp.oauth.setup.failed", failureCode: "session_mismatch", }, "KWP OAuth setup failed before provider authorization", ); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("geerkens2"); expect(mocks.beginKwpOAuthConnection).not.toHaveBeenCalled(); }); }); describe("KWP OAuth callback route", () => { it("clears an invalid challenge before any session, permission, or provider work", async () => { mocks.consumeChallenge.mockResolvedValueOnce({ ok: false, reason: "state-mismatch", clearCookie: "kwp=; Max-Age=0", }); const request = new Request("https://app.example.test/integrations/kwp/oauth/callback?code=code&state=tampered"); const response = await callbackLoader({ request } as never); expect(response.status).toBe(302); expect(response.headers.get("location")).toBe("/integrations/kwp/setup?kwp=error"); expect(response.headers.get("set-cookie")).toContain("Max-Age=0"); expect(mocks.runAuthenticatedProviderOAuthCallback).not.toHaveBeenCalled(); expect(mocks.completeKwpOAuthConnection).not.toHaveBeenCalled(); expect(mocks.loggerWarn).toHaveBeenCalledWith( { op: "kwp.oauth.callback.failed", failureCode: "challenge_invalid", diagnosticCode: "challenge_state_mismatch", }, "KWP OAuth callback failed", ); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("tampered"); }); it("consumes provider errors, restores the reservation, and never exchanges the code", async () => { const request = new Request(`https://app.example.test/integrations/kwp/oauth/callback?error=access_denied&state=${CHALLENGE.state}`); const response = await callbackLoader({ request } as never); expect(response.headers.get("location")).toBe("/acme/settings/integrations/kwp?kwp=error"); expect(response.headers.get("set-cookie")).toContain("Max-Age=0"); expect(mocks.runAuthenticatedProviderOAuthCallback).toHaveBeenCalledTimes(1); expect(mocks.cancelKwpOAuthConnectionAttempt).toHaveBeenCalledWith({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", connectionId: "connection-1", version: CHALLENGE.connectionVersion, }); expect(mocks.completeKwpOAuthConnection).not.toHaveBeenCalled(); expect(mocks.loggerWarn).toHaveBeenCalledWith( { op: "kwp.oauth.callback.failed", failureCode: "provider_response_invalid", diagnosticCode: "provider_access_denied", }, "KWP OAuth callback failed" ); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain(CHALLENGE.state); }); it("rechecks session, tenant module, and permission before exchanging the code", async () => { const request = new Request( `https://app.example.test/integrations/kwp/oauth/callback?code=one-time-code&state=${CHALLENGE.state}&iss=${encodeURIComponent("https://id.kwp-online.de/realms/kwp-federated")}` ); const response = await callbackLoader({ request } as never); expect(response.status).toBe(302); expect(response.headers.get("location")).toBe( "/integrations/kwp/setup?tenant=acme&connection=connection-1", ); expect(response.headers.get("set-cookie")).toContain("Max-Age=0"); expect(mocks.runAuthenticatedProviderOAuthCallback).toHaveBeenCalledWith({ request, tenantId: "tenant-1", userId: "user-1", callback: expect.any(Function), }); expect(mocks.loadIntegrationsContext).toHaveBeenCalledWith({ request, params: { tenant: "acme" }, requireModule: true, }); expect(mocks.requireIntegrationsPermission).toHaveBeenCalledWith(mocks.context, "integrations.connect"); expect(mocks.requireKwpIntegrationModule).toHaveBeenCalledWith(mocks.context); expect(mocks.completeKwpOAuthConnection).toHaveBeenCalledWith({ callbackParameters: { code: "one-time-code", state: CHALLENGE.state, iss: "https://id.kwp-online.de/realms/kwp-federated", }, challenge: CHALLENGE, }); }); it("rejects duplicate authorization parameters after consuming the challenge", async () => { const request = new Request(`https://app.example.test/integrations/kwp/oauth/callback?code=one&code=two&state=${CHALLENGE.state}`); const response = await callbackLoader({ request } as never); expect(response.headers.get("location")).toBe("/acme/settings/integrations/kwp?kwp=error"); expect(mocks.consumeChallenge).toHaveBeenCalledWith(request, CHALLENGE.state); expect(mocks.completeKwpOAuthConnection).not.toHaveBeenCalled(); }); it("logs only stable diagnostic codes when completion fails", async () => { mocks.completeKwpOAuthConnection.mockRejectedValueOnce(new mocks.KwpConnectError("exchange_failed", { diagnosticCode: "missing_refresh_token" })); const request = new Request(`https://app.example.test/integrations/kwp/oauth/callback?code=one-time-code&state=${CHALLENGE.state}`); const response = await callbackLoader({ request } as never); expect(response.headers.get("location")).toBe("/acme/settings/integrations/kwp?kwp=error"); expect(mocks.loggerWarn).toHaveBeenCalledWith( { op: "kwp.oauth.callback.failed", failureCode: "exchange_failed", diagnosticCode: "missing_refresh_token", }, "KWP OAuth callback failed" ); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("one-time-code"); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain(CHALLENGE.state); }); it("logs only the session bucket when callback access is no longer valid", async () => { mocks.runAuthenticatedProviderOAuthCallback.mockRejectedValueOnce( new mocks.ProviderOAuthCallbackAccessError("session_mismatch"), ); const request = new Request(`https://app.example.test/integrations/kwp/oauth/callback?code=session-secret&state=${CHALLENGE.state}`); const response = await callbackLoader({ request } as never); expect(response.headers.get("location")).toBe("/acme/settings/integrations/kwp?kwp=error"); expect(mocks.loggerWarn).toHaveBeenCalledWith( { op: "kwp.oauth.callback.failed", failureCode: "session_mismatch", }, "KWP OAuth callback failed" ); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("session-secret"); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain(CHALLENGE.state); }); it("redacts unexpected callback error details", async () => { mocks.completeKwpOAuthConnection.mockRejectedValueOnce(new Error(`unexpected-secret ${CHALLENGE.state}`)); const request = new Request(`https://app.example.test/integrations/kwp/oauth/callback?code=one-time-code&state=${CHALLENGE.state}`); const response = await callbackLoader({ request } as never); expect(response.headers.get("location")).toBe("/acme/settings/integrations/kwp?kwp=error"); expect(mocks.loggerWarn).toHaveBeenCalledWith( { op: "kwp.oauth.callback.failed", failureCode: "callback_access_or_unexpected", errorName: "Error", }, "KWP OAuth callback failed" ); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("unexpected-secret"); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("one-time-code"); expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain(CHALLENGE.state); }); });