auth

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

commit 7545111f059c60da1d602735468001ef1da7702e
parent cf5327af0b0b8ecb9e9948baddb9ee75145cc0b5
Author: finwo <finwo@pm.me>
Date:   Wed, 21 Oct 2026 03:57:06 +0200

Add realm admin session listing and revocation APIs

Diffstat:
Aserver/src/controller/admin/sessions/list.js | 20++++++++++++++++++++
Aserver/src/controller/admin/sessions/revoke-realm.js | 34++++++++++++++++++++++++++++++++++
Aserver/src/controller/admin/sessions/terminate.js | 36++++++++++++++++++++++++++++++++++++
Aserver/src/lib/admin-auth.js | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/src/lib/admin-sessions.js | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/session.js | 39++++++++++++++++++++++++++++++++++++---
Mserver/test/http.test.js | 441+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 715 insertions(+), 3 deletions(-)

diff --git a/server/src/controller/admin/sessions/list.js b/server/src/controller/admin/sessions/list.js @@ -0,0 +1,20 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { listAdminRealmSessions } from '../../../lib/admin-sessions.js'; + +export default { + method: 'get', + path: '/api/v1/admin/realms/:realm/sessions', + name: 'admin.sessions.list', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const sessions = await listAdminRealmSessions(auth.systemDb, { + realmId: auth.realm.id, + actor: auth.user, + }); + + return new app.HttpOk({ sessions }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/sessions/revoke-realm.js b/server/src/controller/admin/sessions/revoke-realm.js @@ -0,0 +1,34 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { findAdminRealmSession } from '../../../lib/admin-sessions.js'; +import { HttpError } from '../../../lib/http/http-error.js'; +import { revokeSessionRealm } from '../../../lib/session.js'; + +export default { + method: 'delete', + path: '/api/v1/admin/realms/:realm/sessions/:publicId/realm', + name: 'admin.sessions.revoke-realm', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const session = await findAdminRealmSession(auth.systemDb, { + realmId: auth.realm.id, + publicId: req.params.publicId, + }); + if (!session) { + throw new HttpError(404, 'session_not_found', 'Session not found'); + } + + const binding = await revokeSessionRealm(auth.systemDb, { + sessionId: session.id, + realmId: auth.realm.id, + revokedBy: auth.user.id, + }); + + return new app.HttpOk({ + ok: true, + revoked_at: binding.revoked_at, + }); + }, +}; diff --git a/server/src/controller/admin/sessions/terminate.js b/server/src/controller/admin/sessions/terminate.js @@ -0,0 +1,36 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { + canTerminateSession, + findAdminRealmSession, +} from '../../../lib/admin-sessions.js'; +import { HttpError } from '../../../lib/http/http-error.js'; +import { destroySessionById } from '../../../lib/session.js'; + +export default { + method: 'delete', + path: '/api/v1/admin/realms/:realm/sessions/:publicId', + name: 'admin.sessions.terminate', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const session = await findAdminRealmSession(auth.systemDb, { + realmId: auth.realm.id, + publicId: req.params.publicId, + }); + if (!session) { + throw new HttpError(404, 'session_not_found', 'Session not found'); + } + if (!canTerminateSession(auth.user, session, auth.realm.id)) { + throw new HttpError( + 403, + 'forbidden', + 'Only home-realm and system admins can terminate this session' + ); + } + + await destroySessionById(auth.systemDb, session.id); + return new app.HttpOk({ ok: true }); + }, +}; diff --git a/server/src/lib/admin-auth.js b/server/src/lib/admin-auth.js @@ -0,0 +1,73 @@ +import { app } from '../app.js'; +import { HttpError } from './http/http-error.js'; +import { resolveHostContext } from './host-context.js'; +import { canonicalIssuer } from './oidc/context.js'; +import { verifyToken } from './oidc/keys.js'; +import { isRealmAdmin, isSystemAdmin } from './policy.js'; +import { getSystemDatabase, openRealmDatabase, resolveRealm } from './realm.js'; +import { findUserById, getMembership, getUserRoles } from './users.js'; + +function bearerToken(req) { + const header = String(req.headers.authorization || ''); + return header.startsWith('Bearer ') ? header.slice(7) : null; +} + +export async function authenticateAdminRequest(req, { realmSlug }) { + const hostContext = await resolveHostContext(req, { + publicUrl: app.config.server.public_url, + }); + if (hostContext.mode === 'client') { + throw new HttpError(404, 'not_found', 'Not found'); + } + + const realm = await resolveRealm({ + host: hostContext.host, + slug: realmSlug, + }); + const realmDb = await openRealmDatabase(realm); + const token = bearerToken(req); + if (!token) { + throw new HttpError(401, 'invalid_token', 'A bearer token is required'); + } + + let payload; + try { + payload = await verifyToken(realmDb, token, { + issuer: canonicalIssuer(app.config.server.public_url, realm.slug), + audience: 'admin', + }); + } catch { + throw new HttpError(401, 'invalid_token', 'The access token is invalid'); + } + + if (payload.client_id !== 'admin' || !payload.sub || !payload.sid) { + throw new HttpError(401, 'invalid_token', 'The access token is invalid'); + } + + const systemDb = getSystemDatabase(); + const user = await findUserById(systemDb, payload.sub); + if (!user || user.status !== 'active') { + throw new HttpError(401, 'invalid_token', 'The user is not available'); + } + + const session = await systemDb.get( + `SELECT id, user_id + FROM sessions + WHERE id = {id} AND user_id = {userId} AND expires_at > {now}`, + { id: payload.sid, userId: user.id, now: Date.now() } + ); + if (!session) { + throw new HttpError(401, 'invalid_token', 'The admin session is not active'); + } + + const membership = await getMembership(realmDb, user.id); + const roles = await getUserRoles(realmDb, user.id); + if ( + !isSystemAdmin(user) && + !(membership?.status === 'active' && isRealmAdmin(roles)) + ) { + throw new HttpError(403, 'forbidden', 'Realm admin access is required'); + } + + return { systemDb, realmDb, realm, user, membership, roles, session }; +} diff --git a/server/src/lib/admin-sessions.js b/server/src/lib/admin-sessions.js @@ -0,0 +1,75 @@ +import { isSystemAdmin } from './policy.js'; + +const ADMIN_SESSION_FIELDS = ` + s.id, s.public_id, s.group_id, s.user_id, s.scope_type, s.scope_host, + s.client_id, s.created_at, s.last_seen_at, s.expires_at, s.user_agent, s.ip, + u.username, u.display_name, u.home_realm_id, u.status AS user_status, + sr.revoked_at, sr.revoked_by +`; + +function serialize(row, actor, realmId) { + return { + public_id: row.public_id, + user: { + id: row.user_id, + username: row.username, + display_name: row.display_name, + home_realm_id: row.home_realm_id, + status: row.user_status, + }, + scope: { + type: row.scope_type, + host: row.scope_host, + client_id: row.client_id, + }, + created_at: row.created_at, + last_seen_at: row.last_seen_at, + expires_at: row.expires_at, + user_agent: row.user_agent, + ip: row.ip, + revoked_at: row.revoked_at, + revoked_by: row.revoked_by, + can_terminate: canTerminateSession(actor, row, realmId), + }; +} + +export function canTerminateSession(actor, session, realmId) { + return isSystemAdmin(actor) || session.home_realm_id === realmId; +} + +export async function listAdminRealmSessions( + systemDb, + { realmId, actor, now = Date.now() } +) { + const rows = await systemDb.all( + `SELECT ${ADMIN_SESSION_FIELDS} + FROM sessions s + JOIN users u ON u.id = s.user_id + LEFT JOIN session_realms sr + ON sr.session_id = s.id AND sr.realm_id = {realmId} + WHERE s.expires_at > {now} + AND (u.home_realm_id = {realmId} OR sr.session_id IS NOT NULL) + ORDER BY s.last_seen_at DESC, s.created_at DESC`, + { realmId, now } + ); + + return rows.map((row) => serialize(row, actor, realmId)); +} + +export async function findAdminRealmSession( + systemDb, + { realmId, publicId, now = Date.now() } +) { + return systemDb.get( + `SELECT ${ADMIN_SESSION_FIELDS} + FROM sessions s + JOIN users u ON u.id = s.user_id + LEFT JOIN session_realms sr + ON sr.session_id = s.id AND sr.realm_id = {realmId} + WHERE s.public_id = {publicId} + AND s.expires_at > {now} + AND (u.home_realm_id = {realmId} OR sr.session_id IS NOT NULL) + LIMIT 1`, + { realmId, publicId, now } + ); +} diff --git a/server/src/lib/session.js b/server/src/lib/session.js @@ -500,6 +500,28 @@ export async function authenticateRequest({ return { group, session, user, membership, roles }; } +async function removeSession(tx, session, now) { + const group = await tx.get( + 'SELECT active_session_id FROM session_groups WHERE id = {id}', + { id: session.group_id } + ); + await tx.run('DELETE FROM sessions WHERE id = {id}', { id: session.id }); + if (!group) return { groupDeleted: true }; + if (group.active_session_id !== session.id) return { groupDeleted: false }; + + const next = await nextActiveSession(tx, session.group_id, now); + if (next) { + await tx.run( + 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}', + { sessionId: next.id, id: session.group_id } + ); + return { groupDeleted: false }; + } + + await deleteGroup(tx, session.group_id); + return { groupDeleted: true }; +} + export async function destroySession(systemDb, token) { if (!token) return { groupDeleted: true }; @@ -508,9 +530,7 @@ export async function destroySession(systemDb, token) { if (!group) return { groupDeleted: true }; const session = await findActiveSession(tx, group); - if (session) { - await tx.run('DELETE FROM sessions WHERE id = {id}', { id: session.id }); - } + if (session) return removeSession(tx, session, Date.now()); const next = await nextActiveSession(tx, group.id, Date.now()); if (next) { @@ -526,6 +546,19 @@ export async function destroySession(systemDb, token) { }); } +export async function destroySessionById(systemDb, sessionId, now = Date.now()) { + return systemDb.transaction(async (tx) => { + const session = await tx.get( + 'SELECT id, group_id FROM sessions WHERE id = {id}', + { id: sessionId } + ); + if (!session) return { deleted: false, groupDeleted: false }; + + const result = await removeSession(tx, session, now); + return { deleted: true, ...result }; + }); +} + export async function getSessionRealmBinding(systemDb, sessionId, realmId) { return systemDb.get( `SELECT session_id, realm_id, created_at, last_seen_at, revoked_at, revoked_by diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -188,6 +188,39 @@ function activeSessionId(env, cookie) { }); } +function activeSessionPublicId(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 s.public_id + FROM sessions s + JOIN session_groups g ON g.active_session_id = s.id + WHERE g.id = ?` + ) + .get(groupId); + return row.public_id; + }); +} + +function withRealmDatabase(env, slug, fn) { + const system = new DatabaseSync(env.AUTH_DATABASE_PATH); + try { + const realm = system + .prepare('SELECT db_file FROM realms WHERE slug = ?') + .get(slug); + const database = new DatabaseSync(path.join(env.AUTH_REALMS_PATH, realm.db_file)); + try { + return fn(database); + } finally { + database.close(); + } + } finally { + system.close(); + } +} + 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(); @@ -212,6 +245,48 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { const globex = (options = {}) => request(port, { host: `globex.localhost:${port}`, ...options }); const app = (options = {}) => request(port, { host: `app.acme.localhost:${port}`, ...options }); + async function accessToken( + requester, + { clientId, identifier, redirectUri, scope = 'openid profile' } + ) { + const { verifier, challenge } = pkce(); + const authorizePath = + `/oidc/${clientId}/authorize?response_type=code&client_id=${clientId}` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scope)}` + + `&state=admin-api&code_challenge=${challenge}&code_challenge_method=S256`; + + const first = await requester({ path: authorizePath }); + assert.equal(first.status, 302); + let jar = mergeCookies('', first); + const login = await requester({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: clientId, identifier, password: 'demo' }, + cookie: jar, + }); + assert.equal(login.status, 200); + jar = mergeCookies(jar, login); + + const second = await requester({ path: authorizePath, cookie: jar }); + assert.equal(second.status, 302); + const code = locationQuery(second).searchParams.get('code'); + assert.ok(code); + + const tokenResponse = await requester({ + method: 'POST', + path: `/oidc/${clientId}/token`, + form: { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: clientId, + code_verifier: verifier, + }, + }); + assert.equal(tokenResponse.status, 200); + return { access_token: tokenResponse.json.access_token, cookie: jar }; + } + await t.test('realm metadata is served for a realm hostname', async () => { const response = await acme({ path: '/api/v1/realm' }); assert.equal(response.status, 200); @@ -981,6 +1056,372 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(tokenResponse.status, 200); }); + await t.test('admin session APIs require an active admin token', async () => { + const missing = await acme({ path: '/api/v1/admin/realms/acme/sessions' }); + assert.equal(missing.status, 401); + assert.equal(missing.json.error.code, 'invalid_token'); + + const alice = await accessToken(acme, { + clientId: 'internal-app', + identifier: 'alice@acme.test', + redirectUri: `${origin('app.acme.localhost')}/callback`, + }); + const wrongAudience = await acme({ + path: '/api/v1/admin/realms/acme/sessions', + bearer: alice.access_token, + }); + assert.equal(wrongAudience.status, 401); + assert.equal(wrongAudience.json.error.code, 'invalid_token'); + }); + + await t.test('realm admins see bound and home-realm sessions', async () => { + const aliceLogin = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + assert.equal(aliceLogin.status, 200); + const aliceCookie = mergeCookies('', aliceLogin); + const alicePublicId = activeSessionPublicId(env, aliceCookie); + + const guest = await accessToken(acme, { + clientId: 'acme-members-app', + identifier: 'guest@personal.test', + redirectUri: `${origin('members.localhost')}/callback`, + }); + const guestPublicId = activeSessionPublicId(env, guest.cookie); + + const contractor = await accessToken(globex, { + clientId: 'globex-members-app', + identifier: 'contractor@personal.test', + redirectUri: `${origin('members.localhost')}/callback`, + }); + const contractorPublicId = activeSessionPublicId(env, contractor.cookie); + + const admin = await accessToken(acme, { + clientId: 'admin', + identifier: 'it@acme.test', + redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, + }); + const response = await acme({ + path: '/api/v1/admin/realms/acme/sessions', + bearer: admin.access_token, + }); + assert.equal(response.status, 200); + assert.equal(response.headers['cache-control'], 'no-store'); + + const aliceSession = response.json.sessions.find( + (session) => session.public_id === alicePublicId + ); + assert.equal(aliceSession.user.username, 'alice'); + assert.equal(aliceSession.revoked_at, null); + assert.equal(aliceSession.can_terminate, true); + assert.equal('id' in aliceSession, false); + + const guestSession = response.json.sessions.find( + (session) => session.public_id === guestPublicId + ); + assert.equal(guestSession.user.username, 'guest'); + assert.equal(guestSession.can_terminate, false); + + assert.equal( + response.json.sessions.some( + (session) => session.public_id === contractorPublicId + ), + false + ); + }); + + await t.test('guest realm admins can revoke realm access but not terminate', async () => { + const admin = await accessToken(globex, { + clientId: 'admin', + identifier: 'contractor@personal.test', + redirectUri: `${origin('globex.localhost')}/oidc/admin/callback`, + }); + const alice = await accessToken(globex, { + clientId: 'globex-members-app', + identifier: 'alice@acme.test', + redirectUri: `${origin('members.localhost')}/callback`, + }); + const alicePublicId = activeSessionPublicId(env, alice.cookie); + + const list = await globex({ + path: '/api/v1/admin/realms/globex/sessions', + bearer: admin.access_token, + }); + assert.equal(list.status, 200); + assert.equal( + list.json.sessions.find((session) => session.public_id === alicePublicId) + .can_terminate, + false + ); + + const revoked = await globex({ + method: 'DELETE', + path: `/api/v1/admin/realms/globex/sessions/${alicePublicId}/realm`, + bearer: admin.access_token, + }); + assert.equal(revoked.status, 200); + assert.ok(revoked.json.revoked_at); + + const { binding, actorId } = withSystemDatabase(env, (database) => { + const actor = database + .prepare('SELECT id FROM users WHERE username = ?') + .get('contractor'); + const session = database + .prepare('SELECT id FROM sessions WHERE public_id = ?') + .get(alicePublicId); + return { + actorId: actor.id, + binding: database + .prepare( + `SELECT sr.revoked_at, sr.revoked_by + FROM session_realms sr + WHERE sr.session_id = ? + AND sr.realm_id = (SELECT id FROM realms WHERE slug = 'globex')` + ) + .get(session.id), + }; + }); + assert.ok(binding.revoked_at); + assert.equal(binding.revoked_by, actorId); + + const { challenge } = pkce(); + const authorizePath = + `/oidc/globex-members-app/authorize?response_type=code` + + `&client_id=globex-members-app&redirect_uri=${encodeURIComponent( + `${origin('members.localhost')}/callback` + )}&scope=openid&state=reauth` + + `&code_challenge=${challenge}&code_challenge_method=S256`; + const reauth = await globex({ path: authorizePath, cookie: alice.cookie }); + assert.equal(reauth.status, 302); + const reauthLocation = locationQuery(reauth); + assert.equal(reauthLocation.pathname, '/oidc/globex-members-app/login'); + assert.equal(reauthLocation.searchParams.get('reauth'), '1'); + + const terminate = await globex({ + method: 'DELETE', + path: `/api/v1/admin/realms/globex/sessions/${alicePublicId}`, + bearer: admin.access_token, + }); + assert.equal(terminate.status, 403); + assert.equal(terminate.json.error.code, 'forbidden'); + + const stillSignedIn = await globex({ + path: '/api/v1/session', + cookie: alice.cookie, + }); + assert.equal(stillSignedIn.status, 200); + }); + + await t.test('home realm admins terminate only the selected session', async () => { + const admin = await accessToken(acme, { + clientId: 'admin', + identifier: 'it@acme.test', + redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, + }); + + const aliceAcme = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + const aliceAcmeCookie = mergeCookies('', aliceAcme); + const aliceAcmePublicId = activeSessionPublicId(env, aliceAcmeCookie); + + const aliceGlobex = await accessToken(globex, { + clientId: 'globex-members-app', + identifier: 'alice@acme.test', + redirectUri: `${origin('members.localhost')}/callback`, + }); + + const terminated = await acme({ + method: 'DELETE', + path: `/api/v1/admin/realms/acme/sessions/${aliceAcmePublicId}`, + bearer: admin.access_token, + }); + assert.equal(terminated.status, 200); + assert.equal(terminated.json.ok, true); + + const acmeSession = await acme({ + path: '/api/v1/session', + cookie: aliceAcmeCookie, + }); + assert.equal(acmeSession.status, 401); + + const globexSession = await globex({ + path: '/api/v1/session', + cookie: aliceGlobex.cookie, + }); + assert.equal(globexSession.status, 200); + + const deleted = withSystemDatabase(env, (database) => + database + .prepare('SELECT public_id FROM sessions WHERE public_id = ?') + .get(aliceAcmePublicId) + ); + assert.equal(deleted, undefined); + }); + + await t.test('terminating an inactive account keeps the active account', async () => { + const aliceLogin = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + let cookie = 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, + }); + cookie = mergeCookies(cookie, itLogin); + + const group = await acme({ path: '/api/v1/session', cookie }); + const aliceAccount = group.json.accounts.find( + (account) => account.user.username === 'alice' + ); + + const admin = await accessToken(acme, { + clientId: 'admin', + identifier: 'it@acme.test', + redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, + }); + const terminated = await acme({ + method: 'DELETE', + path: `/api/v1/admin/realms/acme/sessions/${aliceAccount.public_id}`, + bearer: admin.access_token, + }); + assert.equal(terminated.status, 200); + + const after = await acme({ path: '/api/v1/session', cookie }); + assert.equal(after.status, 200); + assert.equal(after.json.user.username, 'acme-it'); + assert.deepEqual( + after.json.accounts.map((account) => account.user.username), + ['acme-it'] + ); + }); + + await t.test('system admins can terminate guest sessions', async () => { + const admin = await accessToken(globex, { + clientId: 'admin', + identifier: 'admin@system.test', + redirectUri: `${origin('globex.localhost')}/oidc/admin/callback`, + }); + const alice = await accessToken(globex, { + clientId: 'globex-members-app', + identifier: 'alice@acme.test', + redirectUri: `${origin('members.localhost')}/callback`, + }); + const alicePublicId = activeSessionPublicId(env, alice.cookie); + + const list = await globex({ + path: '/api/v1/admin/realms/globex/sessions', + bearer: admin.access_token, + }); + assert.equal(list.status, 200); + assert.equal( + list.json.sessions.find((session) => session.public_id === alicePublicId) + .can_terminate, + true + ); + + const terminated = await globex({ + method: 'DELETE', + path: `/api/v1/admin/realms/globex/sessions/${alicePublicId}`, + bearer: admin.access_token, + }); + assert.equal(terminated.status, 200); + + const session = await globex({ + path: '/api/v1/session', + cookie: alice.cookie, + }); + assert.equal(session.status, 401); + }); + + await t.test('admin token sessions and realms are enforced', async () => { + const admin = await accessToken(acme, { + clientId: 'admin', + identifier: 'it@acme.test', + redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, + }); + const adminPublicId = activeSessionPublicId(env, admin.cookie); + + const otherRealm = await acme({ + path: '/api/v1/admin/realms/globex/sessions', + bearer: admin.access_token, + }); + assert.equal(otherRealm.status, 404); + assert.equal(otherRealm.json.error.code, 'unknown_realm'); + + const clientHost = await app({ + path: '/api/v1/admin/realms/acme/sessions', + bearer: admin.access_token, + }); + assert.equal(clientHost.status, 404); + + const canonical = await identity({ + path: '/api/v1/admin/realms/acme/sessions', + bearer: admin.access_token, + }); + assert.equal(canonical.status, 200); + + const terminated = await acme({ + method: 'DELETE', + path: `/api/v1/admin/realms/acme/sessions/${adminPublicId}`, + bearer: admin.access_token, + }); + assert.equal(terminated.status, 200); + + const deadToken = await acme({ + path: '/api/v1/admin/realms/acme/sessions', + bearer: admin.access_token, + }); + assert.equal(deadToken.status, 401); + assert.equal(deadToken.json.error.code, 'invalid_token'); + }); + + await t.test('admin access is re-read from the realm database', async () => { + const admin = await accessToken(acme, { + clientId: 'admin', + identifier: 'it@acme.test', + redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, + }); + const actor = withSystemDatabase(env, (database) => + database.prepare('SELECT id FROM users WHERE username = ?').get('acme-it') + ); + + withRealmDatabase(env, 'acme', (database) => { + const role = database + .prepare('SELECT id FROM roles WHERE slug = ?') + .get('realm-admin'); + database + .prepare('DELETE FROM membership_roles WHERE user_id = ? AND role_id = ?') + .run(actor.id, role.id); + }); + + try { + const response = await acme({ + path: '/api/v1/admin/realms/acme/sessions', + bearer: admin.access_token, + }); + assert.equal(response.status, 403); + assert.equal(response.json.error.code, 'forbidden'); + } finally { + withRealmDatabase(env, 'acme', (database) => { + const role = database + .prepare('SELECT id FROM roles WHERE slug = ?') + .get('realm-admin'); + database + .prepare('INSERT INTO membership_roles (user_id, role_id) VALUES (?, ?)') + .run(actor.id, role.id); + }); + } + }); + await t.test('confidential clients authenticate with client_secret_basic', async () => { const { verifier, challenge } = pkce(); const redirectUri = `${origin('confidential.localhost')}/callback`;