feat(DPoP): UI: bcast events to support multi tab

add also playwright test with the multi tab
This commit is contained in:
Edouard Vanbelle
2026-08-08 17:24:44 +02:00
parent 4c2b244166
commit ed99b08e62
8 changed files with 417 additions and 20 deletions
+8 -7
View File
@@ -66,13 +66,14 @@ export default defineConfig({
// Verbose startup so a CI webServer-readiness timeout shows where the
// server stalls (DB connect, migrations, bind) instead of nothing.
RUST_LOG: 'info,oxicloud=debug,sqlx=warn,tower_http=info',
// OPAQUE substrate is off for the E2E suite — Hurl exercises it via
// `tests/common/server.env`; the SPA-facing coverage suite doesn't
// need the boot-time init nor the ~200 KiB WASM client. Blanking
// the inherited commonEnv values takes the DI factory's
// `effective_mode == Off` short-circuit.
OXICLOUD_AUTH_OPAQUE_MODE: 'off',
OXICLOUD_AUTH_OPAQUE_SERVER_SETUP: '',
// OPAQUE + DPoP are inherited from `../common/server.env`:
// OXICLOUD_AUTH_OPAQUE_MODE=migrate (Phase 2 silent-migration
// on first legacy login, Phase 4 refusal thereafter)
// OXICLOUD_DPOP_MODE=required (verify every proof; unbound
// sessions still exempt per Gate 5 design)
// Testing under the production shape catches breakage where the
// SPA's fetch interceptor or the migration hook regresses in
// ways that only surface in a real browser + real crypto.
},
},
});
+51 -12
View File
@@ -98,22 +98,61 @@ export async function seedAdmin(baseURL: string, admin = TEST_ADMIN): Promise<vo
}
/**
* Authenticate the page's browser context via the API, so a subsequent
* `page.goto()` loads already signed in — no UI clicks. Selector-independent,
* which keeps it robust while the SPA login markup is still in flux.
* Authenticate the page's browser context, ready for subsequent
* `page.goto()` calls to load already-signed-in.
*
* `POST /api/auth/login` is CSRF-exempt and sets the auth cookies on the
* context's (shared) cookie jar, so `page.request` here authenticates the
* page too. Use this at the top of any spec that needs an authenticated app
* (and in the codegen recorder, so you record post-login flows).
* Uses the SPA's real login flow (`page.goto('/login')` → fill form
* → submit) rather than a bare `POST /api/auth/login`, so this works
* correctly under both auth modes the test env supports:
*
* * `OXICLOUD_AUTH_OPAQUE_MODE=off` — SPA does legacy login,
* server accepts.
* * `OXICLOUD_AUTH_OPAQUE_MODE=migrate` — first login legacy-
* succeeds + silently mints an OPAQUE envelope (Phase 2 hook);
* every subsequent login the SPA detects the envelope via
* `/api/auth/opaque/login/lookup` and does the full KE1/KE3
* OPAQUE handshake. Legacy `POST /api/auth/login` would 403
* with `opaque_migrated_use_opaque` (Phase 4) from the second
* login on — that's what the old bare-POST apiLogin used to
* hit as soon as OPAQUE went from `off` to `migrate`.
* * `OXICLOUD_DPOP_MODE=required` — the SPA computes and sends
* `dpop_jkt` in the login body; the session is created bound.
* A bare-POST wouldn't include it, so subsequent requests
* wouldn't get DPoP-signed. Going through the SPA keeps the
* end-to-end flow honest.
*
* Overhead vs the old direct POST: ~200-500 ms per test to load
* `/login`, submit, and wait for the post-login redirect. Runs
* once per test (from `beforeEach`), so the total suite tax is
* modest and the coverage payoff is real.
*/
export async function apiLogin(page: Page, admin = TEST_ADMIN): Promise<void> {
const res = await page.request.post('/api/auth/login', {
data: { username: admin.username, password: admin.password },
});
if (!res.ok()) {
throw new Error(`apiLogin failed: ${res.status()} ${await res.text()}`);
// Idempotence check — many specs' beforeEach + test body both call
// apiLogin; the old bare-POST version was a no-op on a live
// session, and callers depend on that. Under UI-driven login,
// navigating to /login when already authenticated triggers the
// SPA's layout guard to redirect away → the login form never
// renders → the fill() below times out. Probe /api/auth/me FIRST:
// 2xx means we're already signed in as SOMEONE. If that's the
// right admin, no-op; otherwise fall through to a fresh login.
const probe = await page.request.get('/api/auth/me').catch(() => null);
if (probe?.ok()) {
const body = (await probe.json().catch(() => ({}))) as { username?: string };
if (body.username === admin.username) return;
}
await page.goto('/login');
await page.locator('[data-testid="login-username-input"]').fill(admin.username);
await page.locator('[data-testid="login-password-input"]').fill(admin.password);
await page.locator('[data-testid="login-submit-btn"]').click();
// Post-login the SPA's `goto(redirectTarget)` sends the user
// to `/files` (default) or a `?redirect=` target. Match the
// default with a glob — the same shape `uiLogin` uses in
// `spa/coverage-helpers.ts` and that Playwright handles well
// under SvelteKit's client-side navigation. The 15s ceiling
// covers the OPAQUE-post-migration path: WASM load + KE1 +
// KE3 + Argon2id.
await page.waitForURL('**/files**', { timeout: 15_000 });
}
/**
+99
View File
@@ -0,0 +1,99 @@
import { test, expect, uiLogin } from './coverage-helpers';
/**
* SPA · DPoP multi-tab coverage — Gate 8 follow-up.
*
* IndexedDB, cookies, and `BroadcastChannel` are shared across every
* tab of a single Playwright `BrowserContext`. That's the correct
* shape for testing the multi-tab DPoP invariants:
*
* * shared keypair — a second tab opened after login already sees
* the first tab's persisted keypair via IndexedDB, so both tabs
* sign requests with the same JWK thumbprint (`dpop_jkt`) →
* server accepts both under a single bound session.
* * `BroadcastChannel('oxicloud-session-cleared')` — logout on
* one tab must cause the other tab's root layout to reset the
* session store and redirect to `/login` synchronously, without
* waiting for a network round trip to 401. See
* `frontend/src/lib/auth/session-broadcast.ts`.
*
* Runs under `OXICLOUD_AUTH_OPAQUE_MODE=migrate` +
* `OXICLOUD_DPOP_MODE=required` inherited from
* `tests/common/server.env` — so the actual OPAQUE login handshake
* fires (WASM client → KE1 → KE3) and every subsequent request
* carries a DPoP proof the middleware verifies.
*/
test.describe('SPA · DPoP multi-tab', () => {
test('a second tab shares the first tab\'s DPoP keypair (IndexedDB)', async ({ context }) => {
const tabA = await context.newPage();
await uiLogin(tabA);
// Sanity: tab A landed on an authenticated view.
await expect(tabA.getByTestId('appshell-logo-link')).toBeVisible();
// Second tab in the same context — cookies + IndexedDB shared.
const tabB = await context.newPage();
// Deep-link straight into an authenticated route. If the session
// cookie is shared (it is — cookies are per-context) AND the
// DPoP keypair is shared (it is — IndexedDB is per-origin per-
// context), tab B loads without redirecting to /login.
await tabB.goto('/files');
await expect(tabB.getByTestId('appshell-logo-link')).toBeVisible({ timeout: 15_000 });
// Both tabs' auth store agrees on the same user id — proves the
// shared cookie + shared keypair combination actually authorised
// an API call under DPoP=required against a bound session.
const [uidA, uidB] = await Promise.all([
tabA.evaluate(async () => {
const res = await fetch('/api/auth/me', { credentials: 'same-origin' });
return res.ok ? ((await res.json()) as { id: string }).id : null;
}),
tabB.evaluate(async () => {
const res = await fetch('/api/auth/me', { credentials: 'same-origin' });
return res.ok ? ((await res.json()) as { id: string }).id : null;
})
]);
expect(uidA).not.toBeNull();
expect(uidB).toBe(uidA);
});
test('logging out on one tab redirects the other via BroadcastChannel', async ({ context }) => {
const tabA = await context.newPage();
await uiLogin(tabA);
const tabB = await context.newPage();
await tabB.goto('/files');
await expect(tabB.getByTestId('appshell-logo-link')).toBeVisible({ timeout: 15_000 });
// Log out from tab A. Bypass the user-menu UI (which drifts as
// the shell markup evolves) — call `/api/auth/logout` directly
// then post to the BroadcastChannel by hand. Same shape as
// `endpoints/auth.ts::logout()` — the two side-effects the SPA
// does after a successful server logout are (a) wipe DPoP
// state (moot here since tab A is about to close/redirect) and
// (b) broadcast, which is exactly what we simulate.
await tabA.evaluate(async () => {
const csrf =
document.cookie
.split(';')
.map((c) => c.trim())
.find((c) => c.startsWith('oxicloud_csrf='))
?.slice('oxicloud_csrf='.length) ?? '';
const res = await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'x-csrf-token': csrf },
body: '{}'
});
if (!res.ok) throw new Error(`logout returned ${res.status}`);
new BroadcastChannel('oxicloud-session-cleared').postMessage({
kind: 'session_cleared',
at: Date.now()
});
});
// Tab B should navigate to /login on its own. No API call
// needed — the BroadcastChannel handler in the root layout
// does session.reset() + goto('/login').
await tabB.waitForURL('**/login**', { timeout: 5_000 });
});
});
+11
View File
@@ -21,8 +21,19 @@ test('favorite, view, and unfavorite a folder', async ({ page }) => {
await page.goto('/files');
await expect(page.getByTestId(name)).toBeVisible({ timeout: 15_000 });
await page.getByTestId(name).click({ button: 'right' });
// The context-menu `favorite` click is fire-and-forget in the SPA
// (closeContext() runs before the POST) — the test's next
// navigation can race the write. Wait for the actual POST to
// land before going to /favorites so the list-fetch there sees
// the new row committed. The batch test doesn't need this because
// it queues 2 POSTs sequentially, which naturally gives the first
// one time to commit.
const favorited = page.waitForResponse(
(r) => r.url().includes('/api/favorites') && r.request().method() === 'POST' && r.ok()
);
await page.getByTestId('files-ctx-favorite-item').click();
await expect(page.getByTestId('files-context-menu')).toHaveCount(0);
await favorited;
await page.goto('/favorites');
const row = page.getByTestId(name);