diff --git a/e2e/common/oauth2-fixtures.mjs b/e2e/common/oauth2-fixtures.mjs index c9eec6c100..450f5d37fc 100644 --- a/e2e/common/oauth2-fixtures.mjs +++ b/e2e/common/oauth2-fixtures.mjs @@ -425,6 +425,7 @@ export async function pkce() { export function sessionContext(apiRequest, ssoToken, extraCookies = []) { const domain = new URL(OPENAM_BASE).hostname; return apiRequest.newContext({ + ignoreHTTPSErrors: true, storageState: { cookies: [{ name: "iPlanetDirectoryPro", value: ssoToken }, ...extraCookies].map((cookie) => ({ ...cookie, domain, path: "/", expires: -1, httpOnly: false, secure: false, sameSite: "Lax", diff --git a/e2e/oauth2/display-test.spec.mjs b/e2e/oauth2/display-test.spec.mjs new file mode 100644 index 0000000000..7e8e8cee34 --- /dev/null +++ b/e2e/oauth2/display-test.spec.mjs @@ -0,0 +1,354 @@ +/* + * The contents of this file are subject to the terms of the Common Development and + * Distribution License (the License). You may not use this file except in compliance with the + * License. + * + * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the + * specific language governing permission and limitations under the License. + * + * When distributing Covered Software, include this CDDL Header Notice in each file and include + * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL + * Header, with the fields enclosed by brackets [] replaced by your own identifying + * information: "Portions copyright [year] [name of copyright owner]". + * + * Copyright 2026 3A Systems, LLC. + */ + +/* + * The ?display= surface of the consent page on /oauth2/authorize. + * OAuth2Representation picks the template folder from the + * parameter: page/ (also for an absent or empty value), popup/ (composed into popup.ftl), touch/ or wap/. This spec + * pins that black-box contract before /oauth2 moves to CHF. A flip may change a pinned value only as a divergence + * listed in its PR. + * + * Two pinned values are master defects, and the assertions name their targets: touch/authorize.ftl writes the + * client name under `isplayName`, and an unknown display answers 400 server_error instead of 400 invalid_request. + */ + +import { test, expect, request as apiRequest } from "@playwright/test"; +import { OPENAM_BASE, getAdminToken, getAuthToken, PASSWORD, USERNAME } from "../common/openam-commons.mjs"; +import { REALM, REDIRECT_URI, SCOPE, ensureProviderConfig, pkce, sessionContext } from "../common/oauth2-fixtures.mjs"; + +/** This spec's own clients: Playwright runs spec files in parallel, and a client another file rewrites mid-run + * would break this one. */ +const CONSENT_CLIENT_ID = "test_client_display"; + +const OAUTH2 = `${OPENAM_BASE}/oauth2`; +/** The deployment's context path, so the form-target checks survive a deployment mounted elsewhere. */ +const CONTEXT_PATH = new URL(OPENAM_BASE).pathname.replace(/\/$/, ""); +/** Content-Type of every page below, the WML one included. */ +const HTML_TYPE = "text/html;charset=UTF-8"; + +let adminToken; +let demoToken; +let demoCtx; +/** The name the consent page shows for the resource owner. */ +let demoName; +let challenge; + +const agentHeaders = () => ({ + iPlanetDirectoryPro: adminToken, "Content-Type": "application/json", + "Accept-API-Version": "protocol=2.0,resource=1.0", +}); + +/** + * Writes a client that requires consent. `isConsentImplied:false` is the whole point: the provider requires consent + * when `!clientsCanSkipConsent || !isConsentImplied`, so this flag alone sends the request to the consent page, the + * only page `?display=` selects a template for. + */ +async function writeClient(request, clientId, extra) { + const written = await request.put( + `${OPENAM_BASE}/json/realms/${REALM}/realm-config/agents/OAuth2Client/${clientId}`, { + headers: agentHeaders(), + data: { + "com.forgerock.openam.oauth2provider.clientType": "Public", + "com.forgerock.openam.oauth2provider.redirectionURIs": [`[0]=${REDIRECT_URI}`], + "com.forgerock.openam.oauth2provider.scopes": [`[0]=${SCOPE}`, "[1]=openid"], + "com.forgerock.openam.oauth2provider.defaultScopes": [`[0]=${SCOPE}`], + "com.forgerock.openam.oauth2provider.responseTypes": ["[0]=code", "[1]=token"], + "com.forgerock.openam.oauth2provider.tokenEndPointAuthMethod": "none", + isConsentImplied: false, + sunIdentityServerDeviceStatus: "Active", + ...extra, + }, + }); + if (!written.ok()) { + throw new Error(`Failed to write ${clientId}: ${written.status()} ${written.statusText()} ${await written.text()}`); + } +} + +test.beforeAll(async ({ request }) => { + adminToken = await getAdminToken(request); + expect(adminToken, "Admin login must return an SSO token").toEqual(expect.any(String)); + expect(adminToken).toBeTruthy(); + await ensureProviderConfig(adminToken, request); + await writeClient(request, CONSENT_CLIENT_ID, { + "com.forgerock.openam.oauth2provider.grantTypes": ["[0]=authorization_code"], + }); + + // The provider enforces PKCE (codeVerifierEnforced defaults to true), so every response_type=code request below + // needs an S256 challenge, or it fails validation before a template is chosen. + challenge = (await pkce()).challenge; + + // The consent page names the resource owner by the provider's display name attribute, cn by default. CI creates + // demo with cn "Demo Demo"; a local embedded store keeps its own demo entry, so the name is read, not assumed. + const demo = await request.get(`${OPENAM_BASE}/json/realms/${REALM}/users/${USERNAME}`, { + headers: { iPlanetDirectoryPro: adminToken, "Accept-API-Version": "resource=3.0, protocol=2.1" }, + }); + if (!demo.ok()) { + throw new Error(`Failed to read ${USERNAME}: ${demo.status()} ${demo.statusText()} ${await demo.text()}`); + } + demoName = (await demo.json()).cn?.[0]; + if (!demoName) { + throw new Error(`${USERNAME} has no cn`); + } + + const loginCtx = await apiRequest.newContext({ ignoreHTTPSErrors: true }); + try { + demoToken = await getAuthToken(loginCtx, USERNAME, PASSWORD); + expect(demoToken, "Resource-owner login must return an SSO token").toEqual(expect.any(String)); + expect(demoToken).toBeTruthy(); + } finally { + await loginCtx.dispose(); + } + // /oauth2/authorize authenticates by the session cookie, never by the iPlanetDirectoryPro header. + demoCtx = await sessionContext(apiRequest, demoToken); +}); + +test.afterAll(async () => { + await demoCtx?.dispose(); +}); + +/** The authorize query, built by hand so the `display` value is the only thing that moves between tests. */ +function authorizeQuery(display) { + const parts = [ + "response_type=code", `client_id=${CONSENT_CLIENT_ID}`, + `redirect_uri=${encodeURIComponent(REDIRECT_URI)}`, `scope=${SCOPE}`, "state=display", + `code_challenge=${encodeURIComponent(challenge)}`, "code_challenge_method=S256", + ]; + if (display !== undefined) parts.push(`display=${display}`); + return parts.join("&"); +} + +/** + * A value the templates interpolate into the `pageData` object literal, scraped out of the rendered page. + * + * Anchored on a preceding delimiter: unanchored, `isplayName` would also match inside `displayName`, and the touch + * tests could no longer tell the two keys apart. + */ +function pageDataValue(html, key) { + const match = new RegExp(`(?:^|[{,\\s])${key}:\\s*"([^"]*)"`).exec(html); + return match && match[1]; +} + +/** ESAPI HTML-encodes the name before FreeMarker interpolates it; decode once as inert text, never markup. */ +async function userNameValue(page, html) { + return page.evaluate((encoded) => { + if (encoded === null) return null; + const text = document.createElement("textarea"); + text.innerHTML = encoded; + return text.value; + }, pageDataValue(html, "userName")); +} + +test.describe("?display= on /oauth2/authorize", () => { + + test("display=page renders the page/ consent template", async ({ page }) => { + const response = await demoCtx.get(`${OAUTH2}/authorize?${authorizeQuery("page")}`, { maxRedirects: 0 }); + const html = await response.text(); + console.log(`[display] page -> ${response.status()} ct=${response.headers()["content-type"]} bytes=${html.length}`); + + expect(response.status(), html).toBe(200); + // Every display is served as text/html, WML included: the template representation's media type does not vary + // by folder. + expect(response.headers()["content-type"]).toBe(HTML_TYPE); + // AuthorizeEndpointFilter stamps every /authorize answer, the consent page included. + expect(response.headers()["cache-control"]).toBe("no-store"); + expect(response.headers()["pragma"]).toBe("no-cache"); + + expect(html).toMatch(/^/); + // ConsentRequiredResource builds the model from the request's attributes and query plus its own keys. These are + // the ones this template reads. + expect(pageDataValue(html, "displayName")).toBe(CONSENT_CLIENT_ID); + expect(pageDataValue(html, "clientId")).toBe(CONSENT_CLIENT_ID); + expect(await userNameValue(page, html), "Consent must name the resource owner").toBe(demoName); + expect(pageDataValue(html, "responseType")).toBe("code"); + expect(pageDataValue(html, "redirectUri")).toBe(REDIRECT_URI); + expect(pageDataValue(html, "scope")).toBe(SCOPE); + expect(pageDataValue(html, "state")).toBe("display"); + expect(pageDataValue(html, "csrf")).toBeTruthy(); + // page/authorize.ftl is the only consent template with the saveConsentEnabled guard, which is why the popup and + // touch tests assert its absence: the cheapest proof that a different file was rendered. + expect(html).toContain("isSaveConsentEnabled: true"); + // The post-back target is the request's path and its raw query, display included, so a consent POST stays on the + // same template. ?js_string escapes the leading slash. + expect(pageDataValue(html, "formTarget"), "Consent target must preserve the raw authorize query") + .toBe(`\\${CONTEXT_PATH}/oauth2/authorize?${authorizeQuery("page")}`); + }); + + test("an EMPTY display= is the page/ template, not a 400", async () => { + // `?display=` is a reachable URL and reads back as an empty string. OAuth2Representation treats empty like + // absent and renders page/; Enum.valueOf("") would be the 400 of the unknown-display test. + const response = await demoCtx.get(`${OAUTH2}/authorize?${authorizeQuery("")}`, { maxRedirects: 0 }); + const html = await response.text(); + console.log(`[display] empty -> ${response.status()} bytes=${html.length}`); + + expect(response.status(), html).toBe(200); + expect(html).toMatch(/^/); + expect(pageDataValue(html, "displayName")).toBe(CONSENT_CLIENT_ID); + expect(html).toContain("isSaveConsentEnabled: true"); + }); + + test("an absent display defaults to the page/ consent template", async () => { + const response = await demoCtx.get(`${OAUTH2}/authorize?${authorizeQuery()}`, { maxRedirects: 0 }); + const html = await response.text(); + console.log(`[display] absent -> ${response.status()} bytes=${html.length}`); + + expect(response.status(), html).toBe(200); + expect(html).toContain("isSaveConsentEnabled: true"); + expect(pageDataValue(html, "displayName"), "Absent display must use the page template").toBe(CONSENT_CLIENT_ID); + }); + + test("display=popup composes the wrapper AROUND the consent page", async ({ page }) => { + const response = await demoCtx.get(`${OAUTH2}/authorize?${authorizeQuery("popup")}`, { maxRedirects: 0 }); + const html = await response.text(); + console.log(`[display] popup -> ${response.status()} bytes=${html.length}`); + + expect(response.status(), html).toBe(200); + expect(response.headers()["content-type"]).toBe(HTML_TYPE); + // popup.ftl's own doctype is lowercase where every other template's is uppercase: the cheapest discriminator for + // "the wrapper was rendered, not the bare page". + expect(html).toMatch(/^/); + expect(html).toContain("