diff --git a/e2e/common/oauth2-fixtures.mjs b/e2e/common/oauth2-fixtures.mjs index c9eec6c100..3aadb5af99 100644 --- a/e2e/common/oauth2-fixtures.mjs +++ b/e2e/common/oauth2-fixtures.mjs @@ -26,6 +26,19 @@ export const REALM = "root"; export const SCOPE = "profile"; export const REDIRECT_URI = "http://app.invalid/cb"; +/* + * The post-logout redirect URIs registered on the OIDC client. endSession accepts a post_logout_redirect_uri + * only when the client's registered set contains it exactly, so the variant with a query is registered on its own. + */ +export const POST_LOGOUT_REDIRECT_URI = "http://app.invalid/logout"; +export const POST_LOGOUT_REDIRECT_URI_WITH_QUERY = "http://app.invalid/logout?ui=1"; + +/* + * The clientSessionURI registered on the OIDC client: the origin the checkSession page accepts postMessage + * calls from. For a client without one the page gets an empty origin and accepts no message. + */ +export const CLIENT_SESSION_URI = "http://rp.invalid"; + /* * Client ids are PER SPEC FILE, not shared. Playwright runs spec files in parallel, and rewriting a client * invalidates the tokens already issued against it -- so two files sharing one client flake as soon as their @@ -192,6 +205,10 @@ export async function ensureOidcClient(adminToken, request, clientId) { "userpassword": OIDC_CLIENT_SECRET, "com.forgerock.openam.oauth2provider.clientType": "Confidential", "com.forgerock.openam.oauth2provider.redirectionURIs": [`[0]=${REDIRECT_URI}`], + "com.forgerock.openam.oauth2provider.postLogoutRedirectURI": [ + `[0]=${POST_LOGOUT_REDIRECT_URI}`, `[1]=${POST_LOGOUT_REDIRECT_URI_WITH_QUERY}`, + ], + "com.forgerock.openam.oauth2provider.clientSessionURI": CLIENT_SESSION_URI, "com.forgerock.openam.oauth2provider.scopes": ["[0]=openid", "[1]=profile"], "com.forgerock.openam.oauth2provider.defaultScopes": ["[0]=openid"], "com.forgerock.openam.oauth2provider.grantTypes": [ @@ -211,6 +228,22 @@ export async function ensureOidcClient(adminToken, request, clientId) { }); } +/** + * A confidential OIDC client without a clientSessionURI, as the admin API creates one by default. It shares + * OIDC_CLIENT_SECRET, so a test can sign an HS256 id_token for it that passes checkSession's signature check. + */ +export async function ensureNoSessionUriOidcClient(adminToken, request, clientId) { + await ensureClient(adminToken, request, clientId, { + "userpassword": OIDC_CLIENT_SECRET, + "com.forgerock.openam.oauth2provider.clientType": "Confidential", + "com.forgerock.openam.oauth2provider.redirectionURIs": [`[0]=${REDIRECT_URI}`], + "com.forgerock.openam.oauth2provider.scopes": ["[0]=openid", "[1]=profile"], + "com.forgerock.openam.oauth2provider.defaultScopes": ["[0]=openid"], + "com.forgerock.openam.oauth2provider.idTokenSignedResponseAlg": "HS256", + "sunIdentityServerDeviceStatus": "Active", + }); +} + /** * Give each worker/run its own provider. No root-realm provider GET/PUT is performed, * so this setup cannot overwrite settings being changed by the other OAuth/UMA specs. diff --git a/e2e/oauth2/oidc-test.spec.mjs b/e2e/oauth2/oidc-test.spec.mjs index 5cca0471d7..219cf4593b 100644 --- a/e2e/oauth2/oidc-test.spec.mjs +++ b/e2e/oauth2/oidc-test.spec.mjs @@ -15,31 +15,42 @@ */ /* - * Protocol cover for the OIDC half of /oauth2: discovery, the JWK set, id_token issuance and idtokeninfo. - * On master Restlet serves all of them (OAuth2RouterProvider under the ForgeRockRest servlet). This spec pins - * their black-box contract before /oauth2 moves to CHF. A flip may change a pinned value only as a divergence + * Protocol cover for the OIDC half of /oauth2: discovery, the JWK set, id_token issuance, idtokeninfo and the + * session endpoints checkSession and endSession. On master Restlet serves all of them (OAuth2RouterProvider under + * the ForgeRockRest servlet), except the bare /oauth2/connect/checkSession, which web.xml maps to a JSP. This spec + * pins their black-box contract before /oauth2 moves to CHF. A flip may change a pinned value only as a divergence * listed in its PR. */ -import { createHash } from "node:crypto"; +import { createHash, createHmac } from "node:crypto"; import { test, expect, request as apiRequest } from "@playwright/test"; import { OPENAM_BASE, getAdminToken, getAuthToken, PASSWORD, USERNAME } from "../common/openam-commons.mjs"; import { - OIDC_CLIENT_SECRET, REALM, authorizationCodeTokens, basicAuth, ensureOidcClient, ensureProviderConfig, - sessionContext, + CLIENT_SESSION_URI, OIDC_CLIENT_SECRET, POST_LOGOUT_REDIRECT_URI, POST_LOGOUT_REDIRECT_URI_WITH_QUERY, REALM, + REDIRECT_URI, authorizationCodeTokens, basicAuth, ensureNoSessionUriOidcClient, ensureOidcClient, + ensureProviderConfig, sessionContext, } from "../common/oauth2-fixtures.mjs"; /** This spec's own client -- spec files run in parallel and rewriting a shared client kills its tokens. */ const OIDC_CLIENT_ID = "test_client_oidc"; +/** Same realm, no clientSessionURI: a client as the admin API creates it by default. */ +const NO_SESSION_URI_CLIENT_ID = "test_client_oidc_nosessionuri"; + const NONCE = "n-0S6_WzA2Mj"; /** Content-Type of the successful JSON answers: discovery, the JWK set and idtokeninfo. */ const JSON_TYPE = "application/json;charset=UTF-8"; -/** Content-Type of the error answers: idtokeninfo's 400s, the unknown realm's 404. Unlike the 200s, no charset. */ +/** + * Content-Type of the error answers: the 400s of idtokeninfo, checkSession and endSession, and the unknown realm's + * 404. Unlike the 200s, no charset. + */ const ERROR_TYPE = "application/json"; +/** Content-Type of both checkSession pages: the JSP on the bare path and the Restlet page under realms/. */ +const HTML_TYPE = "text/html;charset=UTF-8"; + /** Every member the discovery document has on master, sorted. */ const DISCOVERY_KEYS = [ "acr_values_supported", "authorization_endpoint", "check_session_iframe", "claims_parameter_supported", @@ -73,6 +84,31 @@ test.beforeAll(async ({ request }) => { await ensureProviderConfig(adminToken, request); }); +/** + * Logs demo in and runs the authorization_code flow for this spec's client. Returns a request context whose cookie + * jar carries that session and the id_token issued under it. The caller disposes `ctx`. + */ +async function oidcSession(nonce) { + const loginCtx = await apiRequest.newContext(); + let ssoToken; + try { + ssoToken = await getAuthToken(loginCtx, USERNAME, PASSWORD); + } finally { + await loginCtx.dispose(); + } + expect(ssoToken, "demo login failed").toBeTruthy(); + const ctx = await sessionContext(apiRequest, ssoToken); + try { + const { tokens } = await authorizationCodeTokens(ctx, { + clientId: OIDC_CLIENT_ID, clientSecret: OIDC_CLIENT_SECRET, scope: "openid", nonce, + }); + return { ctx, idToken: tokens.id_token }; + } catch (e) { + await ctx.dispose(); + throw e; + } +} + test.describe("OIDC discovery", () => { test("/oauth2/.well-known/openid-configuration advertises this deployment's endpoints", async ({ request }) => { @@ -279,3 +315,274 @@ test.describe("OIDC id_token issuance and idtokeninfo", () => { await expectJson(response, 400, { error: "bad_request", error_description: "invalid id_token" }); }); }); + +test.describe("OIDC checkSession", () => { + + const CHECK_SESSION = `${OPENAM_BASE}/oauth2/realms/${REALM}/connect/checkSession`; + + const b64 = (o) => Buffer.from(JSON.stringify(o)).toString("base64url"); + + /** A JWT whose signature verifies against no key: enough for a token checkSession must not accept. */ + const jwt = (claims) => `${b64({ alg: "HS256", typ: "JWT" })}.${b64(claims)}.c2ln`; + + /** An HS256 JWT signed with the given secret, so it passes checkSession's signature check. */ + const signedJwt = (claims, secret) => { + const signingInput = `${b64({ alg: "HS256", typ: "JWT" })}.${b64(claims)}`; + return `${signingInput}.${createHmac("sha256", secret).update(signingInput).digest("base64url")}`; + }; + + /** checkSession reads the id_token from the Referer's query string, the way the RP's iframe passes it. */ + const withIdToken = (idToken) => ({ headers: { Referer: `http://rp.invalid/page?id_token=${idToken}` } }); + + let session; + + test.beforeAll(async ({ request }) => { + await ensureOidcClient(adminToken, request, OIDC_CLIENT_ID); + await ensureNoSessionUriOidcClient(adminToken, request, NO_SESSION_URI_CLIENT_ID); + session = await oidcSession("check-session"); + }); + + test.afterAll(async () => { + await session?.ctx.dispose(); + }); + + test("/oauth2/connect/checkSession serves the session-management iframe", async ({ request }) => { + const response = await request.get(`${OPENAM_BASE}/oauth2/connect/checkSession`); + const html = await response.text(); + console.log(`[oidc] checkSession -> ${response.status()} ct=${response.headers()["content-type"]} bytes=${html.length}`); + expect(response.status()).toBe(200); + expect(response.headers()["content-type"]).toBe(HTML_TYPE); + // The RP-facing contract of the iframe: it listens for postMessage and answers with a session state. + expect(html).toContain("addEventListener"); + expect(html).toContain("receiveMessage"); + expect(html).toContain("session_state"); + }); + + test("the bare path is the JSP and the realm-prefixed path is the Restlet page", async ({ request }) => { + const jsp = await request.get(`${OPENAM_BASE}/oauth2/connect/checkSession`); + const page = await request.get(CHECK_SESSION); + const jspHtml = await jsp.text(); + const pageHtml = await page.text(); + console.log(`[oidc] checkSession jsp=${jsp.status()} page=${page.status()}`); + + for (const [name, response] of [["jsp", jsp], ["page", page]]) { + expect(response.status(), name).toBe(200); + expect(response.headers()["content-type"], name).toBe(HTML_TYPE); + // The RP frames this page: SecurityHeaders excludes /connect/checkSession, so neither answer carries + // X-Frame-Options. Neither carries a cache header. + expect(response.headers()["x-frame-options"], name).toBeUndefined(); + expect(response.headers()["cache-control"], name).toBeUndefined(); + expect(response.headers()["pragma"], name).toBeUndefined(); + } + + // The JSP loads sha256.js by a relative path, the Restlet page by the absolute base URL. + expect(jspHtml).toContain('