Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/deployment-profiles.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,12 @@ header is test machinery, not a production routing or fleet API.
Every profile exercises fresh Mailpit signup, returning OTP/session use,
independent-client OAuth and direct PDS reads/writes. The PostgreSQL replica case
crosses observed boot IDs for OTP completion, session use, code consumption,
refresh/replay and revocation. Concurrent cold client initialization retains the
refresh/replay and revocation. A separate shared-email OAuth sign-in alternates
nodes: code request on one, code verification on the other, account choice on the
first and consent on the second. It requires each step's responses to name the
selected node's boot ID, then checks the session DID, token audience and an
account-scoped write. A chooser submission for a DID bound to another email is
refused on both nodes. Concurrent cold client initialization retains the
same public metadata keys across nodes. Safe attempt receipts associate actual
application work with its boot identity; private keys and credentials stay in
private volumes.
Expand Down
27 changes: 4 additions & 23 deletions tests/browser/account-chooser.spec.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { test, expect } from "@playwright/test";
import { createSharedEmailPair } from "./support/email-chooser-fixture.mjs";
import {
assertOAuthSubjectAndWrite,
beginAuthorization,
config,
consentForm,
Expand Down Expand Up @@ -36,28 +37,6 @@ async function reachChooser(page) {
).toBeVisible();
}

async function assertOAuthSubjectAndWrite(page, account) {
const response = await page.request.get(
`${config.clientUrl}/client/session?client=primary`,
);
expect(response.ok(), await response.text()).toBeTruthy();
const current = await response.json();
// The OAuth client session DID is the subject returned by the token exchange.
expect(current.did).toBe(account.did);
const pds = config.pds.find(({ id }) => id === account.pdsId);
expect(new URL(current.tokenInfo.aud).href).toBe(new URL(pds.url).href);

const write = await page.request.post(`${config.clientUrl}/client/write`, {
headers: { origin: config.clientUrl, "x-csrf-token": current.csrf },
data: {
client: "primary",
text: `Account chooser write ${account.pdsId} ${runId}`,
},
});
expect(write.ok(), await write.text()).toBeTruthy();
expect((await write.json()).uri).toContain(`at://${account.did}/`);
}

// 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"]) {
Expand Down Expand Up @@ -91,7 +70,9 @@ for (const which of ["first", "second"]) {
});
expect(replay.status()).toBe(400);
expect(await replay.text()).toContain("This sign-in has expired");
await assertOAuthSubjectAndWrite(page, chosen);
await assertOAuthSubjectAndWrite(page, chosen, {
text: `Account chooser write ${chosen.pdsId} ${runId}`,
});
} finally {
await context.close();
}
Expand Down
197 changes: 185 additions & 12 deletions tests/browser/resilience-profile.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ import { loadConfig } from "../../dist/src/config.mjs";
import { openDatabase } from "../../dist/src/database/connection.js";
import { waitForMailpitCode } from "../support/helpers/mailpit.mjs";
import { candidateIdentity } from "../support/candidate-identity.mjs";
import {
createRealAccount,
createSharedEmailPair,
} from "./support/email-chooser-fixture.mjs";
import {
assertOAuthSubjectAndWrite,
beginAuthorization,
consentForm,
finishConsent,
requestVisibleCode,
selectionForm,
verifyVisibleCode,
} from "./support/oauth-client.mjs";
const config = await loadConfig();
const stage = process.env.PROFILE_STAGE;
const label = process.env.PROFILE_LABEL ?? stage;
Expand Down Expand Up @@ -261,7 +274,21 @@ async function rawGrant(db, dpopJwk, parameters, node) {
throw Error("DPoP negotiation failed");
}

/** Boot ID per node from the ingress; every node ready, `count` distinct processes. */
async function nodeInstanceIds() {
const topology = await (
await fetch(`${config.issuer}/__profile/nodes`)
).json();
expect(topology.nodes.length).toBe(count);
expect(topology.nodes.every((node) => node.ready)).toBe(true);
expect(new Set(topology.nodes.map((node) => node.instanceId)).size).toBe(
count,
);
return new Map(topology.nodes.map((node) => [node.node, node.instanceId]));
}

