mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-29 07:28:52 +00:00
fix(login): show account selection after RP-initiated logout (#12638)
**Supersedes #12471** by @conblem — same fix, rebased onto current `main` with conflicts resolved and review feedback applied. Original commits are preserved, all credit to @conblem. Closes #12252 ### Problem After an RP-initiated logout (`end_session` with `id_token_hint`), Login V2 redirected straight to `/loginname` instead of showing the account picker like Login V1. The `sessions` cookie still referenced the previous accounts, but their server-side sessions had been terminated, so `listSessions` returned nothing and the flow treated the browser as having no accounts at all. ### Solution - `handleOIDCFlowInitiation` now checks the `sessions` cookie (`hasCookieAccount`) when no live session is eligible for the request's organization. If the cookie still knows an account and the RP passed no `login_hint`, the user is sent to `/accounts` instead of `/loginname`. `prompt=none` is excluded since it must never render UI. - `/accounts` synthesizes an (invalid) `Session` for each cookie entry that has no live counterpart, so the account is still listed and a click re-authenticates via `/loginname` → password in one step. - `clearSession` prunes the cookie entry when the server reports the session as already gone (`NotFound` / `PermissionDenied`), so stale cards can be dismissed. Any other error is rethrown so a still-valid server session is never silently orphaned. - `getAllSessionCookieIds` is now a thin wrapper over `getAllSessions`; `FlowInitiationParams.sessionCookies` is typed as `Cookie[]`. - Tests: new `describe` block covering the cookie fallback, `login_hint` precedence, `prompt=none`, org-scope matching/mismatch, and `SELECT_ACCOUNT` / default prompt with live sessions filtered out by org. - Also adds `.claude/`, `.cursor/`, `.codex/`, `.windsurf/`, `.copilot/`, `.aider*` to `.gitignore`. --------- Co-authored-by: conblem <[email protected]>
This commit is contained in:
@@ -231,34 +231,17 @@ export async function getSessionCookieByLoginName<T>({
|
||||
|
||||
/**
|
||||
*
|
||||
* @param cleanup when true, removes all expired sessions, default true
|
||||
* @param cleanup when true, excludes expired sessions from the result, default false
|
||||
* @returns Session Cookies
|
||||
*/
|
||||
export async function getAllSessionCookieIds<T>(cleanup: boolean = false): Promise<string[]> {
|
||||
const cookiesList = await cookies();
|
||||
const stringifiedCookie = cookiesList.get("sessions");
|
||||
|
||||
if (!stringifiedCookie?.value) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie.value);
|
||||
|
||||
if (cleanup) {
|
||||
const now = new Date();
|
||||
return sessions
|
||||
.filter((session) =>
|
||||
session.expirationTs ? timestampDate(timestampFromMs(Number(session.expirationTs))) > now : true,
|
||||
)
|
||||
.map((session) => session.id);
|
||||
}
|
||||
|
||||
return sessions.map((session) => session.id);
|
||||
const sessions = await getAllSessions<T>(cleanup);
|
||||
return sessions.map(({ id }) => id);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param cleanup when true, removes all expired sessions, default true
|
||||
* @param cleanup when true, excludes expired sessions from the result, default false
|
||||
* @returns Session Cookies
|
||||
*/
|
||||
export async function getAllSessions<T>(cleanup: boolean = false): Promise<SessionCookie<T>[]> {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Cookie } from "@/lib/cookies";
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { FlowInitiationParams, handleOIDCFlowInitiation } from "./flow-initiation";
|
||||
@@ -51,6 +52,10 @@ function makeRequest(url = "https://example.com/login?requestId=oidc_abc123"): N
|
||||
return new NextRequest(url);
|
||||
}
|
||||
|
||||
function makeCookie(id: string, overrides?: Partial<Cookie>): Cookie {
|
||||
return { id, token: "tok", loginName: "", creationTs: "", expirationTs: "", changeTs: "", ...overrides };
|
||||
}
|
||||
|
||||
function makeBaseParams(overrides?: Partial<FlowInitiationParams>): FlowInitiationParams {
|
||||
return {
|
||||
serviceConfig: { baseUrl: "https://api.example.com" } as any,
|
||||
@@ -243,7 +248,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [{ id: "session-other", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-other")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -270,7 +275,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [{ id: "session-other", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-other")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -296,7 +301,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [{ id: "session-other", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-other")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -321,7 +326,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [orgSession] as any,
|
||||
sessionCookies: [{ id: "session-org", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-org")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -351,7 +356,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [{ id: "session-other", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-other")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -378,7 +383,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [{ id: "session-other", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-other")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -405,7 +410,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [{ id: "session-other", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-other")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -430,7 +435,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [orgSession] as any,
|
||||
sessionCookies: [{ id: "session-org", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-org")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -646,6 +651,191 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleOIDCFlowInitiation — stale session cookie fallback (#12252)", () => {
|
||||
let mockGetAuthRequest: ReturnType<typeof vi.fn>;
|
||||
let mockConstructUrl: ReturnType<typeof vi.fn>;
|
||||
let mockFindValidSession: ReturnType<typeof vi.fn>;
|
||||
let mockSendLoginname: ReturnType<typeof vi.fn>;
|
||||
|
||||
// Cookie entries left behind after an RP-initiated logout terminated the
|
||||
// server-side sessions: no live Session objects, but loginName is still known.
|
||||
const staleOrgCookie = makeCookie("session-stale-org", { loginName: "[email protected]", organization: "111111" });
|
||||
const staleOtherOrgCookie = makeCookie("session-stale-other", { loginName: "[email protected]", organization: "999999" });
|
||||
const otherOrgSession = {
|
||||
id: "session-other",
|
||||
factors: { user: { id: "user2", organizationId: "999999", loginName: "[email protected]" } },
|
||||
};
|
||||
|
||||
function authRequestWith(overrides: Record<string, unknown>) {
|
||||
mockGetAuthRequest.mockResolvedValue({
|
||||
authRequest: {
|
||||
id: "abc123",
|
||||
uiLocales: [],
|
||||
scope: [],
|
||||
prompt: [],
|
||||
loginHint: undefined,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
|
||||
const zitadel = await import("@/lib/zitadel");
|
||||
const serviceUrl = await import("@/lib/service-url");
|
||||
const session = await import("@/lib/session");
|
||||
const authUtils = await import("@/lib/auth-utils");
|
||||
const loginname = await import("@/lib/server/loginname");
|
||||
|
||||
mockGetAuthRequest = vi.mocked(zitadel.getAuthRequest);
|
||||
mockConstructUrl = vi.mocked(serviceUrl.constructUrl);
|
||||
mockFindValidSession = vi.mocked(session.findValidSession);
|
||||
mockSendLoginname = vi.mocked(loginname.sendLoginname);
|
||||
vi.mocked(zitadel.getLoginSettings).mockResolvedValue(undefined);
|
||||
vi.mocked(zitadel.getSecuritySettings).mockResolvedValue(undefined);
|
||||
vi.mocked(authUtils.getValidLocaleFromUILocales).mockReturnValue(null);
|
||||
|
||||
mockConstructUrl.mockImplementation((_req: any, path: string) => {
|
||||
return new URL(`https://example.com${path}`);
|
||||
});
|
||||
|
||||
mockFindValidSession.mockResolvedValue(null);
|
||||
mockSendLoginname.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
test("should redirect to /accounts when there are no live sessions but the cookie references an account", async () => {
|
||||
authRequestWith({});
|
||||
|
||||
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/accounts");
|
||||
expect(location).not.toContain("/loginname");
|
||||
});
|
||||
|
||||
test("should ignore cookie entries without a loginName", async () => {
|
||||
authRequestWith({});
|
||||
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({ sessions: [], sessionCookies: [{ ...staleOrgCookie, loginName: "" }] }),
|
||||
);
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/loginname");
|
||||
});
|
||||
|
||||
test("should prefer login_hint over the cookie fallback when there are no live sessions", async () => {
|
||||
authRequestWith({ loginHint: "[email protected]" });
|
||||
mockSendLoginname.mockResolvedValue({ redirect: "/password?requestId=oidc_abc123" });
|
||||
|
||||
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/password");
|
||||
expect(location).not.toContain("/accounts");
|
||||
});
|
||||
|
||||
test("should not show the account picker for prompt=none even if the cookie references an account", async () => {
|
||||
const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb");
|
||||
authRequestWith({ prompt: [Prompt.NONE] });
|
||||
|
||||
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).not.toContain("/accounts");
|
||||
});
|
||||
|
||||
test("should redirect to /loginname when the cookie account belongs to a different org than the org scope", async () => {
|
||||
authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] });
|
||||
|
||||
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOtherOrgCookie] }));
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/loginname");
|
||||
expect(location).not.toContain("/accounts");
|
||||
});
|
||||
|
||||
test("should redirect to /accounts when the cookie account matches the org scope", async () => {
|
||||
authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] });
|
||||
|
||||
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/accounts");
|
||||
expect(location).toContain("organization=111111");
|
||||
});
|
||||
|
||||
test("should keep /accounts for SELECT_ACCOUNT when live sessions are filtered out by org but the cookie has a matching account", async () => {
|
||||
const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb");
|
||||
authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"], prompt: [Prompt.SELECT_ACCOUNT] });
|
||||
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [{ ...staleOtherOrgCookie, id: "session-other" }, staleOrgCookie],
|
||||
}),
|
||||
);
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/accounts");
|
||||
});
|
||||
|
||||
test("should not show the account picker for prompt=login even if the cookie references an account", async () => {
|
||||
const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb");
|
||||
authRequestWith({ prompt: [Prompt.LOGIN] });
|
||||
|
||||
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/loginname");
|
||||
expect(location).not.toContain("/accounts");
|
||||
});
|
||||
|
||||
test("should let login_hint win over the cookie fallback for SELECT_ACCOUNT when no live session is eligible", async () => {
|
||||
const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb");
|
||||
authRequestWith({
|
||||
scope: ["urn:zitadel:iam:org:id:111111"],
|
||||
prompt: [Prompt.SELECT_ACCOUNT],
|
||||
loginHint: "[email protected]",
|
||||
});
|
||||
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [
|
||||
makeCookie("session-other", { loginName: "[email protected]", organization: "999999" }),
|
||||
staleOrgCookie,
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/loginname");
|
||||
expect(location).toContain("loginName=hinted%40org.com");
|
||||
expect(location).not.toContain("/accounts");
|
||||
});
|
||||
|
||||
test("should keep /accounts (default prompt) when live sessions are filtered out by org but the cookie has a matching account", async () => {
|
||||
authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] });
|
||||
|
||||
const res = await handleOIDCFlowInitiation(
|
||||
makeBaseParams({
|
||||
sessions: [otherOrgSession] as any,
|
||||
sessionCookies: [{ ...staleOtherOrgCookie, id: "session-other" }, staleOrgCookie],
|
||||
}),
|
||||
);
|
||||
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/accounts");
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleOIDCFlowInitiation — Prompt.LOGIN + loginHint requestId prefix", () => {
|
||||
let mockGetAuthRequest: ReturnType<typeof vi.fn>;
|
||||
let mockConstructUrl: ReturnType<typeof vi.fn>;
|
||||
@@ -700,7 +890,7 @@ describe("handleOIDCFlowInitiation — Prompt.LOGIN + loginHint requestId prefix
|
||||
makeBaseParams({
|
||||
requestId: "oidc_abc123",
|
||||
sessions: [existingSession] as any,
|
||||
sessionCookies: [{ id: "session-1", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-1")],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -733,7 +923,7 @@ describe("handleOIDCFlowInitiation — Prompt.LOGIN + loginHint requestId prefix
|
||||
makeBaseParams({
|
||||
requestId: "oidc_abc123",
|
||||
sessions: [existingSession] as any,
|
||||
sessionCookies: [{ id: "session-1", token: "tok" }],
|
||||
sessionCookies: [makeCookie("session-1")],
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { getValidLocaleFromUILocales } from "@/lib/auth-utils";
|
||||
import { isExternalUrl, isSafeRedirectUri } from "@/lib/client-utils";
|
||||
import { getLanguageCookie, setLanguageCookie } from "@/lib/cookies";
|
||||
import { getLanguageCookie, setLanguageCookie, type Cookie } from "@/lib/cookies";
|
||||
|
||||
import { shouldUILocalesOverrideCookie } from "@/lib/i18n";
|
||||
import { idpTypeToSlug } from "@/lib/idp";
|
||||
@@ -222,11 +222,22 @@ function getEligibleSessions(sessions: Session[], organization?: string): Sessio
|
||||
return sessions.filter((s) => s.factors?.user?.organizationId === organization);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the `sessions` cookie references any previous account for the given
|
||||
* organization (or for any org when `organization` is unset).
|
||||
*/
|
||||
function hasCookieAccount(sessionCookies: Cookie[], organization?: string): boolean {
|
||||
if (!sessionCookies || sessionCookies.length === 0) {
|
||||
return false;
|
||||
}
|
||||
return sessionCookies.some((c) => !!c.loginName && (!organization || c.organization === organization));
|
||||
}
|
||||
|
||||
export interface FlowInitiationParams {
|
||||
serviceConfig: ServiceConfig;
|
||||
requestId: string;
|
||||
sessions: Session[];
|
||||
sessionCookies: any[];
|
||||
sessionCookies: Cookie[];
|
||||
request: NextRequest;
|
||||
}
|
||||
|
||||
@@ -366,13 +377,19 @@ export async function handleOIDCFlowInitiation(params: FlowInitiationParams): Pr
|
||||
|
||||
if (authRequest.prompt.includes(Prompt.SELECT_ACCOUNT)) {
|
||||
if (eligibleSessions.length === 0) {
|
||||
return gotoLoginname({
|
||||
request,
|
||||
requestId,
|
||||
loginHint: authRequest.loginHint,
|
||||
organization,
|
||||
orgDomain,
|
||||
});
|
||||
// No live session is eligible. If the session cookie still references
|
||||
// a previous account (and the RP did not pass a login_hint, which always
|
||||
// takes precedence over the cookie fallback), keep account selection so
|
||||
// the user can pick it.
|
||||
if (authRequest.loginHint || !hasCookieAccount(sessionCookies, organization)) {
|
||||
return gotoLoginname({
|
||||
request,
|
||||
requestId,
|
||||
loginHint: authRequest.loginHint,
|
||||
organization,
|
||||
orgDomain,
|
||||
});
|
||||
}
|
||||
}
|
||||
return gotoAccounts({
|
||||
request,
|
||||
@@ -464,7 +481,9 @@ export async function handleOIDCFlowInitiation(params: FlowInitiationParams): Pr
|
||||
|
||||
// Prefill loginname (not the account picker) for an unresolved hint or when
|
||||
// no session is eligible: the picker would only list non-matching accounts.
|
||||
if (authRequest.loginHint || eligibleSessions.length === 0) {
|
||||
// Exception: if the sessions cookie still references a previous account for
|
||||
// this organization, keep the picker so the user can select it (#12252).
|
||||
if (authRequest.loginHint || (eligibleSessions.length === 0 && !hasCookieAccount(sessionCookies, organization))) {
|
||||
return gotoLoginname({
|
||||
request,
|
||||
requestId,
|
||||
@@ -534,6 +553,26 @@ export async function handleOIDCFlowInitiation(params: FlowInitiationParams): Pr
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No live sessions were resolved. If the sessions cookie still references a
|
||||
// previous account and the RP did not pass a login_hint, show account
|
||||
// selection (mirrors Login V1 behavior after RP-initiated logout, #12252).
|
||||
// prompt=none must never render UI and prompt=login goes straight to
|
||||
// /loginname like it does when live sessions exist, so both keep the
|
||||
// existing behavior.
|
||||
if (
|
||||
!authRequest?.loginHint &&
|
||||
!authRequest?.prompt.includes(Prompt.NONE) &&
|
||||
!authRequest?.prompt.includes(Prompt.LOGIN) &&
|
||||
hasCookieAccount(sessionCookies, organization)
|
||||
) {
|
||||
return gotoAccounts({
|
||||
request,
|
||||
requestId,
|
||||
organization,
|
||||
orgDomain,
|
||||
});
|
||||
}
|
||||
|
||||
// No session: resolve a login_hint straight to the next step if we can.
|
||||
const hintResponse = await resolveLoginHint({
|
||||
request,
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { Code } from "@connectrpc/connect";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { clearSession } from "./session";
|
||||
|
||||
vi.mock("@zitadel/client", async () => {
|
||||
const { Code } = await import("@connectrpc/connect");
|
||||
return { Code, create: vi.fn((_schema: unknown, data: unknown) => data), Duration: {} };
|
||||
});
|
||||
|
||||
vi.mock("@/lib/zitadel", () => ({
|
||||
deleteSession: vi.fn(),
|
||||
getLoginSettings: vi.fn(),
|
||||
getSecuritySettings: vi.fn(),
|
||||
humanMFAInitSkipped: vi.fn(),
|
||||
listAuthenticationMethodTypes: vi.fn(),
|
||||
listUsers: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/server/cookie", () => ({
|
||||
createSessionAndUpdateCookie: vi.fn(),
|
||||
setSessionAndUpdateCookie: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../cookies", () => ({
|
||||
getMostRecentSessionCookie: vi.fn(),
|
||||
getSessionCookieById: vi.fn(),
|
||||
getSessionCookieByLoginName: vi.fn(),
|
||||
removeSessionFromCookie: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../service-url", () => ({
|
||||
getServiceConfig: vi.fn(() => ({ serviceConfig: { baseUrl: "https://example.com" } })),
|
||||
}));
|
||||
|
||||
vi.mock("../client", () => ({
|
||||
completeFlowOrGetUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../session", () => ({
|
||||
isSessionValid: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./host", () => ({
|
||||
getPublicHost: vi.fn(() => "test.com"),
|
||||
}));
|
||||
|
||||
vi.mock("./loginname", () => ({
|
||||
sendLoginname: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("next-intl/server", () => ({
|
||||
getTranslations: vi.fn(async () => (key: string) => key),
|
||||
}));
|
||||
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(() => new Headers()),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/grpc/interceptors/error-classification", () => ({
|
||||
isClassifiedError: (error: unknown) => error !== null && typeof error === "object" && "code" in error,
|
||||
}));
|
||||
|
||||
const cookie = { id: "session-1", token: "token-1", loginName: "[email protected]" };
|
||||
|
||||
describe("clearSession", () => {
|
||||
let deleteSession: any;
|
||||
let getSecuritySettings: any;
|
||||
let getSessionCookieById: any;
|
||||
let removeSessionFromCookie: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
const zitadel = await import("@/lib/zitadel");
|
||||
const cookies = await import("../cookies");
|
||||
deleteSession = vi.mocked(zitadel.deleteSession);
|
||||
getSecuritySettings = vi.mocked(zitadel.getSecuritySettings);
|
||||
getSessionCookieById = vi.mocked(cookies.getSessionCookieById);
|
||||
removeSessionFromCookie = vi.mocked(cookies.removeSessionFromCookie);
|
||||
|
||||
getSessionCookieById.mockResolvedValue(cookie);
|
||||
getSecuritySettings.mockResolvedValue({ embeddedIframe: { enabled: true } });
|
||||
});
|
||||
|
||||
test("deletes the session and prunes the cookie entry on success", async () => {
|
||||
deleteSession.mockResolvedValue({ details: {} });
|
||||
|
||||
const res = await clearSession({ sessionId: "session-1" });
|
||||
|
||||
expect(res).toBeUndefined();
|
||||
expect(deleteSession).toHaveBeenCalledWith(expect.objectContaining({ sessionId: "session-1", sessionToken: "token-1" }));
|
||||
expect(removeSessionFromCookie).toHaveBeenCalledWith({ session: cookie, iFrameEnabled: true });
|
||||
});
|
||||
|
||||
test("prunes the cookie entry when the server rejects the cookie token (session gone or token stale)", async () => {
|
||||
deleteSession.mockRejectedValue({ code: Code.PermissionDenied });
|
||||
|
||||
const res = await clearSession({ sessionId: "session-1" });
|
||||
|
||||
expect(res).toBeUndefined();
|
||||
expect(removeSessionFromCookie).toHaveBeenCalledWith({ session: cookie, iFrameEnabled: true });
|
||||
});
|
||||
|
||||
test("keeps the cookie entry and reports an error on any other failure", async () => {
|
||||
deleteSession.mockRejectedValue({ code: Code.Unavailable });
|
||||
|
||||
const res = await clearSession({ sessionId: "session-1" });
|
||||
|
||||
expect(res).toEqual({ error: "couldNotClearSession" });
|
||||
expect(removeSessionFromCookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("attempts the server-side delete even when security settings cannot be loaded", async () => {
|
||||
deleteSession.mockResolvedValue({ details: {} });
|
||||
getSecuritySettings.mockRejectedValue(new Error("settings unavailable"));
|
||||
|
||||
await expect(clearSession({ sessionId: "session-1" })).rejects.toThrow("settings unavailable");
|
||||
|
||||
expect(deleteSession).toHaveBeenCalledTimes(1);
|
||||
expect(removeSessionFromCookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("does nothing when the session id is not in the cookie", async () => {
|
||||
getSessionCookieById.mockResolvedValue(undefined);
|
||||
|
||||
const res = await clearSession({ sessionId: "unknown" });
|
||||
|
||||
expect(res).toBeUndefined();
|
||||
expect(deleteSession).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
listAuthenticationMethodTypes,
|
||||
listUsers,
|
||||
} from "@/lib/zitadel";
|
||||
import { create, Duration } from "@zitadel/client";
|
||||
import { Code, create, Duration } from "@zitadel/client";
|
||||
import { Challenges, RequestChallenges } from "@zitadel/proto/zitadel/session/v2/challenge_pb";
|
||||
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
|
||||
import { Checks, ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
@@ -294,7 +294,7 @@ type ClearSessionOptions = {
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
export async function clearSession(options: ClearSessionOptions) {
|
||||
export async function clearSession(options: ClearSessionOptions): Promise<{ error?: string } | void> {
|
||||
const _headers = await headers();
|
||||
const { serviceConfig } = getServiceConfig(_headers);
|
||||
|
||||
@@ -306,18 +306,40 @@ export async function clearSession(options: ClearSessionOptions) {
|
||||
return;
|
||||
}
|
||||
|
||||
const deleteResponse = await deleteSession({
|
||||
serviceConfig,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
});
|
||||
try {
|
||||
const deleteResponse = await deleteSession({
|
||||
serviceConfig,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
});
|
||||
if (!deleteResponse) {
|
||||
throw new Error("Could not delete session");
|
||||
}
|
||||
} catch (error) {
|
||||
// The backend verifies the cookie's token before it looks at the session
|
||||
// state, so PermissionDenied is what a session that no longer exists answers
|
||||
// (nothing to verify against). It is also what a live session with a stale
|
||||
// cookie token would answer; we deliberately prune the cookie entry in that
|
||||
// case too: the user explicitly asked to remove the account from this
|
||||
// browser, and without its token the server-side session cannot be used by
|
||||
// anyone and simply expires. Every other failure keeps the entry and is
|
||||
// reported so the caller can show it.
|
||||
// (A session terminated by an RP-initiated logout keeps its token id, so
|
||||
// deleting it again succeeds and never reaches this branch.)
|
||||
if (!isClassifiedError(error) || error.code !== Code.PermissionDenied) {
|
||||
logger.error("clearSession: could not delete session", { sessionId: sessionCookie.id, error });
|
||||
const t = await getTranslations("error");
|
||||
return { error: t("couldNotClearSession") };
|
||||
}
|
||||
|
||||
logger.warn("clearSession: session rejected the cookie token (gone or stale), pruning cookie entry", {
|
||||
sessionId: sessionCookie.id,
|
||||
});
|
||||
}
|
||||
|
||||
// Only needed for the cookie rewrite, so it must not gate the delete above.
|
||||
const securitySettings = await getSecuritySettings({ serviceConfig });
|
||||
const iFrameEnabled = !!securitySettings?.embeddedIframe?.enabled;
|
||||
|
||||
if (!deleteResponse) {
|
||||
throw new Error("Could not delete session");
|
||||
}
|
||||
|
||||
return removeSessionFromCookie({ session: sessionCookie, iFrameEnabled });
|
||||
await removeSessionFromCookie({ session: sessionCookie, iFrameEnabled });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user