From 98852b19e9ecd1bba1dc1225ff539648ffbdf73c Mon Sep 17 00:00:00 2001 From: kzoeps Date: Mon, 2 Nov 2026 23:27:03 +0600 Subject: [PATCH 1/2] tests/browser: cover TECH-683 sign-in, consent and confirm behaviour Adds Playwright cases for the account chooser, stale remembered devices, confirm-it's-you gaps, shared-email lookups, signup consent skip, email login_hint and prompt=none. The synthetic client gains an untrusted client and opts the secondary client into signup consent skip; the sandbox stack trusts primary + secondary. --- src/features/oauth-authorization/provider.mjs | 1 + .../stacks/hypercerts-entryway.yaml | 2 + tests/browser/account-chooser.spec.mjs | 168 ++++++++--------- tests/browser/account-confirm.spec.mjs | 136 ++++++++++++++ .../browser/oauth-remembered-device.spec.mjs | 150 ++++++++++++++++ tests/browser/oauth-sign-in-hints.spec.mjs | 170 ++++++++++++++++++ .../oauth-signup-consent-skip.spec.mjs | 89 +++++++++ tests/browser/shared-email-lookups.spec.mjs | 128 +++++++++++++ tests/browser/support/account-password.mjs | 13 ++ .../browser/support/email-chooser-fixture.mjs | 93 ++++++---- tests/browser/support/oauth-client.mjs | 59 ++++++ tests/browser/support/remembered-device.mjs | 37 ++++ .../contracts/provider-client-fetch.test.mjs | 2 + tests/fixtures/synthetic-client.mjs | 30 +++- tests/flows/account-device-lifecycle.md | 17 +- tests/flows/otp-client-oauth.md | 47 +++-- tests/playwright.config.mjs | 4 + 17 files changed, 985 insertions(+), 161 deletions(-) create mode 100644 tests/browser/oauth-remembered-device.spec.mjs create mode 100644 tests/browser/oauth-sign-in-hints.spec.mjs create mode 100644 tests/browser/oauth-signup-consent-skip.spec.mjs create mode 100644 tests/browser/shared-email-lookups.spec.mjs create mode 100644 tests/browser/support/account-password.mjs create mode 100644 tests/browser/support/oauth-client.mjs create mode 100644 tests/browser/support/remembered-device.mjs diff --git a/src/features/oauth-authorization/provider.mjs b/src/features/oauth-authorization/provider.mjs index 9e82a0af..44216dde 100644 --- a/src/features/oauth-authorization/provider.mjs +++ b/src/features/oauth-authorization/provider.mjs @@ -20,6 +20,7 @@ export function createClientMetadataFetch({ const localMetadata = new Set([ `${localOrigin}/client-metadata.json`, `${localOrigin}/client-metadata-secondary.json`, + `${localOrigin}/client-metadata-untrusted.json`, ]); const browserMetadata = config.browserClientMetadataUrl; if (browserMetadata) { diff --git a/tests/atmosphere/stacks/hypercerts-entryway.yaml b/tests/atmosphere/stacks/hypercerts-entryway.yaml index 1255e7e8..78384c22 100644 --- a/tests/atmosphere/stacks/hypercerts-entryway.yaml +++ b/tests/atmosphere/stacks/hypercerts-entryway.yaml @@ -56,6 +56,8 @@ services: MAIL_SMTP_HOST: mail-capture MAIL_SMTP_PORT: "2525" BROWSER_CLIENT_METADATA_URL: https://browser.atmosbox.internal/oauth-client-metadata.json + # Replaces the built-in default (primary only); untrusted is left out on purpose. + OAUTH_TRUSTED_CLIENTS: https://client.entryway.example.com/client-metadata.json,https://client.entryway.example.com/client-metadata-secondary.json SOURCE_FIXTURE_URL: http://source-fixture:3313 SOURCE_FIXTURE_TOKEN_FILE: /run/secrets/source-fixture-token depends_on: diff --git a/tests/browser/account-chooser.spec.mjs b/tests/browser/account-chooser.spec.mjs index d5329366..d610b5f2 100644 --- a/tests/browser/account-chooser.spec.mjs +++ b/tests/browser/account-chooser.spec.mjs @@ -1,63 +1,39 @@ import { test, expect } from "@playwright/test"; -import { readFileSync } from "node:fs"; -import { waitForMailpitCode } from "../support/helpers/mailpit.mjs"; +import { createSharedEmailPair } from "./support/email-chooser-fixture.mjs"; import { - bindAccountsToSharedEmail, - createRealAccount, -} from "./support/email-chooser-fixture.mjs"; + beginAuthorization, + config, + consentForm, + finishConsent, + requestVisibleCode, + selectionForm, + verifyVisibleCode, +} from "./support/oauth-client.mjs"; -const config = JSON.parse( - readFileSync( - process.env.SERVICE_CONFIG_PATH ?? "./.runtime/config.json", - "utf8", - ), -); -const databasePath = - process.env.TEST_ACCOUNT_DATABASE_PATH ?? - "/entryway-data/account-authority.sqlite"; const runId = Date.now().toString(36); +let shared; -function consentForm(page, did) { - return page - .locator('form[action="/auth/consent"]') - .filter({ has: page.locator(`input[name="did"][value="${did}"]`) }); -} +test.describe.configure({ mode: "serial" }); -function selectionForm(page, did) { - return page - .locator('form[action="/auth/select"]') - .filter({ has: page.locator(`input[name="did"][value="${did}"]`) }); -} +test.beforeAll(async ({ browser }) => { + test.setTimeout(180_000); + shared = await createSharedEmailPair(browser, { prefix: "ch", runId }); +}); -async function beginAuthorization(page, { prompt = "consent" } = {}) { - const login = new URL("/client/login", config.clientUrl); - login.searchParams.set("identifier", config.issuer); - login.searchParams.set("client", "primary"); - login.searchParams.set("prompt", prompt); - await page.goto(login.href); +/** Open the client sign-in and verify the shared email, ending at the chooser. */ +async function reachChooser(page) { + await beginAuthorization(page, { prompt: "consent" }); await expect(page.getByLabel("Email address")).toBeVisible(); -} + const message = await requestVisibleCode(page, shared.email); + const beforeProof = await page.content(); + for (const account of [shared.first, shared.second]) + expect(beforeProof).not.toContain(account.did); + await expect(page.locator('form[action="/auth/select"]')).toHaveCount(0); -async function requestVisibleCode(page, email) { - const since = Date.now(); - await page.getByLabel("Email address").fill(email); - await page.getByRole("button", { name: "Send sign-in code" }).click(); + await verifyVisibleCode(page, message.code); await expect( - page.getByRole("heading", { name: "Check your email" }), + page.getByRole("heading", { name: "Choose an account" }), ).toBeVisible(); - return waitForMailpitCode({ recipient: email, since }); -} - -async function verifyVisibleCode(page, code) { - await page.getByLabel("Sign-in code").fill(code); - await page.getByRole("button", { name: "Verify code" }).click(); -} - -async function finishConsent(page, did) { - await consentForm(page, did) - .getByRole("button", { name: "Allow access" }) - .click(); - await expect(page.getByTestId("signed-in-did")).toHaveText(did); } async function assertOAuthSubjectAndWrite(page, account) { @@ -82,35 +58,30 @@ async function assertOAuthSubjectAndWrite(page, account) { expect((await write.json()).uri).toContain(`at://${account.did}/`); } -async function selectAndAuthorize(browser, email, accounts, selected) { +test("verified-email chooser selects each real DID after OTP and keeps OAuth writes account-scoped", async ({ + browser, +}) => { + test.setTimeout(180_000); + const { first, second } = shared; const context = await browser.newContext({ ignoreHTTPSErrors: false }); try { const page = await context.newPage(); - await beginAuthorization(page); - const message = await requestVisibleCode(page, email); - - const beforeProof = await page.content(); - for (const account of accounts) - expect(beforeProof).not.toContain(account.did); - await expect(page.locator('form[action="/auth/select"]')).toHaveCount(0); - - await verifyVisibleCode(page, message.code); - await expect( - page.getByRole("heading", { name: "Choose an account" }), - ).toBeVisible(); + await reachChooser(page); await expect(page.locator('form[action="/auth/select"]')).toHaveCount(2); - for (const account of accounts) + for (const account of [first, second]) await expect(selectionForm(page, account.did)).toHaveCount(1); - const form = selectionForm(page, selected.did); + // Choosing the second, non-default DID on another PDS proves the chooser + // continues the selected account rather than the first binding. + const form = selectionForm(page, second.did); const submitted = await form.evaluate((element) => Object.fromEntries(new FormData(element).entries()), ); await form.getByRole("button").click(); - await expect(consentForm(page, selected.did)).toBeVisible(); + await expect(consentForm(page, second.did)).toBeVisible(); - await finishConsent(page, selected.did); + await finishConsent(page, second.did); const replay = await page.request.post(`${config.issuer}/auth/select`, { maxRedirects: 0, headers: { origin: config.issuer }, @@ -118,41 +89,48 @@ async function selectAndAuthorize(browser, email, accounts, selected) { }); expect(replay.status()).toBe(400); expect(await replay.text()).toContain("This sign-in has expired"); - await assertOAuthSubjectAndWrite(page, selected); + await assertOAuthSubjectAndWrite(page, second); } finally { await context.close(); } -} +}); -test("verified-email chooser selects each real DID after OTP and keeps OAuth writes account-scoped", async ({ +test("each linked account has its own button and status, and consent can return to the chooser", async ({ browser, }) => { test.setTimeout(180_000); - const sharedEmail = `chooser-${runId}-shared@example.test`; - const first = { - email: sharedEmail, - handle: `ch-${runId}-o.entryway.atmosbox.test`, - pdsId: "pds1", - }; - const second = { - email: `chooser-${runId}-second@example.test`, - handle: `ch-${runId}-t.entryway.atmosbox.test`, - pdsId: "pds2", - }; - await createRealAccount(browser, first); - await createRealAccount(browser, second); - - await bindAccountsToSharedEmail({ - first, - second, - email: sharedEmail, - databasePath, - }); + const { first, second } = shared; + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + await reachChooser(page); + for (const account of [first, second]) { + const option = page + .locator("div.account") + .filter({ has: selectionForm(page, account.did) }); + await expect(option).toContainText(account.handle); + await expect(option).toContainText(`${account.did} · active`); + await expect( + option.getByRole("button", { name: "Continue with this account" }), + ).toHaveCount(1); + } + + await selectionForm(page, first.did).getByRole("button").click(); + await expect(consentForm(page, first.did)).toBeVisible(); + await page + .getByRole("button", { name: "Choose a different account" }) + .click(); + await expect( + page.getByRole("heading", { name: "Choose an account" }), + ).toBeVisible(); + await expect(page.locator('form[action="/auth/select"]')).toHaveCount(2); - // Each DID completes its own fresh journey after the email is shared, so a - // regression that issues the wrong subject for either account fails here. - // The second DID lives on another PDS, proving the chooser continues the - // selected account rather than the first binding. - for (const selected of [first, second]) - await selectAndAuthorize(browser, sharedEmail, [first, second], selected); + await selectionForm(page, second.did).getByRole("button").click(); + await expect(consentForm(page, second.did)).toBeVisible(); + await expect(consentForm(page, first.did)).toHaveCount(0); + // The client shows the last chosen account, not the first one. + await finishConsent(page, second.did); + } finally { + await context.close(); + } }); diff --git a/tests/browser/account-confirm.spec.mjs b/tests/browser/account-confirm.spec.mjs index 9118cc62..6b809b1f 100644 --- a/tests/browser/account-confirm.spec.mjs +++ b/tests/browser/account-confirm.spec.mjs @@ -2,6 +2,7 @@ import { test, expect } from "@playwright/test"; import { DatabaseSync } from "node:sqlite"; import { readFileSync } from "node:fs"; import { waitForMailpitCode } from "../support/helpers/mailpit.mjs"; +import { setAccountPassword } from "./support/account-password.mjs"; test.use({ trace: "off", screenshot: "off", video: "off" }); @@ -29,6 +30,21 @@ const midFlow = { pdsId: "pds2", }; const midFlowBackupEmail = `midflow-backup-${run}@example.com`; +const lockout = { + email: `lockout-${run}@example.com`, + handle: `lockout-${run}.entryway.atmosbox.test`, + pdsId: "pds1", +}; +const exempt = { + email: `exempt-${run}@example.com`, + handle: `exempt-${run}.entryway.atmosbox.test`, + pdsId: "pds1", +}; +const passwordChange = { + email: `pwchange-${run}@example.com`, + handle: `pwchange-${run}.entryway.atmosbox.test`, + pdsId: "pds2", +}; const accountForm = (page, action) => page.locator(`form[action="/account/${action}"]`); @@ -314,3 +330,123 @@ test("a change submitted after the ten-minute window is not made; the user confi await context.close(); } }); + +test("five wrong codes lock a confirmation code until a new one is sent", async ({ + browser, +}) => { + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + const page = await context.newPage(); + try { + await signIn(page, lockout, { create: true }); + ageSessions(lockout.email, 11); + await page.getByRole("link", { name: "Set account password" }).click(); + await expect( + page.getByRole("heading", { name: "Confirm it's you" }), + ).toBeVisible(); + + const since = Date.now(); + await page.getByRole("button", { name: "Send code" }).click(); + const sent = await waitForMailpitCode({ + recipient: lockout.email, + since, + }); + const wrong = sent.code === "00000000" ? "11111111" : "00000000"; + const submit = async (code) => { + await page.getByLabel("Confirmation code").fill(code); + const response = posted(page, "/account/confirm"); + await page.getByRole("button", { name: "Confirm and continue" }).click(); + expect((await response).status()).toBe(400); + await expect(page.getByRole("alert")).toContainText( + "Invalid or already used token", + ); + }; + for (let guess = 0; guess < 5; guess++) await submit(wrong); + // The code is spent: even the right one no longer works. + await submit(sent.code); + + const resendSince = Date.now(); + await page.getByRole("button", { name: "Send a new code" }).click(); + await expect(page.getByText("We sent a new code")).toBeVisible(); + const fresh = await waitForMailpitCode({ + recipient: lockout.email, + since: resendSince, + excludeIds: [sent.messageId], + }); + await page.getByLabel("Confirmation code").fill(fresh.code); + await page.getByRole("button", { name: "Confirm and continue" }).click(); + await expect( + accountForm(page, "password-set").getByLabel("New account password"), + ).toBeVisible(); + } finally { + await context.close(); + } +}); + +test("a session past the ten-minute window still revokes app passwords, changes the handle and starts deletion without confirming", async ({ + browser, +}) => { + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + const page = await context.newPage(); + const appPassword = `Exempt ${run}`; + const handle = `chg-${run}.entryway.atmosbox.test`; + const confirmHeading = page.getByRole("heading", { + name: "Confirm it's you", + }); + try { + await signIn(page, exempt, { create: true }); + await page.getByRole("link", { name: "Create app password" }).click(); + await accountForm(page, "app-password-create") + .getByLabel("App password name") + .fill(appPassword); + await accountForm(page, "app-password-create").getByRole("button").click(); + await expect( + page.getByRole("heading", { name: "App password created" }), + ).toBeVisible(); + + ageSessions(exempt.email, 11); + await page.goto(new URL("/account", config.issuer).href); + const row = page.locator("#passwords li").filter({ hasText: appPassword }); + await row.getByRole("button", { name: "Revoke app password" }).click(); + await expect(page.locator("#passwords")).not.toContainText(appPassword); + await expect(confirmHeading).toHaveCount(0); + + await page.getByLabel("New handle").fill(handle); + await page.getByRole("button", { name: "Update handle" }).click(); + await expect(page.locator("main")).toContainText(handle); + await expect(confirmHeading).toHaveCount(0); + + await page + .getByLabel("Type your handle to delete this test account") + .fill(handle); + await page.getByRole("button", { name: "Delete test account" }).click(); + await expect( + page.getByRole("heading", { name: "Confirm account deletion" }), + ).toBeVisible(); + } finally { + await context.close(); + } +}); + +test("changing an existing password asks only for the new one", async ({ + browser, +}) => { + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + const page = await context.newPage(); + try { + await signIn(page, passwordChange, { create: true }); + await page.getByRole("link", { name: "Set account password" }).click(); + await setAccountPassword(page, `First password ${run}!`); + + // Setting a password signs every session out; a fresh sign-in is enough + // proof to change it, with no current password. + await signIn(page, passwordChange); + await page.getByRole("link", { name: "Change account password" }).click(); + await expect( + accountForm(page, "password-set").getByLabel("New account password"), + ).toBeVisible(); + await expect(page.getByLabel(/current password/i)).toHaveCount(0); + await setAccountPassword(page, `Second password ${run}!`); + } finally { + await context.close(); + } +}); diff --git a/tests/browser/oauth-remembered-device.spec.mjs b/tests/browser/oauth-remembered-device.spec.mjs new file mode 100644 index 00000000..76b7daab --- /dev/null +++ b/tests/browser/oauth-remembered-device.spec.mjs @@ -0,0 +1,150 @@ +import { test, expect } from "@playwright/test"; +import { waitForMailpitCode } from "../support/helpers/mailpit.mjs"; +import { + createSharedEmailPair, + signUpOnPage, +} from "./support/email-chooser-fixture.mjs"; +import { + beginAuthorization, + config, + consentForm, + databasePath, + finishConsent, + requestVisibleCode, + selectionForm, + verifyVisibleCode, +} from "./support/oauth-client.mjs"; +import { ageRememberedAccount } from "./support/remembered-device.mjs"; + +const runId = Date.now().toString(36); +const emailCodeButton = (page) => + page.getByRole("button", { name: "Sign in with an email code" }); +const rememberedLogin = (page, did) => + page + .locator('form[action="/auth/remembered-login"]') + .filter({ has: page.locator(`input[name="did"][value="${did}"]`) }); + +// select_account makes the authorization page list the device's accounts. +const listRememberedAccounts = (page) => + beginAuthorization(page, { prompt: "select_account" }); + +test("a remembered device older than seven days sends its code without asking for or showing the address", async ({ + browser, +}) => { + test.setTimeout(120_000); + const localPart = `remember-${runId}`; + const account = { + email: `${localPart}@example.test`, + handle: `rd-${runId}.entryway.atmosbox.test`, + pdsId: "pds1", + }; + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + await signUpOnPage(page, account); + + // A fresh device keeps one-click consent. + await listRememberedAccounts(page); + await expect(consentForm(page, account.did)).toBeVisible(); + await expect(emailCodeButton(page)).toHaveCount(0); + + ageRememberedAccount(account.did, databasePath); + await listRememberedAccounts(page); + await expect(emailCodeButton(page)).toBeVisible(); + await expect(consentForm(page, account.did)).toHaveCount(0); + + // Choosing the account sends the code to its own email, never typed here. + const since = Date.now(); + await emailCodeButton(page).click(); + await expect( + page.getByRole("heading", { name: "Check your email" }), + ).toBeVisible(); + await expect(page.locator("#otp-help strong")).toHaveText( + `r••••@example.test`, + ); + await expect(page.locator("#change-email")).toHaveValue(""); + const html = await page.content(); + expect(html).not.toContain(account.email); + expect(html).not.toContain(localPart); + + const message = await waitForMailpitCode({ + recipient: account.email, + since, + }); + await verifyVisibleCode(page, message.code); + await expect(consentForm(page, account.did)).toBeVisible(); + await finishConsent(page, account.did); + + // The proof renews the device: the account is one click away again. + await listRememberedAccounts(page); + await expect(consentForm(page, account.did)).toBeVisible(); + await expect(emailCodeButton(page)).toHaveCount(0); + } finally { + await context.close(); + } +}); + +test("with a shared email the code only continues the selected remembered account", async ({ + browser, +}) => { + test.setTimeout(180_000); + const { email, first, second } = await createSharedEmailPair(browser, { + prefix: "rs", + runId, + }); + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + // Remember both accounts on this device through the verified-email chooser. + for (const [account, begin] of [ + [first, {}], + [second, { prompt: "select_account" }], + ]) { + await beginAuthorization(page, begin); + const message = await requestVisibleCode(page, email); + await verifyVisibleCode(page, message.code); + await selectionForm(page, account.did).getByRole("button").click(); + await finishConsent(page, account.did); + } + + ageRememberedAccount(first.did, databasePath); + await listRememberedAccounts(page); + await expect(rememberedLogin(page, first.did)).toHaveCount(1); + await expect(consentForm(page, second.did)).toBeVisible(); + + const since = Date.now(); + await rememberedLogin(page, first.did).getByRole("button").click(); + const message = await waitForMailpitCode({ recipient: email, since }); + await verifyVisibleCode(page, message.code); + + // The shared email still goes through the chooser, which offers only the + // selected account; the sibling is neither listed nor accepted. + await expect( + page.getByRole("heading", { name: "Choose an account" }), + ).toBeVisible(); + await expect(page.locator('form[action="/auth/select"]')).toHaveCount(1); + await expect(selectionForm(page, second.did)).toHaveCount(0); + const submitted = await selectionForm(page, first.did).evaluate((element) => + Object.fromEntries(new FormData(element).entries()), + ); + const sibling = await page.request.post(`${config.issuer}/auth/select`, { + maxRedirects: 0, + headers: { origin: config.issuer }, + form: { ...submitted, did: second.did }, + }); + expect(sibling.status()).toBe(400); + + await selectionForm(page, first.did).getByRole("button").click(); + await expect(consentForm(page, first.did)).toBeVisible(); + await expect(consentForm(page, second.did)).toHaveCount(0); + await page + .getByRole("button", { name: "Choose a different account" }) + .click(); + await expect(page.locator('form[action="/auth/select"]')).toHaveCount(1); + await expect(selectionForm(page, second.did)).toHaveCount(0); + await selectionForm(page, first.did).getByRole("button").click(); + await finishConsent(page, first.did); + } finally { + await context.close(); + } +}); diff --git a/tests/browser/oauth-sign-in-hints.spec.mjs b/tests/browser/oauth-sign-in-hints.spec.mjs new file mode 100644 index 00000000..95d30b13 --- /dev/null +++ b/tests/browser/oauth-sign-in-hints.spec.mjs @@ -0,0 +1,170 @@ +import { test, expect } from "@playwright/test"; +import { waitForMailpitCode } from "../support/helpers/mailpit.mjs"; +import { authorizeBrowserApp } from "../support/helpers/browser-oauth.mjs"; +import { signUpOnPage } from "./support/email-chooser-fixture.mjs"; +import { + beginAuthorization, + config, + consentForm, + finishConsent, + verifyVisibleCode, +} from "./support/oauth-client.mjs"; + +const runId = Date.now().toString(36); +const account = { + email: `hint-${runId}@example.test`, + handle: `hn-${runId}.entryway.atmosbox.test`, + pdsId: "pds1", +}; +const callbackPattern = (client) => + new RegExp(`/client/callback${client === "primary" ? "" : `/${client}`}\\?`); + +test.describe.configure({ mode: "serial" }); + +let context; +let page; +test.beforeAll(async ({ browser }) => { + test.setTimeout(120_000); + context = await browser.newContext({ ignoreHTTPSErrors: false }); + page = await context.newPage(); + // This device remembers the account and has approved the primary client. + await signUpOnPage(page, account); +}); +test.afterAll(async () => context?.close()); + +/** Start an authorization and return the error the client's callback received. */ +async function callbackError(options) { + const callback = page.waitForRequest((request) => + callbackPattern(options.client ?? "primary").test(request.url()), + ); + await beginAuthorization(page, options); + return new URL((await callback).url()).searchParams.get("error"); +} + +test.describe("email login_hint on the authorize redirect", () => { + // A new device has no remembered account, so only the hint decides the page. + let fresh; + test.beforeEach(async ({ browser }) => { + fresh = await ( + await browser.newContext({ ignoreHTTPSErrors: false }) + ).newPage(); + }); + test.afterEach(async () => fresh.context().close()); + + test("an email entered on the client lands on the code page with the code already sent", async () => { + const since = Date.now(); + await fresh.goto(`${config.clientUrl}/client?client=primary`); + await fresh + .getByLabel("Email (optional, with an authorization server)") + .fill(account.email); + await fresh.getByRole("button", { name: "Sign in", exact: true }).click(); + await expect( + fresh.getByRole("heading", { name: "Check your email" }), + ).toBeVisible(); + await expect(fresh.locator("#otp-help strong")).toHaveText(account.email); + const message = await waitForMailpitCode({ + recipient: account.email, + since, + }); + await verifyVisibleCode(fresh, message.code); + await expect(consentForm(fresh, account.did)).toBeVisible(); + await finishConsent(fresh, account.did); + }); + + test("an invalid or injection-style email falls back to the sign-in page and sends nothing", async () => { + const since = Date.now(); + const victim = `victim-${runId}@example.test`; + await beginAuthorization(fresh, { email: `${victim}">` }); + await expect( + fresh.getByRole("heading", { name: "Sign in to authorize" }), + ).toBeVisible(); + await expect(fresh.getByLabel("Email address")).toBeVisible(); + expect((await fresh.content()).toLowerCase()).not.toContain( + `victim-${runId}`, + ); + await expect( + waitForMailpitCode({ recipient: victim, since, timeoutMs: 2_000 }), + ).rejects.toThrow("Timed out"); + }); + + test("a handle hint from the pushed request wins over an email on the redirect", async () => { + const since = Date.now(); + const ignored = `ignored-${runId}@example.test`; + await beginAuthorization(fresh, { + identifier: account.handle, + email: ignored, + }); + await expect( + fresh.getByRole("heading", { name: "Sign in to authorize" }), + ).toBeVisible(); + await expect(fresh.getByLabel("Email address")).toBeVisible(); + await expect( + waitForMailpitCode({ recipient: ignored, since, timeoutMs: 2_000 }), + ).rejects.toThrow("Timed out"); + }); +}); + +test.describe("prompt=none", () => { + test("a remembered approved account signs in silently from its handle", async () => { + const entrywayPages = []; + const record = (response) => { + if ( + response.request().resourceType() === "document" && + response.url().startsWith(config.issuer) + ) + entrywayPages.push(response.status()); + }; + page.on("response", record); + await beginAuthorization(page, { + identifier: account.handle, + prompt: "none", + }); + await expect(page.getByTestId("signed-in-did")).toHaveText(account.did); + page.off("response", record); + expect(entrywayPages.length).toBeGreaterThan(0); + // Entryway only redirected: it never rendered a page of its own. + expect(entrywayPages.every((status) => status >= 300 && status < 400)).toBe( + true, + ); + }); + + test("a client the account never approved gets consent_required", async () => { + const error = await callbackError({ + client: "untrusted", + identifier: account.handle, + prompt: "none", + }); + expect(error).toBe("consent_required"); + }); + + test("without a hint the client gets login_required", async () => { + expect(await callbackError({ prompt: "none" })).toBe("login_required"); + }); + + test("an untrusted public client is refused silent sign-in", async () => { + await authorizeBrowserApp(page, account); + // The SDK page offers no "none" choice, so add it to its prompt list. + await page + .locator("#reauthorize-prompt") + .evaluate((select) => select.add(new Option("none", "none"))); + await page + .getByLabel("Authorize another handle or DID") + .fill(account.handle); + await page.getByLabel("Account prompt").selectOption("none"); + const par = page.waitForResponse( + (response) => + response.url() === `${config.issuer}/oauth/par` && + response.request().method() === "POST", + ); + await page + .getByRole("button", { name: "Start another authorization" }) + .click(); + // Entryway refuses the pushed request itself, so the browser never leaves + // the client. + expect((await par).status()).toBe(400); + await expect(page.locator("#reauthorize-error")).toContainText( + "Public clients are not allowed to use silent-sign-on", + ); + await expect(page.locator("#verified-did")).toHaveText(account.did); + }); +}); diff --git a/tests/browser/oauth-signup-consent-skip.spec.mjs b/tests/browser/oauth-signup-consent-skip.spec.mjs new file mode 100644 index 00000000..289b91d9 --- /dev/null +++ b/tests/browser/oauth-signup-consent-skip.spec.mjs @@ -0,0 +1,89 @@ +import { test, expect } from "@playwright/test"; +import { startSignup } from "./support/email-chooser-fixture.mjs"; +import { + beginAuthorization, + config, + consentForm, + finishConsent, + requestVisibleCode, + verifyVisibleCode, +} from "./support/oauth-client.mjs"; + +// The sandbox trusts the primary and secondary clients. Both secondary and +// untrusted opt in to the signup skip; primary does not, and every other +// signup case already asserts its consent page. +const runId = Date.now().toString(36); +const skipped = { + email: `skip-${runId}@example.test`, + handle: `sk-${runId}.entryway.atmosbox.test`, + pdsId: "pds1", +}; +const untrusted = { + email: `skip-${runId}-untrusted@example.test`, + handle: `su-${runId}.entryway.atmosbox.test`, + pdsId: "pds1", +}; + +test.describe.configure({ mode: "serial" }); + +test("a new account signing up through a trusted client that opts in lands signed in without consent", async ({ + browser, +}) => { + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + await startSignup(page, skipped, { client: "secondary" }); + await expect(page.getByTestId("signed-in-did")).toBeVisible(); + expect(new URL(page.url()).origin).toBe(new URL(config.clientUrl).origin); + const session = await ( + await page.request.get( + `${config.clientUrl}/client/session?client=secondary`, + ) + ).json(); + expect(session.session.handle).toBe(skipped.handle); + skipped.did = session.did; + } finally { + await context.close(); + } +}); + +test("a client that opts in without being trusted still shows consent on signup", async ({ + browser, +}) => { + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + await startSignup(page, untrusted, { client: "untrusted" }); + await expect( + page.getByRole("heading", { name: "Authorize application" }), + ).toBeVisible(); + await expect( + page.getByText("Hypercerts untrusted test client"), + ).toBeVisible(); + untrusted.did = await page + .locator('form[action="/auth/consent"] input[name="did"]') + .inputValue(); + await finishConsent(page, untrusted.did); + } finally { + await context.close(); + } +}); + +test("a returning account on the trusted client that opts in still sees consent", async ({ + browser, +}) => { + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + await beginAuthorization(page, { client: "secondary" }); + const message = await requestVisibleCode(page, skipped.email); + await verifyVisibleCode(page, message.code); + await expect( + page.getByRole("heading", { name: "Authorize application" }), + ).toBeVisible(); + await expect(consentForm(page, skipped.did)).toBeVisible(); + await finishConsent(page, skipped.did); + } finally { + await context.close(); + } +}); diff --git a/tests/browser/shared-email-lookups.spec.mjs b/tests/browser/shared-email-lookups.spec.mjs new file mode 100644 index 00000000..56558f9a --- /dev/null +++ b/tests/browser/shared-email-lookups.spec.mjs @@ -0,0 +1,128 @@ +import { test, expect } from "@playwright/test"; +import { waitForMailpitCode } from "../support/helpers/mailpit.mjs"; +import { createAccount } from "../support/helpers/browser-oauth.mjs"; +import { setAccountPassword } from "./support/account-password.mjs"; +import { bindAccountsToSharedEmail } from "./support/email-chooser-fixture.mjs"; +import { + config, + databasePath, + requestVisibleCode, + verifyVisibleCode, +} from "./support/oauth-client.mjs"; + +const runId = Date.now().toString(36); +const password = `Shared lookups ${runId} password!`; +const xrpc = (name) => `${config.issuer}/xrpc/com.atproto.server.${name}`; +const unknownEmail = `nobody-${runId}@example.test`; + +let first; +let second; +let single; +let apiContext; +let api; + +async function createAccountInNewContext(browser, label, { withPassword }) { + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + const account = await createAccount(page, label); + if (withPassword) { + await page.locator('a[href^="/account/manage/password?"]').click(); + await setAccountPassword(page, password); + } + return account; + } finally { + await context.close(); + } +} + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ browser }) => { + test.setTimeout(180_000); + first = await createAccountInNewContext(browser, "lookup-a", { + withPassword: true, + }); + second = await createAccountInNewContext(browser, "lookup-b", { + withPassword: true, + }); + single = await createAccountInNewContext(browser, "lookup-c", { + withPassword: false, + }); + await bindAccountsToSharedEmail({ + first, + second: { ...second, pdsId: config.pds[0].id }, + email: first.email, + databasePath, + }); + apiContext = await browser.newContext({ ignoreHTTPSErrors: false }); + api = apiContext.request; +}); + +test.afterAll(async () => apiContext?.close()); + +test("password login with a shared email fails like an unknown email while handle and DID sign in", async () => { + const login = (identifier) => + api.post(xrpc("createSession"), { data: { identifier, password } }); + + const unknown = await login(unknownEmail); + expect(unknown.status()).toBe(401); + const shared = await login(first.email); + expect(shared.status()).toBe(401); + expect(await shared.json()).toEqual(await unknown.json()); + + for (const [identifier, did] of [ + [first.handle, first.did], + [first.did, first.did], + [second.handle, second.did], + [second.did, second.did], + ]) { + const session = await login(identifier); + expect(session.ok(), identifier).toBe(true); + expect((await session.json()).did).toBe(did); + } +}); + +test("password reset for a shared email sends no mail, unlike a single-account email", async () => { + const reset = (email) => + api.post(xrpc("requestPasswordReset"), { data: { email } }); + + const controlSince = Date.now(); + expect((await reset(single.email)).ok()).toBe(true); + await waitForMailpitCode({ recipient: single.email, since: controlSince }); + + const since = Date.now(); + const shared = await reset(first.email); + expect(shared.ok()).toBe(true); + expect(await shared.json()).toEqual(await (await reset(unknownEmail)).json()); + await expect( + waitForMailpitCode({ recipient: first.email, since, timeoutMs: 2_000 }), + ).rejects.toThrow("Timed out"); +}); + +test("signup with a shared email returns AccountExists", async ({ + browser, +}) => { + // A browser session verified for the shared email can ask to sign up with it. + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + await page.goto(`${config.issuer}/login`); + const message = await requestVisibleCode(page, first.email); + await verifyVisibleCode(page, message.code); + await expect( + page.getByRole("heading", { name: "Choose an account" }), + ).toBeVisible(); + const signup = await page.request.post(xrpc("createAccount"), { + data: { + email: first.email, + handle: `sl-${runId}.entryway.atmosbox.test`, + pdsId: config.pds[0].id, + }, + }); + expect(signup.status()).toBe(409); + expect((await signup.json()).error).toBe("AccountExists"); + } finally { + await context.close(); + } +}); diff --git a/tests/browser/support/account-password.mjs b/tests/browser/support/account-password.mjs new file mode 100644 index 00000000..2f1715c9 --- /dev/null +++ b/tests/browser/support/account-password.mjs @@ -0,0 +1,13 @@ +import { expect } from "@playwright/test"; + +/** Set the account password from the open "Set/Change account password" page. */ +export async function setAccountPassword(page, value) { + await page.getByLabel("New account password").fill(value); + await page + .locator('form[action="/account/password-set"]') + .getByRole("button") + .click(); + await expect( + page.getByRole("heading", { name: "Account password updated" }), + ).toBeVisible(); +} diff --git a/tests/browser/support/email-chooser-fixture.mjs b/tests/browser/support/email-chooser-fixture.mjs index 98a5038e..cfbda4e8 100644 --- a/tests/browser/support/email-chooser-fixture.mjs +++ b/tests/browser/support/email-chooser-fixture.mjs @@ -1,57 +1,74 @@ import { expect } from "@playwright/test"; -import { readFileSync } from "node:fs"; import { createAccounts } from "../../../dist/src/compose-accounts.mjs"; import { openDatabase } from "../../../dist/src/database/connection.js"; -import { waitForMailpitCode } from "../../support/helpers/mailpit.mjs"; - -const config = JSON.parse( - readFileSync( - process.env.SERVICE_CONFIG_PATH ?? "./.runtime/config.json", - "utf8", - ), -); +import { + beginAuthorization, + config, + databasePath, + requestVisibleCode, +} from "./oauth-client.mjs"; -async function requestVisibleCode(page, email) { - const since = Date.now(); - await page.getByLabel("Email address").fill(email); - await page.getByRole("button", { name: "Send sign-in code" }).click(); +/** + * Sign up `account` through an OAuth client and stop after "Create account", + * so callers can assert what follows: a consent page, or straight back to the + * client when a trusted client skips consent on signup. + */ +export async function startSignup(page, account, { client = "primary" } = {}) { + await beginAuthorization(page, { client, prompt: "create" }); + await expect(page.getByLabel("Email address")).toBeVisible(); + const message = await requestVisibleCode(page, account.email); + await page.getByLabel("Sign-in code").fill(message.code); + await page.getByRole("button", { name: "Verify code" }).click(); await expect( - page.getByRole("heading", { name: "Check your email" }), + page.getByRole("heading", { name: "Create your account" }), ).toBeVisible(); - return waitForMailpitCode({ recipient: email, since }); + await page.getByLabel("Handle", { exact: true }).fill(account.handle); + await page.getByLabel("Personal data server").selectOption(account.pdsId); + await page.getByRole("button", { name: "Create account" }).click(); +} + +/** Complete a primary-client signup, including consent, on `page`. */ +export async function signUpOnPage(page, account) { + await startSignup(page, account); + const consent = page.locator('form[action="/auth/consent"]'); + await expect(consent).toBeVisible(); + account.did = await consent.locator('input[name="did"]').inputValue(); + await consent.getByRole("button", { name: "Allow access" }).click(); + await expect(page.getByTestId("signed-in-did")).toHaveText(account.did); + return account; } export async function createRealAccount(browser, account) { const context = await browser.newContext({ ignoreHTTPSErrors: false }); try { - const page = await context.newPage(); - const login = new URL("/client/login", config.clientUrl); - login.searchParams.set("identifier", config.issuer); - login.searchParams.set("client", "primary"); - login.searchParams.set("prompt", "create"); - await page.goto(login.href); - await expect(page.getByLabel("Email address")).toBeVisible(); - - const message = await requestVisibleCode(page, account.email); - await page.getByLabel("Sign-in code").fill(message.code); - await page.getByRole("button", { name: "Verify code" }).click(); - await expect( - page.getByRole("heading", { name: "Create your account" }), - ).toBeVisible(); - await page.getByLabel("Handle", { exact: true }).fill(account.handle); - await page.getByLabel("Personal data server").selectOption(account.pdsId); - await page.getByRole("button", { name: "Create account" }).click(); - const consent = page.locator('form[action="/auth/consent"]'); - await expect(consent).toBeVisible(); - account.did = await consent.locator('input[name="did"]').inputValue(); - await consent.getByRole("button", { name: "Allow access" }).click(); - await expect(page.getByTestId("signed-in-did")).toHaveText(account.did); - return account; + return await signUpOnPage(await context.newPage(), account); } finally { await context.close(); } } +/** + * Two real accounts on different PDSs that share `email` the way migration or + * import shares it. Handles stay within the 18-character label limit. + */ +export async function createSharedEmailPair(browser, { prefix, runId }) { + const email = `${prefix}-${runId}-shared@example.test`; + const first = { + email, + handle: `${prefix}-${runId}-o.entryway.atmosbox.test`, + pdsId: "pds1", + }; + const second = { + email: `${prefix}-${runId}-second@example.test`, + handle: `${prefix}-${runId}-t.entryway.atmosbox.test`, + pdsId: "pds2", + }; + await createRealAccount(browser, first); + await createRealAccount(browser, second); + await bindAccountsToSharedEmail({ first, second, email, databasePath }); + return { email, first, second }; +} + export async function bindAccountsToSharedEmail({ first, second, diff --git a/tests/browser/support/oauth-client.mjs b/tests/browser/support/oauth-client.mjs new file mode 100644 index 00000000..bedf91b6 --- /dev/null +++ b/tests/browser/support/oauth-client.mjs @@ -0,0 +1,59 @@ +import { expect } from "@playwright/test"; +import { waitForMailpitCode } from "../../support/helpers/mailpit.mjs"; +import { config } from "../../support/helpers/browser-oauth.mjs"; + +export { config }; +export const databasePath = + process.env.TEST_ACCOUNT_DATABASE_PATH ?? + "/entryway-data/account-authority.sqlite"; + +export function consentForm(page, did) { + return page + .locator('form[action="/auth/consent"]') + .filter({ has: page.locator(`input[name="did"][value="${did}"]`) }); +} + +export function selectionForm(page, did) { + return page + .locator('form[action="/auth/select"]') + .filter({ has: page.locator(`input[name="did"][value="${did}"]`) }); +} + +/** + * Start an OAuth authorization through the synthetic client's login route. + * The sandbox clients are `primary`, `secondary` (trusted, skips consent on + * signup) and `untrusted` (opts in to the skip without being trusted). + */ +export async function beginAuthorization( + page, + { client = "primary", identifier = config.issuer, prompt, email } = {}, +) { + const login = new URL("/client/login", config.clientUrl); + login.searchParams.set("identifier", identifier); + login.searchParams.set("client", client); + if (prompt) login.searchParams.set("prompt", prompt); + if (email) login.searchParams.set("email", email); + await page.goto(login.href); +} + +export async function requestVisibleCode(page, email) { + const since = Date.now(); + await page.getByLabel("Email address").fill(email); + await page.getByRole("button", { name: "Send sign-in code" }).click(); + await expect( + page.getByRole("heading", { name: "Check your email" }), + ).toBeVisible(); + return waitForMailpitCode({ recipient: email, since }); +} + +export async function verifyVisibleCode(page, code) { + await page.getByLabel("Sign-in code").fill(code); + await page.getByRole("button", { name: "Verify code" }).click(); +} + +export async function finishConsent(page, did) { + await consentForm(page, did) + .getByRole("button", { name: "Allow access" }) + .click(); + await expect(page.getByTestId("signed-in-did")).toHaveText(did); +} diff --git a/tests/browser/support/remembered-device.mjs b/tests/browser/support/remembered-device.mjs new file mode 100644 index 00000000..1c071a3c --- /dev/null +++ b/tests/browser/support/remembered-device.mjs @@ -0,0 +1,37 @@ +import { DatabaseSync } from "node:sqlite"; +import { expect } from "@playwright/test"; + +const DAY = 24 * 60 * 60_000; + +/** + * Move one account's remembered-device sign-in back in time. A device row lives + * in key_value_state as `oauth:device-accounts` / `/` and counts + * as stale after seven days. Only that account's rows change, so a sibling + * account remembered on the same device keeps its own age. + */ +export function ageRememberedAccount(did, databasePath, days = 8) { + const database = new DatabaseSync(databasePath, { timeout: 5_000 }); + try { + const rows = database + .prepare( + "SELECT key, value FROM key_value_state WHERE namespace='oauth:device-accounts' AND key LIKE ?", + ) + .all(`%/${did}`); + expect(rows.length).toBeGreaterThan(0); + const past = { $date: new Date(Date.now() - days * DAY).toISOString() }; + const update = database.prepare( + "UPDATE key_value_state SET value=? WHERE namespace='oauth:device-accounts' AND key=?", + ); + for (const { key, value } of rows) + update.run( + JSON.stringify({ + ...JSON.parse(value), + createdAt: past, + updatedAt: past, + }), + key, + ); + } finally { + database.close(); + } +} diff --git a/tests/contracts/provider-client-fetch.test.mjs b/tests/contracts/provider-client-fetch.test.mjs index f19cf053..b9eff070 100644 --- a/tests/contracts/provider-client-fetch.test.mjs +++ b/tests/contracts/provider-client-fetch.test.mjs @@ -29,6 +29,7 @@ test("only configured client metadata URLs bypass private-network SSRF protectio config.browserClientMetadataUrl, `${config.clientUrl}/client-metadata.json`, `${config.clientUrl}/client-metadata-secondary.json`, + `${config.clientUrl}/client-metadata-untrusted.json`, ]) { assert.equal((await fetch(url)).status, 200); } @@ -48,6 +49,7 @@ test("only configured client metadata URLs bypass private-network SSRF protectio "private", "private", "private", + "private", "safe", "safe", "safe", diff --git a/tests/fixtures/synthetic-client.mjs b/tests/fixtures/synthetic-client.mjs index 6f0aaad2..2074cc15 100644 --- a/tests/fixtures/synthetic-client.mjs +++ b/tests/fixtures/synthetic-client.mjs @@ -111,12 +111,23 @@ export async function mountClient({ app, config, db }) { const metadataPaths = { primary: "/client-metadata.json", secondary: "/client-metadata-secondary.json", + untrusted: "/client-metadata-untrusted.json", }; const callbackPaths = { primary: "/client/callback", secondary: "/client/callback/secondary", + untrusted: "/client/callback/untrusted", }; - for (const id of ["primary", "secondary"]) { + const clientNames = { + primary: "Hypercerts test client", + secondary: "Hypercerts second test client", + untrusted: "Hypercerts untrusted test client", + }; + // ePDS signup consent skip opt-in. The sandbox trusts primary and secondary + // (OAUTH_TRUSTED_CLIENTS), so secondary skips consent on signup, untrusted + // opts in without trust and must still show it, and primary does not opt in. + const skipsConsentOnSignup = new Set(["secondary", "untrusted"]); + for (const id of Object.keys(metadataPaths)) { const jwk = await db.transact(async () => { const stored = await db.get("client:keys", id); if (stored) return stored; @@ -135,10 +146,7 @@ export async function mountClient({ app, config, db }) { clients[id] = new NodeOAuthClient({ clientMetadata: { client_id: `${origin}${metadataPaths[id]}`, - client_name: - id === "primary" - ? "Hypercerts test client" - : "Hypercerts second test client", + client_name: clientNames[id], client_uri: `${origin}/`, redirect_uris: [`${origin}${callbackPaths[id]}`], scope: DEFAULT_SCOPE, @@ -279,7 +287,12 @@ export async function mountClient({ app, config, db }) { "Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=60", }) - .json(clients[id].clientMetadata), + .json({ + ...clients[id].clientMetadata, + ...(skipsConsentOnSignup.has(id) + ? { epds_skip_consent_on_signup: true } + : {}), + }), ); } router.get( @@ -364,7 +377,10 @@ export async function mountClient({ app, config, db }) { router.get( Object.values(callbackPaths), route(async (req, res) => { - const id = req.path === callbackPaths.secondary ? "secondary" : "primary"; + const id = + Object.keys(callbackPaths).find( + (key) => callbackPaths[key] === req.path, + ) ?? "primary"; const browser = await readBrowser(req, res); const params = new URL(req.originalUrl, origin).searchParams; const state = params.get("state"); diff --git a/tests/flows/account-device-lifecycle.md b/tests/flows/account-device-lifecycle.md index 1700b123..5caf9422 100644 --- a/tests/flows/account-device-lifecycle.md +++ b/tests/flows/account-device-lifecycle.md @@ -12,13 +12,15 @@ For a verified identity with multiple bindings, `/account` requires an explicit DID choice; every action and proof stays pinned to that DID. Reject duplicate, conflicting, foreign and revoked selectors without falling back to a sibling. Open two selected-DID tabs and verify their actions remain isolated. -Logout/session revocation, forgetting a device-account membership and revoking -an application grant have distinct effects. +A shared email never selects an account in password login, standard password +reset (no mail is sent) or signup (`AccountExists`); only the verified-email +chooser does. Logout/session revocation, forgetting a device-account membership +and revoking an application grant have distinct effects. Inspect `account-console.spec.mjs`, `account-security.test.mjs`, -`account-schema.test.mjs`, `experience-browser.spec.mjs` and -`oauth-lifecycle.spec.mjs` plus contract cases for the exact behavior. Ordinary -email changes, backup recovery and admin repair reject a normalized destination +`account-schema.test.mjs`, `experience-browser.spec.mjs`, +`oauth-lifecycle.spec.mjs` and `shared-email-lookups.spec.mjs` plus contract +cases for the exact behavior. Ordinary email changes, backup recovery and admin repair reject a normalized destination claimed as another DID's primary email. Moving an existing shared account to an unused address preserves sibling claims and bindings; authorized migration/import remains the explicit sharing exception. Remembered OAuth device authentication @@ -29,7 +31,10 @@ session shows "Confirm it's you" first, takes a Mailpit code and returns to the page's form; a gated change submitted after the window is not made, and the user confirms and makes it again (`account-confirm.spec.mjs`). A session signed in or confirmed within ten minutes is not asked, and `noRecentLogin` actions never -are. A confirmation code works only for the session that asked and only once. +are. A confirmation code works only for the session that asked and only once, +and five wrong guesses spend it until the user asks for a new code. Revoking an +app password, changing the handle and starting account deletion never ask a +stale session to confirm, and changing a password asks for no current password. Browser-session removal does not necessarily revoke OAuth refresh credentials, and existing access tokens can remain valid until expiration. diff --git a/tests/flows/otp-client-oauth.md b/tests/flows/otp-client-oauth.md index d451bd68..2e7554a9 100644 --- a/tests/flows/otp-client-oauth.md +++ b/tests/flows/otp-client-oauth.md @@ -14,27 +14,44 @@ metadata URL and requested scope. Google/GitHub are outside this flow. 3. Preserve the zero/single-account path. For multiple established bindings, explicitly choose one; selection re-reads current bindings and continues only with that DID. Before consent is granted, the user may return to the chooser - and pick another bound DID. This email chooser is distinct from the pre-existing device - account picker. + and pick another bound DID; the client then shows the last chosen account. + Each linked account has its own "Continue with this account" button and + status. This email chooser is distinct from the pre-existing device account + picker. 4. Complete the existing consent flow when required and assert the returned identity equals the intended DID and the original OAuth request is retained. - A stale remembered device requires visible email OTP for its selected DID; - both the OAuth `login_hint` and selected-account hint must still match after - restart. Client trust is the Entryway-wide `OAUTH_TRUSTED_CLIENTS` list. - A newly created account skips consent only when a trusted client's - metadata opts in; no browser case covers the - skip yet, so its decision table lives in `signup-consent-skip.test.mjs`. + A stale remembered device (older than seven days) lists its account as + "Sign in with an email code" instead of one-click consent. Choosing it sends + the code to the account's own email without asking for it; the page shows the + address masked and neither the address nor its local part is in the HTML. + With a shared email the chooser stays, limited to the selected DID. Both the + OAuth `login_hint` and selected-account hint must still match after restart. + Client trust is the Entryway-wide `OAUTH_TRUSTED_CLIENTS` list. A newly + created account skips consent only when a trusted client's metadata opts in + (`epds_skip_consent_on_signup`): the sandbox trusts the primary and secondary + clients, the secondary and an extra untrusted client opt in, and the primary + does not. A returning account on the trusted opted-in client still sees + consent; the full decision table lives in `signup-consent-skip.test.mjs`. + An OAuth app may also start email-first sign-in with `login_hint=` on + the authorize redirect; a handle or DID hint from the pushed request wins, + and an invalid email falls back to the sign-in page without sending mail. + `prompt=none` signs a remembered, approved account in silently, returns + `consent_required` for a client that was never approved and `login_required` + without a hint, and is refused for an untrusted public client. 5. Use the resulting credentials for a real PDS write and refresh. 6. Check denied/revoked paths in the accompanying lifecycle cases. **Source cases:** `browser.spec.mjs`, `experience-browser.spec.mjs`, -`account-chooser.spec.mjs`, `browser-oauth.spec.mjs` and `oauth-lifecycle.spec.mjs` -under `tests/browser/`. The account chooser case reads sign-in codes from visible -Mailpit messages and creates a second real PDS account for a sandbox-only shared- -email fixture through the reviewed account authority helper. This does not test -joining-PDS association import. The original cases read the test outbox; -experience cases use the private Mailpit API. Do not describe every imported case -as an SMTP end-to-end proof. +`account-chooser.spec.mjs`, `oauth-remembered-device.spec.mjs`, +`oauth-signup-consent-skip.spec.mjs`, `oauth-sign-in-hints.spec.mjs`, +`browser-oauth.spec.mjs` and `oauth-lifecycle.spec.mjs` under `tests/browser/`. +The newer cases read sign-in codes from visible +Mailpit messages. The account chooser and remembered-device cases create a second +real PDS account for a sandbox-only shared-email fixture through the reviewed +account authority helper; this does not test joining-PDS association import. The +remembered-device cases age one account's device row directly in the database. +The original cases read the test outbox; experience cases use the private Mailpit +API. Do not describe every imported case as an SMTP end-to-end proof. **Repeat:** `fresh` supplies isolated state. Ordinary browser identities use run-specific names where implemented; a repeated persistent run is not a clean diff --git a/tests/playwright.config.mjs b/tests/playwright.config.mjs index 8dfe14df..1a93e214 100644 --- a/tests/playwright.config.mjs +++ b/tests/playwright.config.mjs @@ -16,6 +16,10 @@ export default defineConfig({ "browser-oauth.spec.mjs", "oauth-lifecycle.spec.mjs", "account-chooser.spec.mjs", + "oauth-remembered-device.spec.mjs", + "oauth-signup-consent-skip.spec.mjs", + "oauth-sign-in-hints.spec.mjs", + "shared-email-lookups.spec.mjs", ], fullyParallel: false, workers: 1, From db2c61bfaa89b831bd4a0be1af766e4a8e0305d0 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 5 Nov 2026 17:56:59 +0600 Subject: [PATCH 2/2] tests/browser: complete chooser sign-in for each shared-email DID TECH-683 requires each account to finish its own journey. The completed sign-in test now runs once per DID in a fresh context, checking replay rejection, token subject, PDS audience and an account-scoped write. --- tests/browser/account-chooser.spec.mjs | 69 ++++++++++++++------------ 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/tests/browser/account-chooser.spec.mjs b/tests/browser/account-chooser.spec.mjs index d610b5f2..1140c11a 100644 --- a/tests/browser/account-chooser.spec.mjs +++ b/tests/browser/account-chooser.spec.mjs @@ -58,42 +58,45 @@ async function assertOAuthSubjectAndWrite(page, account) { expect((await write.json()).uri).toContain(`at://${account.did}/`); } -test("verified-email chooser selects each real DID after OTP and keeps OAuth writes account-scoped", async ({ - browser, -}) => { - test.setTimeout(180_000); - const { first, second } = shared; - const context = await browser.newContext({ ignoreHTTPSErrors: false }); - try { - const page = await context.newPage(); - await reachChooser(page); - await expect(page.locator('form[action="/auth/select"]')).toHaveCount(2); - for (const account of [first, second]) - await expect(selectionForm(page, account.did)).toHaveCount(1); +// Each DID completes its own journey in a fresh context, so a regression that +// only breaks consent, token subject or writes for one binding still fails. +for (const which of ["first", "second"]) { + test(`verified-email chooser completes sign-in as the ${which} DID and keeps OAuth writes account-scoped`, async ({ + browser, + }) => { + test.setTimeout(180_000); + const { first, second } = shared; + const chosen = shared[which]; + const context = await browser.newContext({ ignoreHTTPSErrors: false }); + try { + const page = await context.newPage(); + await reachChooser(page); + await expect(page.locator('form[action="/auth/select"]')).toHaveCount(2); + for (const account of [first, second]) + await expect(selectionForm(page, account.did)).toHaveCount(1); - // Choosing the second, non-default DID on another PDS proves the chooser - // continues the selected account rather than the first binding. - const form = selectionForm(page, second.did); - const submitted = await form.evaluate((element) => - Object.fromEntries(new FormData(element).entries()), - ); + const form = selectionForm(page, chosen.did); + const submitted = await form.evaluate((element) => + Object.fromEntries(new FormData(element).entries()), + ); - await form.getByRole("button").click(); - await expect(consentForm(page, second.did)).toBeVisible(); + await form.getByRole("button").click(); + await expect(consentForm(page, chosen.did)).toBeVisible(); - await finishConsent(page, second.did); - const replay = await page.request.post(`${config.issuer}/auth/select`, { - maxRedirects: 0, - headers: { origin: config.issuer }, - form: submitted, - }); - expect(replay.status()).toBe(400); - expect(await replay.text()).toContain("This sign-in has expired"); - await assertOAuthSubjectAndWrite(page, second); - } finally { - await context.close(); - } -}); + await finishConsent(page, chosen.did); + const replay = await page.request.post(`${config.issuer}/auth/select`, { + maxRedirects: 0, + headers: { origin: config.issuer }, + form: submitted, + }); + expect(replay.status()).toBe(400); + expect(await replay.text()).toContain("This sign-in has expired"); + await assertOAuthSubjectAndWrite(page, chosen); + } finally { + await context.close(); + } + }); +} test("each linked account has its own button and status, and consent can return to the chooser", async ({ browser,