test(`fresh deployment profile ${stage}`, async ({ browser }) => {
test.skip(stage === "cross-node-signin", "Has its own test below");
await mkdir("/profile", { recursive: true, mode: 0o700 });
const db =
stage === "database-refusal" ? null : await openDatabase(configuration);
Expand All @@ -281,14 +308,7 @@ test(`fresh deployment profile ${stage}`, async ({ browser }) => {
const page = await context.newPage();
try {
if (stage === "journey") {
const topology = await (
await fetch(`${config.issuer}/__profile/nodes`)
).json();
expect(topology.nodes.length).toBe(count);
expect(topology.nodes.every((node) => node.ready)).toBe(true);
expect(new Set(topology.nodes.map((node) => node.instanceId)).size).toBe(
count,
);
const ids = await nodeInstanceIds();
const metadata = await Promise.all(
nodes.map(async (node) => {
const response = await fetch(
Expand Down Expand Up @@ -415,12 +435,9 @@ test(`fresh deployment profile ${stage}`, async ({ browser }) => {
await authorize(page, identity);
await context.storageState({ path: "/profile/browser.json" });
await writeRecord(page, identity, "Profile write after replay isolation");
const actual = new Map(
topology.nodes.map((node) => [node.node, node.instanceId]),
);
expect(
observed.every(
(receipt) => receipt.instanceId === actual.get(receipt.expectedNode),
(receipt) => receipt.instanceId === ids.get(receipt.expectedNode),
),
).toBe(true);
} else if (stage === "survivor" || stage === "rejoin") {
Expand Down Expand Up @@ -570,3 +587,159 @@ test(`fresh deployment profile ${stage}`, async ({ browser }) => {
await context.close();
}
});

const issuerOrigin = new URL(config.issuer).origin;
const clientOrigin = new URL(config.clientUrl).origin;
const steps = [];

/**
* Run one browser step on `node`. Every Entryway page response it produces must
* carry that node's boot ID, so a step served elsewhere fails instead of
* quietly proving nothing.
*/
async function onNode(page, ids, node, step, action) {
await page.context().setExtraHTTPHeaders(select(node));
const responses = [];
const collect = (response) => {
const { origin } = new URL(response.url());
if (
response.request().resourceType() === "document" &&
[issuerOrigin, clientOrigin].includes(origin)
)
responses.push(response);
};
page.on("response", collect);
try {
await action();
} finally {
page.off("response", collect);
}
expect(
responses.length,
`${step}: no Entryway page response`,
).toBeGreaterThan(0);
for (const response of responses) {
const instanceId = response.headers()["x-entryway-instance"];
expect(instanceId, `${step}: ${new URL(response.url()).pathname}`).toBe(
ids.get(node),
);
observed.push({
phase: stage,
path: new URL(response.url()).pathname,
expectedNode: node,
instanceId,
status: response.status(),
});
}
steps.push({
step,
node,
instanceId: ids.get(node),
responses: responses.length,
});
}

// TECH-683: OTP, account choice and consent for one OAuth sign-in span both
// nodes. Entryway keeps no per-process state between them; PostgreSQL carries it.
test(`cross-node OAuth sign-in ${stage}`, async ({ browser }) => {
test.skip(stage !== "cross-node-signin", "Runs in its own profile stage");
// A one-node profile cannot cross nodes, so it must fail rather than pass.
expect(count).toBe(2);
const [nodeA, nodeB] = nodes;
const ids = await nodeInstanceIds();
expect([...ids.keys()]).toEqual(nodes);
const runId = Date.now().toString(36);
const shared = await createSharedEmailPair(browser, {
prefix: "xn",
runId,
database: configuration,
});
// A real account whose email differs: bound to a different verified identity.
const outsider = await createRealAccount(browser, {
email: `xn-${runId}-outsider@example.test`,
handle: `xn-${runId}-x.entryway.atmosbox.test`,
pdsId: "pds1",
});
// The second account is on the other PDS, so a wrong subject or audience
// cannot pass by defaulting to the first.
const chosen = shared.second;
const context = await browser.newContext({ ignoreHTTPSErrors: false });
const page = await context.newPage();
try {
let message;
await onNode(page, ids, nodeA, "authorize and request code", async () => {
await beginAuthorization(page, { prompt: "consent" });
await expect(page.getByLabel("Email address")).toBeVisible();
message = await requestVisibleCode(page, shared.email);
});
await onNode(page, ids, nodeB, "verify code", async () => {
await verifyVisibleCode(page, message.code);
await expect(
page.getByRole("heading", { name: "Choose an account" }),
).toBeVisible();
});
await expect(page.locator('form[action="/auth/select"]')).toHaveCount(2);
for (const account of [shared.first, shared.second])
await expect(selectionForm(page, account.did)).toHaveCount(1);
await expect(selectionForm(page, outsider.did)).toHaveCount(0);

// A DID bound to another email is refused on both nodes, with the real
// hidden fields of this chooser, and does not spoil the pending choice.
const form = selectionForm(page, chosen.did);
const submitted = await form.evaluate((element) =>
Object.fromEntries(new FormData(element).entries()),
);
for (const node of nodes) {
const refused = await page.request.post(`${config.issuer}/auth/select`, {
maxRedirects: 0,
headers: { origin: config.issuer, ...select(node) },
form: { ...submitted, did: outsider.did },
});
expect(refused.status()).toBe(400);
expect(refused.headers()["x-entryway-instance"]).toBe(ids.get(node));
expect(await refused.text()).toContain(
"not linked to this verified identity",
);
}

await onNode(page, ids, nodeA, "choose account", async () => {
await form.getByRole("button").click();
await expect(consentForm(page, chosen.did)).toBeVisible();
await expect(consentForm(page, shared.first.did)).toHaveCount(0);
});
await onNode(page, ids, nodeB, "approve consent", () =>
finishConsent(page, chosen.did),
);
// The client session began on node B; read and write it through node A.
const { session, write } = await assertOAuthSubjectAndWrite(page, chosen, {
text: `Cross-node sign-in write ${runId}`,
headers: select(nodeA),
});
for (const response of [session, write])
expect(response.headers()["x-entryway-instance"]).toBe(ids.get(nodeA));

await marker(`profile-${label}.json`, {
status: "passed",
stage,
backend: config.database.backend,
deploymentMode: process.env.DEPLOYMENT_MODE,
nodeCount: count,
steps,
observed,
identity: candidateIdentity(),
});
} catch (error) {
await marker(`profile-${label}-failure-context.json`, {
stage,
steps: steps.map(({ step, node }) => ({ step, node })),
path: new URL(page.url()).pathname,
heading: await page
.locator("h1")
.allTextContents()
.catch(() => []),
}).catch(() => {});
throw error;
} finally {
await context.close();
}
});
21 changes: 18 additions & 3 deletions tests/browser/support/email-chooser-fixture.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ export async function createRealAccount(browser, account) {
* 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 }) {
export async function createSharedEmailPair(
browser,
{ prefix, runId, database },
) {
const email = `${prefix}-${runId}-shared@example.test`;
const first = {
email,
Expand All @@ -65,17 +68,29 @@ export async function createSharedEmailPair(browser, { prefix, runId }) {
};
await createRealAccount(browser, first);
await createRealAccount(browser, second);
await bindAccountsToSharedEmail({ first, second, email, databasePath });
await bindAccountsToSharedEmail({
first,
second,
email,
databasePath,
database,
});
return { email, first, second };
}

/**
* `database` selects a non-default authority database, such as the PostgreSQL
* one a deployment profile shares between nodes. It defaults to the sandbox's
* SQLite file at `databasePath`.
*/
export async function bindAccountsToSharedEmail({
first,
second,
email,
databasePath,
database = { backend: "sqlite", path: databasePath },
}) {
const db = await openDatabase({ backend: "sqlite", path: databasePath });
const db = await openDatabase(database);
try {
const accounts = await createAccounts({ db, config });
// Ordinary email changes reject an occupied primary email, so share it the
Expand Down
35 changes: 35 additions & 0 deletions tests/browser/support/oauth-client.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,38 @@ export async function finishConsent(page, did) {
.click();
await expect(page.getByTestId("signed-in-did")).toHaveText(did);
}

/**
* Assert the primary client's session subject, token audience and an
* account-scoped write for `account`. `headers` apply to both client calls, for
* example to select a deployment-profile node; the responses are returned so
* callers can inspect where each call was served.
*/
export async function assertOAuthSubjectAndWrite(
page,
account,
{ text, headers = {} },
) {
const session = await page.request.get(
`${config.clientUrl}/client/session?client=primary`,
{ headers },
);
expect(session.ok(), await session.text()).toBeTruthy();
const current = await session.json();
// The OAuth client session DID is the subject returned by the token exchange.
expect(current.did).toBe(account.did);
const pds = config.pds.find(({ id }) => id === account.pdsId);
expect(new URL(current.tokenInfo.aud).href).toBe(new URL(pds.url).href);

const write = await page.request.post(`${config.clientUrl}/client/write`, {
headers: {
...headers,
origin: config.clientUrl,
"x-csrf-token": current.csrf,
},
data: { client: "primary", text },
});
expect(write.ok(), await write.text()).toBeTruthy();
expect((await write.json()).uri).toContain(`at://${account.did}/`);
return { session, write };
}
10 changes: 9 additions & 1 deletion tests/profiles.playwright.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ process.env.PLAYWRIGHT_NO_COPY_PROMPT = "1";
const stage = process.env.PROFILE_STAGE;
const label = process.env.PROFILE_LABEL ?? stage;
if (!/^[a-z-]+$/.test(label)) throw new Error("InvalidProfileLabel");
if (!["journey", "survivor", "rejoin", "database-refusal"].includes(stage))
if (
![
"journey",
"cross-node-signin",
"survivor",
"rejoin",
"database-refusal",
].includes(stage)
)
throw new Error("InvalidProfileStage");
export default defineConfig({
testDir: "./browser",
Expand Down
Loading