auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

commit cf5327af0b0b8ecb9e9948baddb9ee75145cc0b5
parent c9a2cee3a170a9ad80e713ada4ab29fe065c31bb
Author: finwo <finwo@pm.me>
Date:   Wed, 21 Oct 2026 03:17:44 +0200

Enforce realm revocation with forced password re-verification

Diffstat:
Mserver/src/controller/login/password.js | 7++++++-
Mserver/src/controller/oidc.js | 14++++++++++++++
Mserver/src/lib/session.js | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/test/http.test.js | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/test/session.test.js | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/web/src/screen/login.tsx | 27++++++++++++++++++++++-----
6 files changed, 500 insertions(+), 6 deletions(-)

diff --git a/server/src/controller/login/password.js b/server/src/controller/login/password.js @@ -16,6 +16,7 @@ import { SHORT_SESSION_TTL, createHostSession, purgeExpiredSessions, + reauthenticateSession, requestIp, requestToken, setSessionCookie, @@ -130,12 +131,16 @@ export default { userAgent: req.headers['user-agent'] || null, ip: requestIp(req), }); + const authTime = await reauthenticateSession(systemDb, { + sessionId: session.id, + realmId: realm.id, + }); setSessionCookie(res, req, token, session.ttl); if (pendingClient && pending) { await selectAuthRequestAccount(realmDb, pending.id, { userId: user.id, sessionId: session.id, - authTime: session.auth_time, + authTime, }); } await updateLastLogin(systemDb, user.id); diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js @@ -37,6 +37,7 @@ import { bindSessionRealm, clearSessionCookie, destroySession, + getSessionRealmBinding, listSessionAccounts, requestToken, } from '../lib/session.js'; @@ -256,6 +257,19 @@ async function authorize(context, client, req, res) { return redirect(res, endpointUrls(context).login); } + const binding = await getSessionRealmBinding( + systemDb, + auth.session.id, + context.realm.id + ); + if (binding?.revoked_at) { + await clearAuthRequestSelection(db, pending.id); + setAuthRequestCookie(res, req, context.realm, pending.id); + const login = new URL(endpointUrls(context).login); + login.searchParams.set('reauth', '1'); + return redirect(res, login.toString()); + } + await bindSessionRealm(systemDb, auth.session.id, context.realm.id); await completeAuthRequest(db, pending.id, { userId: auth.user.id, diff --git a/server/src/lib/session.js b/server/src/lib/session.js @@ -526,6 +526,89 @@ export async function destroySession(systemDb, token) { }); } +export async function getSessionRealmBinding(systemDb, sessionId, realmId) { + return systemDb.get( + `SELECT session_id, realm_id, created_at, last_seen_at, revoked_at, revoked_by + FROM session_realms + WHERE session_id = {sessionId} AND realm_id = {realmId}`, + { sessionId, realmId } + ); +} + +export async function revokeSessionRealm( + systemDb, + { sessionId, realmId, revokedBy = null, now = Date.now() } +) { + return systemDb.transaction(async (tx) => { + const existing = await getSessionRealmBinding(tx, sessionId, realmId); + if (existing) { + if (!existing.revoked_at) { + await tx.run( + `UPDATE session_realms + SET revoked_at = {now}, revoked_by = {revokedBy} + WHERE session_id = {sessionId} AND realm_id = {realmId}`, + { now, revokedBy, sessionId, realmId } + ); + existing.revoked_at = now; + existing.revoked_by = revokedBy; + } + return existing; + } + + await tx.run( + `INSERT INTO session_realms + (session_id, realm_id, created_at, last_seen_at, revoked_at, revoked_by) + VALUES + ({sessionId}, {realmId}, {now}, {now}, {now}, {revokedBy})`, + { sessionId, realmId, now, revokedBy } + ); + return { + session_id: sessionId, + realm_id: realmId, + created_at: now, + last_seen_at: now, + revoked_at: now, + revoked_by: revokedBy, + }; + }); +} + +export async function revokeRealmSessions( + systemDb, + { realmId, revokedBy = null, now = Date.now() } +) { + const result = await systemDb.run( + `UPDATE session_realms + SET revoked_at = {now}, revoked_by = {revokedBy} + WHERE realm_id = {realmId} AND revoked_at IS NULL`, + { realmId, revokedBy, now } + ); + return result.changes; +} + +export async function reauthenticateSession( + systemDb, + { sessionId, realmId, now = Date.now() } +) { + const authTime = Math.floor(now / 1000); + + return systemDb.transaction(async (tx) => { + await tx.run( + `UPDATE sessions + SET auth_time = {authTime}, last_seen_at = {now} + WHERE id = {id}`, + { authTime, now, id: sessionId } + ); + await tx.run( + `UPDATE session_realms + SET revoked_at = NULL, revoked_by = NULL, last_seen_at = {now} + WHERE session_id = {sessionId} AND realm_id = {realmId}`, + { now, sessionId, realmId } + ); + return authTime; + }); +} + export async function bindSessionRealm(systemDb, sessionId, realmId, now = Date.now()) { const existing = await systemDb.get( `SELECT session_id, realm_id, revoked_at diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -161,6 +161,33 @@ function locationQuery(response) { return new URL(response.headers.location, 'http://localhost'); } +function cookieValue(cookie, name) { + const pair = cookie + .split('; ') + .find((value) => value.startsWith(`${name}=`)); + return pair ? pair.slice(name.length + 1) : null; +} + +function withSystemDatabase(env, fn) { + const database = new DatabaseSync(env.AUTH_DATABASE_PATH); + try { + return fn(database); + } finally { + database.close(); + } +} + +function activeSessionId(env, cookie) { + const token = cookieValue(cookie, 'auth_session'); + const groupId = crypto.createHash('sha256').update(token).digest('hex'); + return withSystemDatabase(env, (database) => { + const row = database + .prepare('SELECT active_session_id FROM session_groups WHERE id = ?') + .get(groupId); + return row.active_session_id; + }); +} + test('HTTP realm, login, OIDC and logout flows', async (t) => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-http-')); const port = await freePort(); @@ -474,6 +501,166 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(payload.preferred_username, 'alice'); }); + await t.test('a revoked realm binding requires password re-verification', async () => { + const login = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + assert.equal(login.status, 200); + let jar = mergeCookies('', login); + + const { verifier, challenge } = pkce(); + const redirectUri = `${origin('app.acme.localhost')}/callback`; + const authorizePath = + `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` + + `&state=state-revoked&code_challenge=${challenge}&code_challenge_method=S256`; + + const first = await acme({ path: authorizePath, cookie: jar }); + assert.equal(first.status, 302); + assert.ok(locationQuery(first).searchParams.get('code')); + + const sessionId = activeSessionId(env, jar); + const revokedAt = Date.now(); + withSystemDatabase(env, (database) => { + database + .prepare( + `UPDATE session_realms + SET revoked_at = ?, revoked_by = ? + WHERE session_id = ? + AND realm_id = (SELECT id FROM realms WHERE slug = 'acme')` + ) + .run(revokedAt, 'test-admin', sessionId); + }); + + const reauth = await acme({ path: authorizePath, cookie: jar }); + assert.equal(reauth.status, 302); + const reauthLocation = locationQuery(reauth); + assert.equal(reauthLocation.pathname, '/oidc/internal-app/login'); + assert.equal(reauthLocation.searchParams.get('reauth'), '1'); + jar = mergeCookies(jar, reauth); + + const relogin = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + cookie: jar, + }); + assert.equal(relogin.status, 200); + assert.equal(relogin.json.pending_auth_request, true); + jar = mergeCookies(jar, relogin); + + const second = await acme({ path: authorizePath, cookie: jar }); + assert.equal(second.status, 302); + const code = locationQuery(second).searchParams.get('code'); + assert.ok(code); + + const binding = withSystemDatabase(env, (database) => + database + .prepare( + `SELECT revoked_at + FROM session_realms + WHERE session_id = ? + AND realm_id = (SELECT id FROM realms WHERE slug = 'acme')` + ) + .get(sessionId) + ); + assert.equal(binding.revoked_at, null); + + const tokenResponse = await acme({ + method: 'POST', + path: '/oidc/internal-app/token', + form: { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: 'internal-app', + code_verifier: verifier, + }, + }); + assert.equal(tokenResponse.status, 200); + }); + + await t.test('the account chooser cannot bypass a revoked realm binding', async () => { + const aliceLogin = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + let jar = mergeCookies('', aliceLogin); + const itLogin = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'it@acme.test', password: 'demo' }, + cookie: jar, + }); + jar = mergeCookies(jar, itLogin); + + const { challenge } = pkce(); + const redirectUri = `${origin('app.acme.localhost')}/callback`; + const authorizePath = + `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` + + `&state=state-revoked-chooser&code_challenge=${challenge}&code_challenge_method=S256`; + + const chooser = await acme({ path: authorizePath, cookie: jar }); + assert.equal(chooser.status, 302); + assert.equal(locationQuery(chooser).pathname, '/oidc/internal-app/login'); + jar = mergeCookies(jar, chooser); + + const session = await acme({ path: '/api/v1/session', cookie: jar }); + const itAccount = session.json.accounts.find( + (account) => account.user.username === 'acme-it' + ); + const selected = await acme({ + method: 'POST', + path: '/api/v1/session/select', + body: { public_id: itAccount.public_id, client_id: 'internal-app' }, + cookie: jar, + }); + assert.equal(selected.status, 200); + assert.equal(selected.json.pending_auth_request, true); + + const authorized = await acme({ path: authorizePath, cookie: jar }); + assert.equal(authorized.status, 302); + assert.ok(locationQuery(authorized).searchParams.get('code')); + + const sessionId = activeSessionId(env, jar); + withSystemDatabase(env, (database) => { + database + .prepare( + `UPDATE session_realms + SET revoked_at = ?, revoked_by = ? + WHERE session_id = ? + AND realm_id = (SELECT id FROM realms WHERE slug = 'acme')` + ) + .run(Date.now(), 'test-admin', sessionId); + }); + + const nextChooser = await acme({ path: authorizePath, cookie: jar }); + assert.equal(nextChooser.status, 302); + const chooserLocation = locationQuery(nextChooser); + assert.equal(chooserLocation.pathname, '/oidc/internal-app/login'); + assert.equal(chooserLocation.searchParams.get('reauth'), null); + jar = mergeCookies(jar, nextChooser); + + const reselected = await acme({ + method: 'POST', + path: '/api/v1/session/select', + body: { public_id: itAccount.public_id, client_id: 'internal-app' }, + cookie: jar, + }); + assert.equal(reselected.status, 200); + assert.equal(reselected.json.pending_auth_request, true); + + const blocked = await acme({ path: authorizePath, cookie: jar }); + assert.equal(blocked.status, 302); + const blockedLocation = locationQuery(blocked); + assert.equal(blockedLocation.pathname, '/oidc/internal-app/login'); + assert.equal(blockedLocation.searchParams.get('reauth'), '1'); + }); + await t.test('unknown hosts are rejected by auth and session APIs', async () => { const unknown = (options = {}) => request(port, { host: `unknown.test:${port}`, ...options }); diff --git a/server/test/session.test.js b/server/test/session.test.js @@ -19,7 +19,11 @@ import { createHostSession, destroySession, getSessionByToken, + getSessionRealmBinding, listSessionAccounts, + reauthenticateSession, + revokeRealmSessions, + revokeSessionRealm, selectSessionAccount, } from '../src/lib/session.js'; import { createUser, ensureMembership } from '../src/lib/users.js'; @@ -485,3 +489,187 @@ test('realm bindings are inserted once and updated on repeat', async () => { await fs.rm(dir, { recursive: true, force: true }); } }); + +test('revoking one session realm leaves other realm bindings intact', async () => { + const { dir, realm, systemDb, userId } = await setup(); + try { + const other = await createRealm({ slug: 'globex', displayName: 'Globex' }); + const { session } = await createHostSession(systemDb, { + context: canonicalContext(), + userId, + ttl: SHORT_SESSION_TTL, + }); + + await bindSessionRealm(systemDb, session.id, realm.id, 1000); + await bindSessionRealm(systemDb, session.id, other.id, 1000); + + const revoked = await revokeSessionRealm(systemDb, { + sessionId: session.id, + realmId: realm.id, + revokedBy: 'admin', + now: 2000, + }); + assert.equal(revoked.revoked_at, 2000); + assert.equal(revoked.revoked_by, 'admin'); + + const acme = await getSessionRealmBinding(systemDb, session.id, realm.id); + assert.equal(acme.revoked_at, 2000); + const globex = await getSessionRealmBinding(systemDb, session.id, other.id); + assert.equal(globex.revoked_at, null); + + const again = await revokeSessionRealm(systemDb, { + sessionId: session.id, + realmId: realm.id, + revokedBy: 'second-admin', + now: 3000, + }); + assert.equal(again.revoked_at, 2000); + assert.equal(again.revoked_by, 'admin'); + } finally { + await closeRealms(); + await fs.rm(dir, { recursive: true, force: true }); + } +}); + +test('revoking an unbound session realm creates a revoked binding', async () => { + const { dir, realm, systemDb, userId } = await setup(); + try { + const { session } = await createHostSession(systemDb, { + context: canonicalContext(), + userId, + ttl: SHORT_SESSION_TTL, + }); + + await revokeSessionRealm(systemDb, { + sessionId: session.id, + realmId: realm.id, + revokedBy: 'admin', + now: 4000, + }); + + const binding = await getSessionRealmBinding(systemDb, session.id, realm.id); + assert.equal(binding.created_at, 4000); + assert.equal(binding.last_seen_at, 4000); + assert.equal(binding.revoked_at, 4000); + assert.equal(binding.revoked_by, 'admin'); + } finally { + await closeRealms(); + await fs.rm(dir, { recursive: true, force: true }); + } +}); + +test('revoking a realm marks every unrevoked binding for that realm', async () => { + const { dir, realm, systemDb, userId } = await setup(); + try { + const other = await createRealm({ slug: 'globex', displayName: 'Globex' }); + const first = await createHostSession(systemDb, { + context: canonicalContext('identity.test'), + userId, + ttl: SHORT_SESSION_TTL, + }); + const second = await createHostSession(systemDb, { + context: canonicalContext('other-identity.test'), + userId, + ttl: SHORT_SESSION_TTL, + }); + + await bindSessionRealm(systemDb, first.session.id, realm.id, 1000); + await bindSessionRealm(systemDb, first.session.id, other.id, 1000); + await bindSessionRealm(systemDb, second.session.id, realm.id, 1000); + + const changed = await revokeRealmSessions(systemDb, { + realmId: realm.id, + revokedBy: 'admin', + now: 5000, + }); + assert.equal(changed, 2); + + const firstAcme = await getSessionRealmBinding(systemDb, first.session.id, realm.id); + const secondAcme = await getSessionRealmBinding(systemDb, second.session.id, realm.id); + const firstGlobex = await getSessionRealmBinding(systemDb, first.session.id, other.id); + assert.equal(firstAcme.revoked_at, 5000); + assert.equal(secondAcme.revoked_at, 5000); + assert.equal(firstGlobex.revoked_at, null); + } finally { + await closeRealms(); + await fs.rm(dir, { recursive: true, force: true }); + } +}); + +test('reauthentication clears only the target realm and refreshes auth_time', async () => { + const { dir, realm, systemDb, userId } = await setup(); + try { + const other = await createRealm({ slug: 'globex', displayName: 'Globex' }); + const { session } = await createHostSession(systemDb, { + context: canonicalContext(), + userId, + ttl: SHORT_SESSION_TTL, + }); + + await bindSessionRealm(systemDb, session.id, realm.id, 1000); + await bindSessionRealm(systemDb, session.id, other.id, 1000); + await revokeSessionRealm(systemDb, { + sessionId: session.id, + realmId: realm.id, + revokedBy: 'admin', + now: 2000, + }); + await revokeSessionRealm(systemDb, { + sessionId: session.id, + realmId: other.id, + revokedBy: 'admin', + now: 2000, + }); + + const authTime = await reauthenticateSession(systemDb, { + sessionId: session.id, + realmId: realm.id, + now: 9000, + }); + assert.equal(authTime, 9); + + const acme = await getSessionRealmBinding(systemDb, session.id, realm.id); + const globex = await getSessionRealmBinding(systemDb, session.id, other.id); + assert.equal(acme.revoked_at, null); + assert.equal(acme.revoked_by, null); + assert.equal(acme.last_seen_at, 9000); + assert.equal(globex.revoked_at, 2000); + + const updated = await systemDb.get( + 'SELECT auth_time, last_seen_at FROM sessions WHERE id = {id}', + { id: session.id } + ); + assert.equal(updated.auth_time, 9); + assert.equal(updated.last_seen_at, 9000); + } finally { + await closeRealms(); + await fs.rm(dir, { recursive: true, force: true }); + } +}); + +test('binding a revoked realm does not clear the revocation', async () => { + const { dir, realm, systemDb, userId } = await setup(); + try { + const { session } = await createHostSession(systemDb, { + context: canonicalContext(), + userId, + ttl: SHORT_SESSION_TTL, + }); + + await bindSessionRealm(systemDb, session.id, realm.id, 1000); + await revokeSessionRealm(systemDb, { + sessionId: session.id, + realmId: realm.id, + revokedBy: 'admin', + now: 2000, + }); + await bindSessionRealm(systemDb, session.id, realm.id, 3000); + + const binding = await getSessionRealmBinding(systemDb, session.id, realm.id); + assert.equal(binding.revoked_at, 2000); + assert.equal(binding.last_seen_at, 1000); + } finally { + await closeRealms(); + await fs.rm(dir, { recursive: true, force: true }); + } +}); diff --git a/server/web/src/screen/login.tsx b/server/web/src/screen/login.tsx @@ -24,6 +24,16 @@ interface TextFieldAttrs { oninput: (value: string) => void; } +function queryParam(name: string) { + const query = (m.route.get() || '').split('?')[1] || ''; + return new URLSearchParams(query).get(name); +} + +function authorizeRoute() { + const path = (m.route.get() || '').split('?')[0]; + return path.replace(/\/login$/, '/authorize'); +} + const TextField: m.Component<TextFieldAttrs> = { view({ attrs }) { return ( @@ -58,10 +68,12 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = { signedIn: null as PasswordLoginResult['user'] | null, error: null as Error | null, pending: false, + reauth: false, oninit(this: any, vnode: any) { this.realmSlug = vnode.attrs.realm ?? null; this.clientId = vnode.attrs.clientId ?? null; + this.reauth = queryParam('reauth') === '1'; this.loadClient(); }, @@ -81,6 +93,10 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = { }, async loadAccounts(this: any) { + if (this.reauth) { + this.accounts = []; + return; + } try { const session = await getSession(); if (session.accounts.length >= 2) { @@ -122,8 +138,7 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = { ); if (result.pending_auth_request) { - const current = m.route.get() || ''; - m.route.set(current.replace(/\/login$/, '/authorize')); + m.route.set(authorizeRoute()); return; } @@ -149,8 +164,7 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = { try { const result = await selectSession(account.public_id, this.clientId); if (result.pending_auth_request) { - const current = m.route.get() || ''; - m.route.set(current.replace(/\/login$/, '/authorize')); + m.route.set(authorizeRoute()); return; } @@ -271,6 +285,9 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = { if (!this.pending && this.identifier.trim()) this.submitIdentifier(); }} > + {this.reauth ? ( + <p class="auth-note">Confirm your password to continue.</p> + ) : null} <TextField id="identifier" label="Email or username" @@ -284,7 +301,7 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = { /> {this.error ? <p class="auth-error">{this.error.message}</p> : null} <div class="auth-actions"> - {this.accounts.length >= 2 ? ( + {!this.reauth && this.accounts.length >= 2 ? ( <button class="auth-link" type="button" onclick={() => this.backToAccounts()}> Back to accounts </button>