mirror of
https://github.com/bitbaum/fleet.git
synced 2026-12-04 05:07:28 +01:00
test(auth): verify real consumer account journeys (#201)
This commit is contained in:
8 files changed
+428
-12
No files matched your search
@@ -413,6 +413,7 @@ jobs:
|
||||
- name: The app starter holds the fleet's contract
|
||||
run: |
|
||||
node --test scripts/ci/package-composition-audit.test.mjs scripts/ci/package-rollout-gate.test.mjs scripts/ci/package-canary-audit.test.mjs scripts/ci/git-package-currency.test.mjs
|
||||
node --test scripts/test/auth-journey.test.mjs
|
||||
bash scripts/templates/test-app-template.sh
|
||||
|
||||
# Drift guard. The fleet is on v7; templates handing out v4 is exactly
|
||||
|
||||
@@ -85,19 +85,22 @@ jobs:
|
||||
# land in UNCHECKED — named, never counted as current.
|
||||
GH_TOKEN: ${{ secrets.FLEET_PAT || secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
{
|
||||
echo '## Internal package currency'
|
||||
echo
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
node scripts/ci/currency-reconciler.mjs 2>&1 | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
echo '```' >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
matrix=$(node scripts/ci/currency-reconciler.mjs --json)
|
||||
set -euo pipefail
|
||||
matrix_file="$RUNNER_TEMP/internal-package-plan.json"
|
||||
# One scan, one set of release targets. Repeating the network census
|
||||
# for the summary doubles API work and can choose different targets.
|
||||
node scripts/ci/currency-reconciler.mjs --json > "$matrix_file"
|
||||
node -e '
|
||||
const fs = require("node:fs");
|
||||
const plan = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
|
||||
console.log("## Internal package currency\n");
|
||||
console.log(`${plan.length} repositories have planned updates. Unchecked evidence is reported in the job log.\n`);
|
||||
for (const entry of plan) {
|
||||
console.log(`- ${entry.repo}: ${entry.bumps.map(b => `${b.name} → ${b.latest}`).join(", ")}`);
|
||||
}
|
||||
' "$matrix_file" >> "$GITHUB_STEP_SUMMARY"
|
||||
matrix="$(cat "$matrix_file")"
|
||||
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
|
||||
# An empty plan must not start a matrix job with nothing in it — and
|
||||
# over the cap the script emits [] deliberately, which lands here too.
|
||||
if [ "$matrix" = "[]" ]; then
|
||||
echo "any=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
name: Shared account lifecycle
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
migrate-command:
|
||||
type: string
|
||||
required: true
|
||||
sign-in-path:
|
||||
type: string
|
||||
default: /sign-in
|
||||
account-path:
|
||||
type: string
|
||||
default: /account
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
lifecycle:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17
|
||||
env:
|
||||
POSTGRES_USER: app
|
||||
POSTGRES_PASSWORD: app
|
||||
POSTGRES_DB: auth_test
|
||||
ports: ["5432:5432"]
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U app -d auth_test"
|
||||
--health-interval 5s --health-timeout 5s --health-retries 10
|
||||
env:
|
||||
DATABASE_URL: postgres://app:app@127.0.0.1:5432/auth_test
|
||||
NEXT_PUBLIC_SITE_URL: http://localhost:3000
|
||||
NEXT_TELEMETRY_DISABLED: "1"
|
||||
NODE_OPTIONS: --max-old-space-size=4096
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
repository: bitbaum/fleet
|
||||
path: .fleet-auth-tests
|
||||
sparse-checkout: |
|
||||
scripts/test/auth-journey.mjs
|
||||
scripts/test/capture-auth-mail.mjs
|
||||
sparse-checkout-cone-mode: false
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Apply this app's committed migrations to the isolated database
|
||||
env:
|
||||
MIGRATE_COMMAND: ${{ inputs.migrate-command }}
|
||||
run: bash -euo pipefail -c "$MIGRATE_COMMAND"
|
||||
- run: pnpm run build
|
||||
- name: Exercise account lifecycle and shared reset form
|
||||
env:
|
||||
AUTH_TEST_SIGNIN_PATH: ${{ inputs.sign-in-path }}
|
||||
AUTH_TEST_ACCOUNT_PATH: ${{ inputs.account-path }}
|
||||
BROWSER_EXECUTABLE: /usr/bin/google-chrome
|
||||
run: node .fleet-auth-tests/scripts/test/auth-journey.mjs
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: account-lifecycle-evidence
|
||||
path: auth-journey-artifacts/
|
||||
retention-days: 14
|
||||
if-no-files-found: warn
|
||||
@@ -60,6 +60,28 @@ tags verified stable versions even before npm bootstrap. The template sync
|
||||
offers missing release files to every registered package, not just newly
|
||||
extracted packages. Existing files remain owned by their repositories.
|
||||
|
||||
## Account lifecycle evidence
|
||||
|
||||
`.github/workflows/shared-auth-journey.yml` builds the consuming app without auth
|
||||
secrets, applies its committed migrations to an isolated PostgreSQL database,
|
||||
then starts the production server with synthetic credentials. Consumers provide
|
||||
`migrate-command`, `sign-in-path`, and `account-path` through a job in their
|
||||
`browser-smoke.yml`. The driver captures mail locally through the app's real
|
||||
adapter; it does not send external mail.
|
||||
|
||||
The journey checks registration and role escalation protection, verification,
|
||||
reset response parity for unknown addresses, return paths, token removal from
|
||||
browser history, password reset and token reuse, session revocation, old and new
|
||||
passwords, and browser login into the server-rendered account page. It captures
|
||||
light and dark reset forms at 320, 390, and 1280 pixels and rejects horizontal
|
||||
overflow. Building without auth secrets is intentional: it catches session pages
|
||||
incorrectly cached as signed-out redirects. Logs and screenshots contain synthetic
|
||||
users; mail bodies and recovery tokens remain in memory.
|
||||
|
||||
This journey covers the shared email/password runtime. Apps with Supabase,
|
||||
organizations, or different account routes require equivalent adapter-specific
|
||||
journeys before promotion; installing a package does not establish adoption.
|
||||
|
||||
The existing Loki [self-host deployment workflow](https://github.com/bitbaum/loki/blob/main/.github/workflows/selfhost-deploy.yml)
|
||||
uses atomic releases and includes health-check and page-regression rollback.
|
||||
Those checks do not establish correctness of every authenticated or domain flow;
|
||||
|
||||
@@ -338,6 +338,9 @@ async function main() {
|
||||
|
||||
const plan = byRepo(rows);
|
||||
|
||||
if (asJson && unreadable.length) console.error(`UNCHECKED repositories: ${unreadable.join(", ")}`);
|
||||
if (asJson && uncheckedGit.size) console.error(`UNCHECKED Git releases: ${[...uncheckedGit].join(", ")}`);
|
||||
|
||||
if (asJson) {
|
||||
// Over the cap, emit an EMPTY matrix rather than the plan. The workflow
|
||||
// acts on whatever this prints, so refusing here is the refusal.
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:http";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { mkdirSync, createWriteStream } from "node:fs";
|
||||
|
||||
const base = process.env.AUTH_TEST_BASE_URL ?? "http://localhost:3000";
|
||||
const origin = new URL(base);
|
||||
assert.ok(
|
||||
["localhost", "127.0.0.1"].includes(origin.hostname),
|
||||
"Journey may only target a local test app",
|
||||
);
|
||||
const signIn = process.env.AUTH_TEST_SIGNIN_PATH ?? "/sign-in";
|
||||
const account = process.env.AUTH_TEST_ACCOUNT_PATH ?? "/account";
|
||||
const out = resolve(
|
||||
process.env.AUTH_TEST_ARTIFACTS ?? "auth-journey-artifacts",
|
||||
);
|
||||
mkdirSync(out, { recursive: true });
|
||||
const messages = [];
|
||||
const outbox = createServer(async (request, response) => {
|
||||
if (request.method !== "POST" || request.url !== "/messages") {
|
||||
response.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
let body = "";
|
||||
for await (const chunk of request) body += chunk;
|
||||
messages.push(JSON.parse(body));
|
||||
response
|
||||
.writeHead(200, { "content-type": "application/json" })
|
||||
.end(JSON.stringify({ id: `test-${messages.length}` }));
|
||||
});
|
||||
await new Promise((done) => outbox.listen(0, "127.0.0.1", done));
|
||||
const serverLog = createWriteStream(resolve(out, "server.log"));
|
||||
const child = spawn(
|
||||
"pnpm",
|
||||
["run", "start", "--hostname", "127.0.0.1", "--port", origin.port || "3000"],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
detached: true,
|
||||
env: {
|
||||
...process.env,
|
||||
NEXT_PUBLIC_SITE_URL: base,
|
||||
BETTER_AUTH_SECRET: randomBytes(48).toString("base64"),
|
||||
RESEND_API_KEY: "re_fleet_test_" + randomBytes(24).toString("hex"),
|
||||
FLEET_AUTH_TEST_MAIL_PORT: String(outbox.address().port),
|
||||
NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import ${fileURLToPath(new URL("./capture-auth-mail.mjs", import.meta.url))}`,
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
child.stdout.pipe(serverLog);
|
||||
child.stderr.pipe(serverLog);
|
||||
const cookies = new Map();
|
||||
async function call(path, body, useCookies = true) {
|
||||
const response = await fetch(base + path, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
redirect: "manual",
|
||||
headers: {
|
||||
origin: base,
|
||||
"content-type": "application/json",
|
||||
...(useCookies
|
||||
? { cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join("; ") }
|
||||
: {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
for (const value of response.headers.getSetCookie()) {
|
||||
const pair = value.split(";")[0],
|
||||
separator = pair.indexOf("=");
|
||||
cookies.set(pair.slice(0, separator), pair.slice(separator + 1));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
const post = (path, body, useCookies) =>
|
||||
call("/api/auth" + path, body, useCookies);
|
||||
const session = () => call("/api/auth/get-session").then((r) => r.json());
|
||||
const emailLink = () => {
|
||||
const message = messages.at(-1);
|
||||
assert.ok(message, "App must send account mail through its actual adapter");
|
||||
const link = message.text.match(/https?:\/\/[^\s<>]+/)?.[0];
|
||||
assert.equal(
|
||||
new URL(link).origin,
|
||||
base,
|
||||
"Account links must use the configured origin",
|
||||
);
|
||||
return new URL(link);
|
||||
};
|
||||
let browser;
|
||||
try {
|
||||
let ready = false;
|
||||
for (let i = 0; i < 120; i++) {
|
||||
if (child.exitCode !== null)
|
||||
throw new Error("Test app exited; see server.log");
|
||||
try {
|
||||
if ((await fetch(base + signIn)).ok) {
|
||||
ready = true;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
/* starting */
|
||||
}
|
||||
await new Promise((done) => setTimeout(done, 500));
|
||||
}
|
||||
assert.ok(ready, "Test app must become ready");
|
||||
const email = `journey-${randomBytes(6).toString("hex")}@example.test`;
|
||||
const password = "an isolated initial test passphrase";
|
||||
const signedUp = await post("/sign-up/email", {
|
||||
email,
|
||||
password,
|
||||
name: "Journey",
|
||||
role: "admin",
|
||||
callbackURL: account,
|
||||
});
|
||||
assert.equal(signedUp.status, 200, "registration");
|
||||
assert.ok(messages.length, "verification message captured");
|
||||
const verify = emailLink();
|
||||
await call(verify.pathname + verify.search);
|
||||
const signedIn = await session();
|
||||
assert.ok(signedIn?.user?.id, "verification signs in");
|
||||
assert.notEqual(
|
||||
signedIn.user.role,
|
||||
"admin",
|
||||
"registration cannot grant admin",
|
||||
);
|
||||
const absent = await post("/request-password-reset", {
|
||||
email: "absent@example.test",
|
||||
redirectTo: base + signIn + "?next=" + encodeURIComponent(account),
|
||||
});
|
||||
const present = await post("/request-password-reset", {
|
||||
email,
|
||||
redirectTo: base + signIn + "?next=" + encodeURIComponent(account),
|
||||
});
|
||||
assert.equal(present.status, 200);
|
||||
assert.deepEqual(
|
||||
await present.json(),
|
||||
await absent.json(),
|
||||
"recovery must not enumerate accounts",
|
||||
);
|
||||
const resetLink = emailLink();
|
||||
const callback = await call(resetLink.pathname + resetLink.search);
|
||||
const redirect = new URL(callback.headers.get("location"));
|
||||
assert.equal(redirect.pathname, signIn);
|
||||
assert.equal(redirect.searchParams.get("next"), account);
|
||||
const token = redirect.searchParams.get("token");
|
||||
const require = createRequire(resolve("package.json"));
|
||||
const { chromium } = require("playwright");
|
||||
browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE ?? "/usr/bin/chromium",
|
||||
args: ["--no-sandbox"],
|
||||
});
|
||||
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
|
||||
await page.goto(redirect.href);
|
||||
const inputs = page.locator('input[type="password"]');
|
||||
// SSR initially draws the ordinary sign-in form; hydration reads and clears
|
||||
// the reset token before rendering the two password fields.
|
||||
await inputs.nth(1).waitFor();
|
||||
assert.equal(
|
||||
await inputs.count(),
|
||||
2,
|
||||
"real app renders the shared reset form",
|
||||
);
|
||||
await inputs.nth(0).fill("a replacement isolated test passphrase");
|
||||
await inputs.nth(1).fill("a replacement isolated test passphrase");
|
||||
assert.ok(
|
||||
!new URL(page.url()).searchParams.has("token"),
|
||||
"token removed from address bar",
|
||||
);
|
||||
for (const width of [320, 390, 1280]) {
|
||||
await page.setViewportSize({ width, height: 844 });
|
||||
for (const colorScheme of ["light", "dark"]) {
|
||||
await page.emulateMedia({ colorScheme });
|
||||
assert.equal(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth > innerWidth,
|
||||
),
|
||||
false,
|
||||
`reset overflow at ${width}`,
|
||||
);
|
||||
await page.screenshot({
|
||||
path: resolve(out, `reset-${width}-${colorScheme}.png`),
|
||||
fullPage: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
await page
|
||||
.locator("form")
|
||||
.filter({ has: page.locator('input[autocomplete="new-password"]') })
|
||||
.locator('button[type="submit"]')
|
||||
.click();
|
||||
await page.getByRole("status").waitFor();
|
||||
assert.equal(await session(), null, "reset revokes old sessions");
|
||||
assert.equal(
|
||||
(
|
||||
await post("/reset-password", {
|
||||
token,
|
||||
newPassword: "another isolated passphrase",
|
||||
})
|
||||
).status,
|
||||
400,
|
||||
"token is one-time",
|
||||
);
|
||||
assert.equal(
|
||||
(await post("/sign-in/email", { email, password })).status,
|
||||
401,
|
||||
"old password rejected",
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await post("/sign-in/email", {
|
||||
email,
|
||||
password: "a replacement isolated test passphrase",
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
"new password works",
|
||||
);
|
||||
assert.equal(
|
||||
(await session()).user.id,
|
||||
signedIn.user.id,
|
||||
"identity is preserved",
|
||||
);
|
||||
await page.goto(base + signIn + "?next=" + encodeURIComponent(account));
|
||||
await page.locator('input[type="email"]').fill(email);
|
||||
await page
|
||||
.locator('input[autocomplete="current-password"]')
|
||||
.fill("a replacement isolated test passphrase");
|
||||
await page
|
||||
.locator("form")
|
||||
.filter({ has: page.locator('input[autocomplete="current-password"]') })
|
||||
.locator('button[type="submit"]')
|
||||
.click();
|
||||
await page.waitForURL(base + account);
|
||||
await page.locator("#acct-display-name").waitFor();
|
||||
assert.equal(
|
||||
await page.locator("#acct-display-name").inputValue(),
|
||||
"Journey",
|
||||
"server page and API recognize the same person",
|
||||
);
|
||||
assert.equal((await post("/sign-out", {})).status, 200);
|
||||
assert.equal(await session(), null);
|
||||
console.log(
|
||||
"PASS real app registration, verification, password recovery, browser reset, session revocation and sign-out",
|
||||
);
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
try {
|
||||
process.kill(-child.pid, "SIGTERM");
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
child.stdout.unpipe(serverLog);
|
||||
child.stderr.unpipe(serverLog);
|
||||
outbox.close();
|
||||
serverLog.end();
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
test("the account journey refuses deployed targets before starting anything", () => {
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[fileURLToPath(new URL("./auth-journey.mjs", import.meta.url))],
|
||||
{
|
||||
env: { ...process.env, AUTH_TEST_BASE_URL: "https://production.example" },
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(result.stderr, /only target a local test app/);
|
||||
});
|
||||
|
||||
test("test mail capture cannot run with real credentials", () => {
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
fileURLToPath(new URL("./capture-auth-mail.mjs", import.meta.url)),
|
||||
"-e",
|
||||
"",
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
FLEET_AUTH_TEST_MAIL_PORT: "54321",
|
||||
RESEND_API_KEY: "a-real-key-is-not-allowed",
|
||||
},
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(result.stderr, /synthetic key/);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// Loaded only by the isolated auth journey, never by a deployed application.
|
||||
const port = Number(process.env.FLEET_AUTH_TEST_MAIL_PORT);
|
||||
if (
|
||||
!Number.isInteger(port) ||
|
||||
port < 1 ||
|
||||
!process.env.RESEND_API_KEY?.startsWith("re_fleet_test_")
|
||||
)
|
||||
throw new Error(
|
||||
"The auth test transport requires an isolated outbox and a synthetic key",
|
||||
);
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = (input, init) => {
|
||||
const url = input instanceof Request ? input.url : String(input);
|
||||
if (url === "https://api.resend.com/emails")
|
||||
return original(`http://127.0.0.1:${port}/messages`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: init?.body,
|
||||
});
|
||||
return original(input, init);
|
||||
};
|
||||
Reference in new issue
Block a user