auth

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

commit 639051eceba34bb7f930902fdb7566a2bccd0dd4
parent b3892e25d78216389b6b06933789f4c34b21dad7
Author: finwo <finwo@pm.me>
Date:   Tue, 20 Oct 2026 22:11:17 +0200

Add client-scoped OIDC provider with global users and virtual admin/account clients

Diffstat:
Mserver/auth.example.yaml | 1+
Aserver/migrations/sqlite/realm/002_oidc.sql | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/migrations/sqlite/system/002_client_hosts.sql | 8++++++++
Aserver/migrations/sqlite/system/003_system_admin.sql | 1+
Mserver/package-lock.json | 10++++++++++
Mserver/package.json | 1+
Mserver/scripts/seed-demo.js | 106++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mserver/src/controller/login/password.js | 46++++++++++++++++++++++++++++++++++++++--------
Aserver/src/controller/oidc.js | 514+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/controller/session/show.js | 3++-
Mserver/src/index.js | 8+++++++-
Mserver/src/lib/config.js | 11+++++++++++
Aserver/src/lib/oidc/clients.js | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/src/lib/oidc/context.js | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/src/lib/oidc/keys.js | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/src/lib/oidc/requests.js | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/policy.js | 9+++++++--
Mserver/src/lib/realm.js | 144+++++++++++++++++++++++++++++++------------------------------------------------
Mserver/src/lib/session.js | 5-----
Mserver/src/lib/users.js | 20++++++++++++++------
Mserver/test/http.test.js | 332++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mserver/test/policy.test.js | 42+++++++++++++++++++++++++++++++++++++++++-
Mserver/test/session.test.js | 15++++++++++-----
Mserver/web/src/main.ts | 21++++++++++++++-------
Mserver/web/src/screen/login.tsx | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mserver/web/src/util/api.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++----
26 files changed, 1781 insertions(+), 192 deletions(-)

diff --git a/server/auth.example.yaml b/server/auth.example.yaml @@ -1,6 +1,7 @@ server: host: 0.0.0.0 port: 3000 + public_url: http://localhost:3000 database: dialect: sqlite diff --git a/server/migrations/sqlite/realm/002_oidc.sql b/server/migrations/sqlite/realm/002_oidc.sql @@ -0,0 +1,55 @@ +ALTER TABLE oidc_clients ADD COLUMN branding TEXT NOT NULL DEFAULT '{}'; +ALTER TABLE oidc_clients ADD COLUMN client_secret_hash TEXT; +ALTER TABLE oidc_clients ADD COLUMN token_endpoint_auth_method TEXT NOT NULL DEFAULT 'none'; +ALTER TABLE oidc_clients ADD COLUMN require_pkce INTEGER NOT NULL DEFAULT 1; +ALTER TABLE oidc_clients ADD COLUMN post_logout_redirect_uris TEXT NOT NULL DEFAULT '[]'; + +CREATE TABLE signing_keys ( + id TEXT PRIMARY KEY, + alg TEXT NOT NULL, + private_jwk TEXT NOT NULL, + public_jwk TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'retired')), + created_at INTEGER NOT NULL, + retired_at INTEGER +); + +CREATE INDEX signing_keys_status ON signing_keys(status); + +CREATE TABLE auth_requests ( + id TEXT PRIMARY KEY, + client_id TEXT NOT NULL, + redirect_uri TEXT NOT NULL, + scope TEXT NOT NULL, + state TEXT, + nonce TEXT, + code_challenge TEXT, + code_challenge_method TEXT, + session_id TEXT, + user_id TEXT, + auth_time INTEGER, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + completed_at INTEGER +); + +CREATE INDEX auth_requests_expires ON auth_requests(expires_at); + +CREATE TABLE authorization_codes ( + id TEXT PRIMARY KEY, + auth_request_id TEXT NOT NULL UNIQUE, + client_id TEXT NOT NULL, + user_id TEXT NOT NULL, + redirect_uri TEXT NOT NULL, + scope TEXT NOT NULL, + nonce TEXT, + code_challenge TEXT, + code_challenge_method TEXT, + session_id TEXT, + auth_time INTEGER NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + consumed_at INTEGER +); + +CREATE INDEX authorization_codes_expires ON authorization_codes(expires_at); diff --git a/server/migrations/sqlite/system/002_client_hosts.sql b/server/migrations/sqlite/system/002_client_hosts.sql @@ -0,0 +1,8 @@ +CREATE TABLE oidc_client_hosts ( + host TEXT PRIMARY KEY, + realm_id TEXT NOT NULL REFERENCES realms(id) ON DELETE CASCADE, + client_id TEXT NOT NULL, + created_at INTEGER NOT NULL +); + +CREATE INDEX oidc_client_hosts_realm ON oidc_client_hosts(realm_id); diff --git a/server/migrations/sqlite/system/003_system_admin.sql b/server/migrations/sqlite/system/003_system_admin.sql @@ -0,0 +1 @@ +ALTER TABLE users ADD COLUMN is_system_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_system_admin IN (0, 1)); diff --git a/server/package-lock.json b/server/package-lock.json @@ -9,6 +9,7 @@ "body-parser": "^2.3.0", "cookie": "^2.0.1", "cors": "^2.8.6", + "jose": "^6.2.13", "mithril": "^2.3.8", "morgan": "^1.12.1", "router": "^2.2.0", @@ -1131,6 +1132,15 @@ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "license": "MIT" }, + "node_modules/jose": { + "version": "6.2.13", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz", + "integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/junk": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/junk/-/junk-4.0.1.tgz", diff --git a/server/package.json b/server/package.json @@ -13,6 +13,7 @@ "body-parser": "^2.3.0", "cookie": "^2.0.1", "cors": "^2.8.6", + "jose": "^6.2.13", "mithril": "^2.3.8", "morgan": "^1.12.1", "router": "^2.2.0", diff --git a/server/scripts/seed-demo.js b/server/scripts/seed-demo.js @@ -1,7 +1,9 @@ import crypto from 'node:crypto'; import { loadConfig } from '../src/lib/config.js'; import { hashPassword } from '../src/lib/password.js'; +import { hashClientSecret } from '../src/lib/oidc/clients.js'; import { + addOidcClientHost, addRealmEmailDomain, closeRealms, createRealm, @@ -19,6 +21,7 @@ import { findUserByEmail, findUserByUsername, setPasswordCredential, + setSystemAdmin, } from '../src/lib/users.js'; const DEMO_PASSWORD = 'demo'; @@ -57,16 +60,23 @@ async function ensureRealmUser(realmSlug, userId, roles = []) { } } -async function ensureUser({ username, email, displayName, password = DEMO_PASSWORD }) { +async function ensureUser({ + username, + email, + displayName, + password = DEMO_PASSWORD, + isSystemAdmin = false, +}) { const systemDb = getSystemDatabase(); const existing = (await findUserByEmail(systemDb, email)) || (await findUserByUsername(systemDb, username)); if (existing) { await setPasswordCredential(systemDb, existing.id, await hashPassword(password)); + if (isSystemAdmin) await setSystemAdmin(systemDb, existing.id, true); return existing.id; } - const id = await createUser(systemDb, { username, displayName }); + const id = await createUser(systemDb, { username, displayName, isSystemAdmin }); await addUserEmail(systemDb, id, email, { verified: true, primary: true }); await assignHomeRealmForEmail(systemDb, id, email); await setPasswordCredential(systemDb, id, await hashPassword(password)); @@ -108,21 +118,45 @@ async function ensureProviderDomain(db, domain, providerId) { ); } -async function ensureClient(db, { clientId, name, accessMode, roles = [] }) { +async function ensureClient( + db, + { + clientId, + name, + accessMode, + roles = [], + redirectUris = [], + postLogoutRedirectUris = [], + tokenEndpointAuthMethod = 'none', + clientSecret = null, + branding = {}, + requirePkce = true, + } +) { let client = await db.get('SELECT id FROM oidc_clients WHERE client_id = {clientId}', { clientId }); if (!client) { const now = Date.now(); client = { id: crypto.randomUUID() }; await db.run( `INSERT INTO oidc_clients - (id, client_id, name, redirect_uris, scopes, access_mode, enabled, created_at, updated_at) + (id, client_id, name, redirect_uris, scopes, access_mode, enabled, branding, + client_secret_hash, token_endpoint_auth_method, require_pkce, + post_logout_redirect_uris, created_at, updated_at) VALUES - ({id}, {clientId}, {name}, '[]', 'openid profile email', {accessMode}, 1, {createdAt}, {updatedAt})`, + ({id}, {clientId}, {name}, {redirectUris}, 'openid profile email', {accessMode}, 1, {branding}, + {clientSecretHash}, {tokenEndpointAuthMethod}, {requirePkce}, + {postLogoutRedirectUris}, {createdAt}, {updatedAt})`, { id: client.id, clientId, name, + redirectUris: JSON.stringify(redirectUris), accessMode, + branding: JSON.stringify(branding), + clientSecretHash: clientSecret ? hashClientSecret(clientSecret) : null, + tokenEndpointAuthMethod, + requirePkce: requirePkce ? 1 : 0, + postLogoutRedirectUris: JSON.stringify(postLogoutRedirectUris), createdAt: now, updatedAt: now, } @@ -145,6 +179,10 @@ async function ensureClient(db, { clientId, name, accessMode, roles = [] }) { } const cfg = loadConfig(); +const publicUrl = new URL(cfg.server.public_url); +const portSuffix = publicUrl.port ? `:${publicUrl.port}` : ''; +const clientOrigin = (host) => `${publicUrl.protocol}//${host}${portSuffix}`; + await initRealms(cfg); const acme = await ensureRealm({ @@ -159,12 +197,10 @@ const globex = await ensureRealm({ hosts: ['globex.localhost'], branding: { primary_color: '#25A' }, }); -const system = await findRealmBySlug('system'); await ensureRealmDomain(acme.id, 'acme.test'); await ensureRealmDomain(acme.id, 'sso.acme.test'); await ensureRealmDomain(globex.id, 'globex.test'); -await ensureRealmDomain(system.id, 'system.test'); const alice = await ensureUser({ username: 'alice', @@ -190,6 +226,7 @@ const systemAdmin = await ensureUser({ username: 'admin', email: 'admin@system.test', displayName: 'System Admin', + isSystemAdmin: true, }); await ensureRealmUser('acme', alice); @@ -197,7 +234,6 @@ await ensureRealmUser('globex', alice); await ensureRealmUser('acme', acmeAdmin, ['realm-admin']); await ensureRealmUser('acme', guest); await ensureRealmUser('globex', contractor, ['realm-admin']); -await ensureRealmUser('system', systemAdmin, ['system-admin']); const acmeDb = await openRealmDatabase(acme); const providerId = await ensureProvider(acmeDb, { @@ -209,15 +245,57 @@ const providerId = await ensureProvider(acmeDb, { }); await ensureProviderDomain(acmeDb, 'sso.acme.test', providerId); -await ensureClient(acmeDb, { clientId: 'internal-app', name: 'Internal App', accessMode: 'internal' }); -await ensureClient(acmeDb, { clientId: 'members-app', name: 'Members App', accessMode: 'members' }); -await ensureClient(acmeDb, { clientId: 'public-app', name: 'Public App', accessMode: 'public' }); +await ensureClient(acmeDb, { + clientId: 'internal-app', + name: 'Internal App', + accessMode: 'internal', + redirectUris: [`${clientOrigin('app.acme.localhost')}/callback`], + postLogoutRedirectUris: [`${clientOrigin('app.acme.localhost')}/`], +}); +await ensureClient(acmeDb, { + clientId: 'members-app', + name: 'Members App', + accessMode: 'members', + redirectUris: [`${clientOrigin('members.localhost')}/callback`], +}); +await ensureClient(acmeDb, { + clientId: 'public-app', + name: 'Public App', + accessMode: 'public', + redirectUris: [`${clientOrigin('public.localhost')}/callback`], +}); +await ensureClient(acmeDb, { + clientId: 'confidential-app', + name: 'Confidential App', + accessMode: 'members', + redirectUris: [`${clientOrigin('confidential.localhost')}/callback`], + tokenEndpointAuthMethod: 'client_secret_basic', + clientSecret: 'demo-secret', +}); + +const globexDb = await openRealmDatabase(globex); +await ensureClient(globexDb, { + clientId: 'members-app', + name: 'Members App', + accessMode: 'members', + redirectUris: [`${clientOrigin('members.localhost')}/callback`], +}); +await ensureClient(globexDb, { + clientId: 'public-app', + name: 'Public App', + accessMode: 'public', + redirectUris: [`${clientOrigin('public.localhost')}/callback`], +}); + +await addOidcClientHost(acme.id, 'internal-app', 'app.acme.localhost'); -console.log('seeded realms acme, globex and system'); +console.log('seeded realms acme and globex'); console.log('password for all demo users: demo'); -console.log('home users: alice@acme.test, it@acme.test, admin@system.test'); +console.log('home users: alice@acme.test, it@acme.test, admin@system.test (system admin)'); console.log('guest users: guest@personal.test (acme), contractor@personal.test (globex realm-admin)'); console.log('upstream mapping: sso.acme.test -> Example SSO'); -console.log('clients: admin-ui, internal-app, members-app, public-app'); +console.log('clients: internal-app, members-app, public-app, confidential-app'); +console.log('client host: app.acme.localhost -> acme/internal-app'); +console.log('virtual clients: admin, account'); await closeRealms(); diff --git a/server/src/controller/login/password.js b/server/src/controller/login/password.js @@ -1,7 +1,10 @@ import { app } from '../../app.js'; import { HttpError } from '../../lib/http/http-error.js'; import { findManagedProviderForUser, resolveLogin } from '../../lib/login.js'; +import { getClient } from '../../lib/oidc/clients.js'; +import { getAuthRequest, readAuthRequestId } from '../../lib/oidc/requests.js'; import { verifyDummyPassword, verifyPassword } from '../../lib/password.js'; +import { canUseClient } from '../../lib/policy.js'; import { getSystemDatabase, openRealmDatabase, realmMetadata, resolveRealm } from '../../lib/realm.js'; import { LONG_SESSION_TTL, @@ -15,6 +18,7 @@ import { findUserByIdentifier, getMembership, getPasswordCredential, + getUserRoles, updateLastLogin, } from '../../lib/users.js'; @@ -33,6 +37,9 @@ export default { if (body.password.length > 1024) { throw new HttpError(400, 'invalid_request', 'password is too long'); } + if (typeof body.client_id !== 'string') { + throw new HttpError(400, 'invalid_request', 'client_id is required'); + } if (body.realm != null && typeof body.realm !== 'string') { throw new HttpError(400, 'invalid_request', 'realm must be a string'); } @@ -47,6 +54,10 @@ export default { const metadata = await realmMetadata(realm); const realmDb = await openRealmDatabase(realm); const systemDb = getSystemDatabase(); + const client = await getClient(realmDb, body.client_id); + if (!client || !client.enabled) { + throw new HttpError(404, 'unknown_client', 'Unknown client'); + } if (body.identifier.includes('@')) { const resolution = await resolveLogin({ identifier: body.identifier }); @@ -58,15 +69,12 @@ export default { const user = await findUserByIdentifier(systemDb, body.identifier); const credential = user ? await getPasswordCredential(systemDb, user.id) : null; const membership = user ? await getMembership(realmDb, user.id) : null; + const roles = user ? await getUserRoles(realmDb, user.id) : []; + const pendingId = readAuthRequestId(req, realm); + const pending = pendingId ? await getAuthRequest(realmDb, pendingId) : null; + const pendingClient = pending && !pending.completed_at && pending.client_id === client.client_id; - const canCheckPassword = - user && - user.status === 'active' && - credential && - membership && - membership.status === 'active'; - - if (!canCheckPassword) { + if (!credential) { await verifyDummyPassword(body.password); throw new HttpError(401, 'invalid_credentials', 'Invalid credentials'); } @@ -76,6 +84,27 @@ export default { throw new HttpError(401, 'invalid_credentials', 'Invalid credentials'); } + if (!user || user.status !== 'active') { + throw new HttpError(401, 'invalid_credentials', 'Invalid credentials'); + } + + const allowedByPolicy = canUseClient({ + user, + membership, + roles, + client, + realm, + }); + const member = membership && membership.status === 'active'; + const publicNonMember = client.access_mode === 'public' && !client.virtual && pendingClient; + const allowed = + allowedByPolicy && + (member || client.virtual || publicNonMember || user.is_system_admin); + + if (!allowed) { + throw new HttpError(401, 'invalid_credentials', 'Invalid credentials'); + } + if (!body.identifier.includes('@')) { const provider = await findManagedProviderForUser(systemDb, user); if (provider && !provider.enabled) { @@ -107,6 +136,7 @@ export default { display_name: user.display_name, }, expires_at: session.expires_at, + pending_auth_request: Boolean(pendingClient), }); }, }; diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js @@ -0,0 +1,514 @@ +import crypto from 'node:crypto'; +import { app } from '../app.js'; +import { HttpError } from '../lib/http/http-error.js'; +import { + authenticateClient, + getClient, + postLogoutRedirectAllowed, + redirectUriAllowed, +} from '../lib/oidc/clients.js'; +import { + canonicalIssuer, + endpointBase, + endpointUrls, + resolveOidcContext, +} from '../lib/oidc/context.js'; +import { getJwks, signToken, verifyToken } from '../lib/oidc/keys.js'; +import { + clearAuthRequestCookie, + completeAuthRequest, + createAuthRequest, + createAuthorizationCode, + deleteAuthRequest, + getAuthRequest, + purgeExpired, + readAuthRequestId, + setAuthRequestCookie, +} from '../lib/oidc/requests.js'; +import { canUseClient } from '../lib/policy.js'; +import { + getSystemDatabase, + openRealmDatabase, + realmMetadata, +} from '../lib/realm.js'; +import { + authenticateRequest, + clearSessionCookie, + destroySession, + requestToken, +} from '../lib/session.js'; +import { + findUserById, + getMembership, + getPrimaryEmail, + getUserRoles, +} from '../lib/users.js'; + +function oidcError(status, error, description, headers = {}) { + return new app.HttpResponse( + status, + { error, error_description: description }, + { 'cache-control': 'no-store', ...headers } + ); +} + +function redirect(res, location) { + return new app.HttpResponse(302, undefined, { location }); +} + +function withQuery(url, params) { + const target = new URL(url); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined && value !== null && value !== '') { + target.searchParams.set(key, String(value)); + } + } + return target.toString(); +} + +function bearerToken(req) { + const header = String(req.headers.authorization || ''); + return header.startsWith('Bearer ') ? header.slice(7) : null; +} + +function accessDenied(res, redirectUri, state) { + return redirect( + res, + withQuery(redirectUri, { + error: 'access_denied', + error_description: 'The user is not allowed to use this client', + state, + }) + ); +} + +async function discovery(context, client) { + const realm = await realmMetadata(context.realm); + const publicUrl = app.config.server.public_url; + const urls = endpointUrls(context); + const branding = Object.keys(client.branding || {}).length > 0 ? client.branding : realm.branding; + const scopes = String(client.scopes || 'openid profile email') + .split(/\s+/) + .filter(Boolean); + + return new app.HttpOk( + { + issuer: canonicalIssuer(publicUrl, context.realm.slug), + client_id: client.client_id, + client_name: client.name, + realm: context.realm.slug, + display_name: client.name, + branding, + access_mode: client.access_mode, + virtual: Boolean(client.virtual), + allow_session_duration_choice: realm.allow_session_duration_choice, + authorization_endpoint: urls.authorize, + token_endpoint: urls.token, + userinfo_endpoint: urls.userinfo, + jwks_uri: urls.jwks, + end_session_endpoint: urls.logout, + response_types_supported: ['code'], + grant_types_supported: ['authorization_code'], + subject_types_supported: ['public'], + id_token_signing_alg_values_supported: ['ES256'], + scopes_supported: scopes, + token_endpoint_auth_methods_supported: [client.token_endpoint_auth_method || 'none'], + code_challenge_methods_supported: ['S256'], + claims_supported: [ + 'iss', + 'sub', + 'aud', + 'exp', + 'iat', + 'auth_time', + 'nonce', + 'name', + 'preferred_username', + 'email', + 'email_verified', + 'roles', + ], + require_pkce: Boolean(client.require_pkce), + }, + { 'cache-control': 'no-cache' } + ); +} + +async function authorize(context, client, req, res) { + const url = new URL(req.url, context.origin); + const params = url.searchParams; + const redirectUri = params.get('redirect_uri'); + const state = params.get('state'); + const scope = params.get('scope') || 'openid'; + const clientId = params.get('client_id') || context.clientId; + const virtualCallbacks = [ + `${endpointBase(context)}/callback`, + `${context.origin}/app/${client.client_id}/callback`, + ]; + + if (!redirectUri) { + return oidcError(400, 'invalid_request', 'redirect_uri is required'); + } + if (!redirectUriAllowed(client, redirectUri, virtualCallbacks)) { + return oidcError(400, 'invalid_request', 'redirect_uri is not registered'); + } + + const fail = (error, description) => + redirect(res, withQuery(redirectUri, { error, error_description: description, state })); + + if (params.get('response_type') !== 'code') { + return fail('unsupported_response_type', 'Only response_type=code is supported'); + } + if (clientId !== client.client_id) { + return fail('invalid_request', 'client_id does not match the requested client'); + } + if (!scope.split(/\s+/).includes('openid')) { + return fail('invalid_scope', 'The openid scope is required'); + } + + const codeChallenge = params.get('code_challenge'); + const codeChallengeMethod = params.get('code_challenge_method'); + if (client.require_pkce && (!codeChallenge || codeChallengeMethod !== 'S256')) { + return fail('invalid_request', 'PKCE with S256 is required'); + } + + const db = await openRealmDatabase(context.realm); + const systemDb = getSystemDatabase(); + await purgeExpired(db); + + const pendingId = readAuthRequestId(req, context.realm); + let pending = await getAuthRequest(db, pendingId); + if ( + pending && + (pending.client_id !== client.client_id || + pending.redirect_uri !== redirectUri || + pending.completed_at) + ) { + await deleteAuthRequest(db, pending.id); + pending = null; + } + + const auth = await authenticateRequest({ + systemDb, + realmDb: db, + req, + res, + realm: context.realm, + }); + + const allowed = auth + ? canUseClient({ + user: auth.user, + membership: auth.membership, + roles: auth.roles, + client, + realm: context.realm, + }) + : false; + + if (auth && !allowed) { + if (pending) { + await deleteAuthRequest(db, pending.id); + clearAuthRequestCookie(res, req, context.realm); + } + return accessDenied(res, redirectUri, state); + } + + if (!pending) { + pending = { + id: await createAuthRequest(db, { + clientId: client.client_id, + redirectUri, + scope, + state, + nonce: params.get('nonce'), + codeChallenge, + codeChallengeMethod, + }), + }; + + if (!auth) { + setAuthRequestCookie(res, req, context.realm, pending.id); + return redirect(res, endpointUrls(context).login); + } + } + + if (!auth) { + setAuthRequestCookie(res, req, context.realm, pending.id); + return redirect(res, endpointUrls(context).login); + } + + const authTime = Math.floor(auth.session.created_at / 1000); + await completeAuthRequest(db, pending.id, { + userId: auth.user.id, + sessionId: auth.session.id, + authTime, + }); + + const request = await getAuthRequest(db, pending.id); + const code = await createAuthorizationCode(db, request); + await deleteAuthRequest(db, pending.id); + clearAuthRequestCookie(res, req, context.realm); + + return redirect(res, withQuery(redirectUri, { code, state })); +} + +function verifyPkce(codeVerifier, challenge) { + if (!codeVerifier || !challenge) return false; + const computed = crypto.createHash('sha256').update(codeVerifier).digest('base64url'); + const left = Buffer.from(computed); + const right = Buffer.from(challenge); + return left.length === right.length && crypto.timingSafeEqual(left, right); +} + +async function token(context, client, req) { + if (req.method !== 'POST') { + return oidcError(405, 'invalid_request', 'POST is required'); + } + + const body = req.body || {}; + if (!authenticateClient(req, client, body)) { + return oidcError(401, 'invalid_client', 'Client authentication failed', { + 'www-authenticate': 'Basic realm="oidc"', + }); + } + if (body.grant_type !== 'authorization_code') { + return oidcError(400, 'unsupported_grant_type', 'Only authorization_code is supported'); + } + + const db = await openRealmDatabase(context.realm); + const systemDb = getSystemDatabase(); + const code = await db.get( + `SELECT id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce, + code_challenge, code_challenge_method, session_id, auth_time, + expires_at, consumed_at + FROM authorization_codes + WHERE id = {id}`, + { id: crypto.createHash('sha256').update(String(body.code || '')).digest('hex') } + ); + + if ( + !code || + code.consumed_at || + code.expires_at <= Date.now() || + code.client_id !== client.client_id + ) { + return oidcError(400, 'invalid_grant', 'The authorization code is invalid'); + } + if (body.redirect_uri !== code.redirect_uri) { + return oidcError(400, 'invalid_grant', 'redirect_uri does not match'); + } + if (code.code_challenge) { + if ( + code.code_challenge_method !== 'S256' || + !verifyPkce(body.code_verifier, code.code_challenge) + ) { + return oidcError(400, 'invalid_grant', 'PKCE verification failed'); + } + } else if (client.require_pkce) { + return oidcError(400, 'invalid_grant', 'PKCE is required'); + } + + await db.run('UPDATE authorization_codes SET consumed_at = {now} WHERE id = {id}', { + now: Date.now(), + id: code.id, + }); + + const user = await findUserById(systemDb, code.user_id); + if (!user || user.status !== 'active') { + return oidcError(400, 'invalid_grant', 'The user is not available'); + } + + const membership = await getMembership(db, user.id); + const roles = await getUserRoles(db, user.id); + if ( + !canUseClient({ + user, + membership, + roles, + client, + realm: context.realm, + }) + ) { + return oidcError(400, 'invalid_grant', 'The user no longer has access to this client'); + } + + const email = await getPrimaryEmail(systemDb, user.id); + const issuer = canonicalIssuer(app.config.server.public_url, context.realm.slug); + const audience = client.client_id; + const expiresIn = 300; + + const idClaims = { + sub: user.id, + email: email?.email, + email_verified: Boolean(email?.verified), + name: user.display_name || user.username, + preferred_username: user.username, + roles, + auth_time: code.auth_time, + sid: code.session_id || undefined, + nonce: code.nonce || undefined, + }; + + const accessClaims = { + sub: user.id, + client_id: client.client_id, + scope: code.scope, + roles, + sid: code.session_id || undefined, + }; + + const idToken = await signToken(db, idClaims, { issuer, audience, expiresIn }); + const accessToken = await signToken(db, accessClaims, { issuer, audience, expiresIn }); + + return new app.HttpOk( + { + access_token: accessToken, + token_type: 'Bearer', + expires_in: expiresIn, + id_token: idToken, + scope: code.scope, + }, + { 'cache-control': 'no-store' } + ); +} + +async function userinfo(context, client, req) { + const tokenValue = bearerToken(req); + if (!tokenValue) { + return oidcError(401, 'invalid_token', 'A bearer token is required', { + 'www-authenticate': 'Bearer', + }); + } + + const db = await openRealmDatabase(context.realm); + const issuer = canonicalIssuer(app.config.server.public_url, context.realm.slug); + let payload; + try { + payload = await verifyToken(db, tokenValue, { + issuer, + audience: client.client_id, + }); + } catch { + return oidcError(401, 'invalid_token', 'The access token is invalid', { + 'www-authenticate': 'Bearer error="invalid_token"', + }); + } + + if (payload.client_id !== client.client_id || !payload.sub) { + return oidcError(401, 'invalid_token', 'The access token does not belong to this client', { + 'www-authenticate': 'Bearer error="invalid_token"', + }); + } + + const systemDb = getSystemDatabase(); + const user = await findUserById(systemDb, payload.sub); + if (!user || user.status !== 'active') { + return oidcError(401, 'invalid_token', 'The user is not available'); + } + + const email = await getPrimaryEmail(systemDb, user.id); + const roles = await getUserRoles(db, user.id); + + return new app.HttpOk({ + sub: user.id, + name: user.display_name || user.username, + preferred_username: user.username, + email: email?.email, + email_verified: Boolean(email?.verified), + roles, + }); +} + +async function logout(context, client, req, res) { + const url = new URL(req.url, context.origin); + const postLogoutUri = url.searchParams.get('post_logout_redirect_uri'); + const state = url.searchParams.get('state'); + const virtualCallbacks = [ + `${endpointBase(context)}/callback`, + `${context.origin}/app/${client.client_id}/callback`, + ]; + + if (!postLogoutRedirectAllowed(client, postLogoutUri, virtualCallbacks)) { + return oidcError(400, 'invalid_request', 'post_logout_redirect_uri is not registered'); + } + + const db = await openRealmDatabase(context.realm); + const idTokenHint = url.searchParams.get('id_token_hint'); + if (idTokenHint) { + try { + await verifyToken(db, idTokenHint, { + issuer: canonicalIssuer(app.config.server.public_url, context.realm.slug), + audience: client.client_id, + }); + } catch { + return oidcError(400, 'invalid_request', 'id_token_hint is invalid'); + } + } + + await destroySession(db, requestToken(req, context.realm)); + clearSessionCookie(res, req, context.realm); + clearAuthRequestCookie(res, req, context.realm); + + if (postLogoutUri) { + return redirect(res, withQuery(postLogoutUri, { state })); + } + return new app.HttpOk({ ok: true }); +} + +export default { + mount: '/oidc', + name: 'oidc', + async handler(req, res, next) { + try { + const context = await resolveOidcContext(req); + if (context.action === 'login' || context.action === 'callback') { + next(); + return; + } + + const db = await openRealmDatabase(context.realm); + const client = await getClient(db, context.clientId); + if (!client || !client.enabled) { + throw new HttpError(404, 'unknown_client', 'Unknown client'); + } + + let result; + switch (context.action) { + case 'openid-configuration': + result = await discovery(context, client); + break; + case 'jwks': + result = new app.HttpOk(await getJwks(db)); + break; + case 'authorize': + result = await authorize(context, client, req, res); + break; + case 'token': + result = await token(context, client, req); + break; + case 'userinfo': + result = await userinfo(context, client, req); + break; + case 'logout': + result = await logout(context, client, req, res); + break; + default: + throw new HttpError(404, 'not_found', 'Not found'); + } + + if (result) result.send(res); + } catch (e) { + if (res.headersSent) { + res.end(); + return; + } + if (e instanceof app.HttpError) { + e.toResponse().send(res); + return; + } + console.error(e); + new app.HttpError(500, 'internal_error', 'Internal server error').toResponse().send(res); + } + }, +}; diff --git a/server/src/controller/session/show.js b/server/src/controller/session/show.js @@ -1,6 +1,7 @@ import { app } from '../../app.js'; import { HttpError } from '../../lib/http/http-error.js'; import { getSystemDatabase, openRealmDatabase, realmMetadata, resolveRealm } from '../../lib/realm.js'; +import { isSystemAdmin } from '../../lib/policy.js'; import { authenticateRequest } from '../../lib/session.js'; export default { @@ -23,7 +24,7 @@ export default { realm, }); - if (!auth) { + if (!auth || (!isSystemAdmin(auth.user) && (!auth.membership || auth.membership.status !== 'active'))) { throw new HttpError(401, 'not_authenticated', 'Not signed in'); } diff --git a/server/src/index.js b/server/src/index.js @@ -36,12 +36,18 @@ for (const mod of await loadModules(path.join(here, 'lib', 'http'))) { app.use(morgan('tiny')); app.use(cors()); app.use(bodyParser.json({ limit: '16kb' })); +app.use(bodyParser.urlencoded({ extended: false, limit: '16kb' })); const routes = []; for (const mod of await loadModules(path.join(here, 'controller'))) { const exported = mod.default ?? mod.route ?? mod; for (const route of Array.isArray(exported) ? exported : [exported]) { - if (!route || !route.method || !route.path) continue; + if (!route) continue; + if (route.mount) { + app.use(route.mount, route.handler); + continue; + } + if (!route.method || !route.path) continue; if (route.name) { app.manifest.push({ method: route.method, diff --git a/server/src/lib/config.js b/server/src/lib/config.js @@ -14,6 +14,7 @@ const DEFAULTS = { server: { host: '0.0.0.0', port: 3000, + public_url: 'http://localhost:3000', }, database: { dialect: 'sqlite', @@ -26,6 +27,7 @@ const DEFAULTS = { const ENV_MAP = [ ['AUTH_HOST', 'server.host', String], ['AUTH_PORT', 'server.port', toInt], + ['AUTH_PUBLIC_URL', 'server.public_url', String], ['AUTH_DATABASE_DIALECT', 'database.dialect', lower], ['AUTH_DATABASE_PATH', 'database.path', String], ['AUTH_REALMS_PATH', 'database.realms', String], @@ -80,6 +82,15 @@ function validate(cfg) { errors.push(`server.port must be between 0 and 65535, got ${port}`); } + try { + const publicUrl = new URL(cfg.server.public_url); + if (publicUrl.protocol !== 'http:' && publicUrl.protocol !== 'https:') { + errors.push('server.public_url must use http or https'); + } + } catch { + errors.push('server.public_url must be an absolute URL'); + } + if (!SUPPORTED_DIALECTS.includes(cfg.database.dialect)) { errors.push( `database.dialect must be one of ${SUPPORTED_DIALECTS.join(', ')}, got ${JSON.stringify(cfg.database.dialect)}` diff --git a/server/src/lib/oidc/clients.js b/server/src/lib/oidc/clients.js @@ -0,0 +1,125 @@ +import crypto from 'node:crypto'; + +const VIRTUAL_CLIENTS = { + admin: { + id: 'virtual:admin', + client_id: 'admin', + name: 'Admin', + access_mode: 'admin', + enabled: 1, + require_pkce: 1, + token_endpoint_auth_method: 'none', + redirect_uris: [], + post_logout_redirect_uris: [], + branding: {}, + required_roles: [], + virtual: true, + }, + account: { + id: 'virtual:account', + client_id: 'account', + name: 'Account', + access_mode: 'public', + enabled: 1, + require_pkce: 1, + token_endpoint_auth_method: 'none', + redirect_uris: [], + post_logout_redirect_uris: [], + branding: {}, + required_roles: [], + virtual: true, + }, +}; + +function parseJson(raw, fallback) { + try { + return JSON.parse(raw || 'null') ?? fallback; + } catch { + return fallback; + } +} + +export function hashClientSecret(secret) { + return crypto.createHash('sha256').update(secret).digest('hex'); +} + +export function isVirtualClient(clientId) { + return Object.hasOwn(VIRTUAL_CLIENTS, clientId); +} + +export async function getClient(db, clientId) { + const virtual = VIRTUAL_CLIENTS[clientId]; + if (virtual) return { ...virtual }; + + const row = await db.get( + `SELECT id, client_id, name, redirect_uris, scopes, access_mode, enabled, + client_secret_hash, token_endpoint_auth_method, require_pkce, + post_logout_redirect_uris, branding + FROM oidc_clients + WHERE client_id = {clientId}`, + { clientId } + ); + if (!row) return null; + + const roles = await db.all( + `SELECT r.slug + FROM oidc_client_roles cr + JOIN roles r ON r.id = cr.role_id + WHERE cr.client_id = {id}`, + { id: row.id } + ); + + return { + ...row, + enabled: Boolean(row.enabled), + require_pkce: Boolean(row.require_pkce), + redirect_uris: parseJson(row.redirect_uris, []), + post_logout_redirect_uris: parseJson(row.post_logout_redirect_uris, []), + branding: parseJson(row.branding, {}), + required_roles: roles.map((role) => role.slug), + virtual: false, + }; +} + +export function redirectUriAllowed(client, redirectUri, virtualCallbacks = []) { + if (client.virtual) return virtualCallbacks.includes(redirectUri); + return client.redirect_uris.includes(redirectUri); +} + +export function postLogoutRedirectAllowed(client, redirectUri, virtualCallbacks = []) { + if (!redirectUri) return true; + if (client.virtual) return virtualCallbacks.includes(redirectUri); + return client.post_logout_redirect_uris.includes(redirectUri); +} + +export function authenticateClient(req, client, body = {}) { + const method = client.token_endpoint_auth_method || 'none'; + + if (method === 'none') { + return !body.client_id || body.client_id === client.client_id; + } + + if (method !== 'client_secret_basic' || !client.client_secret_hash) { + return false; + } + + const header = String(req.headers.authorization || ''); + if (!header.startsWith('Basic ')) return false; + + let decoded; + try { + decoded = Buffer.from(header.slice(6), 'base64').toString('utf8'); + } catch { + return false; + } + + const colon = decoded.indexOf(':'); + if (colon === -1) return false; + const clientId = decoded.slice(0, colon); + const secret = decoded.slice(colon + 1); + if (clientId !== client.client_id) return false; + + const expected = Buffer.from(client.client_secret_hash, 'hex'); + const actual = Buffer.from(hashClientSecret(secret), 'hex'); + return expected.length === actual.length && crypto.timingSafeEqual(expected, actual); +} diff --git a/server/src/lib/oidc/context.js b/server/src/lib/oidc/context.js @@ -0,0 +1,94 @@ +import { HttpError } from '../http/http-error.js'; +import { + findOidcClientHost, + findRealmBySlug, + findRealmHost, +} from '../realm.js'; + +export function requestOrigin(req) { + const proto = String(req.headers['x-forwarded-proto'] || '') + .split(',')[0] + .trim() + .toLowerCase() || (req.socket?.encrypted ? 'https' : 'http'); + return `${proto}://${req.headers.host}`; +} + +export function canonicalIssuer(publicUrl, realmSlug) { + const base = String(publicUrl || '').replace(/\/+$/, ''); + return `${base}/oidc/${encodeURIComponent(realmSlug)}`; +} + +function pathSegments(req) { + const pathname = String(req.url || '/').split('?')[0]; + return pathname + .split('/') + .filter(Boolean) + .map((segment) => decodeURIComponent(segment)); +} + +export async function resolveOidcContext(req) { + const segments = pathSegments(req); + const origin = requestOrigin(req); + + const clientHost = await findOidcClientHost(req.headers.host); + if (clientHost) { + if (segments.length !== 1) throw new HttpError(404, 'not_found', 'Not found'); + return { + mode: 'client', + origin, + realm: { + id: clientHost.realm_id, + slug: clientHost.slug, + db_file: clientHost.db_file, + owner_user_id: clientHost.owner_user_id, + }, + clientId: clientHost.client_id, + action: segments[0], + }; + } + + const realmHost = await findRealmHost(req.headers.host); + if (realmHost) { + if (segments.length !== 2) throw new HttpError(404, 'not_found', 'Not found'); + return { + mode: 'realm', + origin, + realm: realmHost, + clientId: segments[0], + action: segments[1], + }; + } + + if (segments.length !== 3) throw new HttpError(404, 'not_found', 'Not found'); + const realm = await findRealmBySlug(segments[0]); + if (!realm) throw new HttpError(404, 'unknown_realm', 'Unknown realm'); + + return { + mode: 'canonical', + origin, + realm, + clientId: segments[1], + action: segments[2], + }; +} + +export function endpointBase(context) { + if (context.mode === 'client') return `${context.origin}/oidc`; + if (context.mode === 'realm') return `${context.origin}/oidc/${encodeURIComponent(context.clientId)}`; + return `${context.origin}/oidc/${encodeURIComponent(context.realm.slug)}/${encodeURIComponent( + context.clientId + )}`; +} + +export function endpointUrls(context) { + const base = endpointBase(context); + return { + openid_configuration: `${base}/openid-configuration`, + login: `${base}/login`, + authorize: `${base}/authorize`, + token: `${base}/token`, + userinfo: `${base}/userinfo`, + jwks: `${base}/jwks`, + logout: `${base}/logout`, + }; +} diff --git a/server/src/lib/oidc/keys.js b/server/src/lib/oidc/keys.js @@ -0,0 +1,88 @@ +import crypto from 'node:crypto'; +import { + SignJWT, + exportJWK, + generateKeyPair, + importJWK, + jwtVerify, +} from 'jose'; + +const pending = new WeakMap(); + +async function loadSigningKey(db) { + const row = await db.get( + `SELECT id, alg, private_jwk, public_jwk + FROM signing_keys + WHERE status = 'active' + ORDER BY created_at DESC + LIMIT 1` + ); + if (row) { + return { + id: row.id, + alg: row.alg, + privateJwk: JSON.parse(row.private_jwk), + publicJwk: JSON.parse(row.public_jwk), + }; + } + + const { privateKey, publicKey } = await generateKeyPair('ES256', { extractable: true }); + const id = crypto.randomUUID(); + const privateJwk = await exportJWK(privateKey); + const publicJwk = await exportJWK(publicKey); + + privateJwk.kid = id; + privateJwk.alg = 'ES256'; + privateJwk.use = 'sig'; + publicJwk.kid = id; + publicJwk.alg = 'ES256'; + publicJwk.use = 'sig'; + + await db.run( + `INSERT INTO signing_keys (id, alg, private_jwk, public_jwk, status, created_at) + VALUES ({id}, 'ES256', {privateJwk}, {publicJwk}, 'active', {createdAt})`, + { + id, + privateJwk: JSON.stringify(privateJwk), + publicJwk: JSON.stringify(publicJwk), + createdAt: Date.now(), + } + ); + + return { id, alg: 'ES256', privateJwk, publicJwk }; +} + +export function ensureSigningKey(db) { + let promise = pending.get(db); + if (!promise) { + promise = loadSigningKey(db); + pending.set(db, promise); + } + return promise; +} + +export async function getJwks(db) { + const key = await ensureSigningKey(db); + return { keys: [key.publicJwk] }; +} + +export async function signToken(db, claims, { issuer, audience, expiresIn }) { + const key = await ensureSigningKey(db); + const privateKey = await importJWK(key.privateJwk, key.alg); + const now = Math.floor(Date.now() / 1000); + + return new SignJWT(claims) + .setProtectedHeader({ alg: key.alg, kid: key.id, typ: 'JWT' }) + .setIssuer(issuer) + .setAudience(audience) + .setIssuedAt(now) + .setExpirationTime(now + expiresIn) + .sign(privateKey); +} + +export async function verifyToken(db, token, { issuer, audience }) { + const key = await ensureSigningKey(db); + const publicKey = await importJWK(key.publicJwk, key.alg); + const { payload } = await jwtVerify(token, publicKey, { issuer, audience }); + return payload; +} diff --git a/server/src/lib/oidc/requests.js b/server/src/lib/oidc/requests.js @@ -0,0 +1,176 @@ +import crypto from 'node:crypto'; +import { parseCookie, stringifySetCookie } from 'cookie'; + +const AUTH_REQUEST_TTL = 10 * 60; +const CODE_TTL = 60; + +export function authRequestCookieName(realm) { + return `auth_request_${realm.slug}`; +} + +function secureRequest(req) { + if (req.socket?.encrypted) return true; + const proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim().toLowerCase(); + return proto === 'https'; +} + +function appendSetCookie(res, value) { + const existing = res.getHeader('Set-Cookie'); + if (!existing) { + res.setHeader('Set-Cookie', value); + return; + } + const values = Array.isArray(existing) ? existing : [existing]; + res.setHeader('Set-Cookie', [...values, value]); +} + +export function setAuthRequestCookie(res, req, realm, id, ttl = AUTH_REQUEST_TTL) { + appendSetCookie( + res, + stringifySetCookie({ + name: authRequestCookieName(realm), + value: id, + httpOnly: true, + sameSite: 'lax', + path: '/', + maxAge: ttl, + secure: secureRequest(req), + }) + ); +} + +export function clearAuthRequestCookie(res, req, realm) { + appendSetCookie( + res, + stringifySetCookie({ + name: authRequestCookieName(realm), + value: '', + httpOnly: true, + sameSite: 'lax', + path: '/', + maxAge: 0, + secure: secureRequest(req), + }) + ); +} + +export function readAuthRequestId(req, realm) { + const cookies = parseCookie(req.headers.cookie || ''); + return cookies[authRequestCookieName(realm)] || null; +} + +export async function purgeExpired(db, now = Date.now()) { + await db.run('DELETE FROM auth_requests WHERE expires_at <= {now}', { now }); + await db.run('DELETE FROM authorization_codes WHERE expires_at <= {now}', { now }); +} + +export async function createAuthRequest(db, data, now = Date.now()) { + const id = crypto.randomBytes(24).toString('base64url'); + await db.run( + `INSERT INTO auth_requests + (id, client_id, redirect_uri, scope, state, nonce, code_challenge, + code_challenge_method, created_at, expires_at) + VALUES + ({id}, {clientId}, {redirectUri}, {scope}, {state}, {nonce}, {codeChallenge}, + {codeChallengeMethod}, {createdAt}, {expiresAt})`, + { + id, + clientId: data.clientId, + redirectUri: data.redirectUri, + scope: data.scope, + state: data.state || null, + nonce: data.nonce || null, + codeChallenge: data.codeChallenge || null, + codeChallengeMethod: data.codeChallengeMethod || null, + createdAt: now, + expiresAt: now + AUTH_REQUEST_TTL * 1000, + } + ); + return id; +} + +export async function getAuthRequest(db, id, now = Date.now()) { + if (!id) return null; + const request = await db.get( + `SELECT id, client_id, redirect_uri, scope, state, nonce, code_challenge, + code_challenge_method, session_id, user_id, auth_time, + created_at, expires_at, completed_at + FROM auth_requests + WHERE id = {id}`, + { id } + ); + if (!request) return null; + if (request.expires_at <= now) { + await db.run('DELETE FROM auth_requests WHERE id = {id}', { id }); + return null; + } + return request; +} + +export async function completeAuthRequest(db, id, { userId, sessionId, authTime }, now = Date.now()) { + await db.run( + `UPDATE auth_requests + SET user_id = {userId}, session_id = {sessionId}, auth_time = {authTime}, completed_at = {now} + WHERE id = {id}`, + { id, userId, sessionId, authTime, now } + ); +} + +export async function deleteAuthRequest(db, id) { + if (!id) return; + await db.run('DELETE FROM auth_requests WHERE id = {id}', { id }); +} + +export async function createAuthorizationCode(db, request, now = Date.now()) { + const code = crypto.randomBytes(32).toString('base64url'); + const id = crypto.createHash('sha256').update(code).digest('hex'); + + await db.run( + `INSERT INTO authorization_codes + (id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce, + code_challenge, code_challenge_method, session_id, auth_time, + created_at, expires_at) + VALUES + ({id}, {authRequestId}, {clientId}, {userId}, {redirectUri}, {scope}, {nonce}, + {codeChallenge}, {codeChallengeMethod}, {sessionId}, {authTime}, + {createdAt}, {expiresAt})`, + { + id, + authRequestId: request.id, + clientId: request.client_id, + userId: request.user_id, + redirectUri: request.redirect_uri, + scope: request.scope, + nonce: request.nonce, + codeChallenge: request.code_challenge, + codeChallengeMethod: request.code_challenge_method, + sessionId: request.session_id, + authTime: request.auth_time, + createdAt: now, + expiresAt: now + CODE_TTL * 1000, + } + ); + + return code; +} + +export async function consumeAuthorizationCode(db, code, clientId, now = Date.now()) { + if (!code) return null; + const id = crypto.createHash('sha256').update(String(code)).digest('hex'); + + return db.transaction(async (tx) => { + const row = await tx.get( + `SELECT id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce, + code_challenge, code_challenge_method, session_id, auth_time, + expires_at, consumed_at + FROM authorization_codes + WHERE id = {id}`, + { id } + ); + if (!row || row.consumed_at || row.expires_at <= now || row.client_id !== clientId) { + return null; + } + await tx.run('UPDATE authorization_codes SET consumed_at = {now} WHERE id = {id}', { now, id }); + return row; + }); +} diff --git a/server/src/lib/policy.js b/server/src/lib/policy.js @@ -2,8 +2,8 @@ export function isRealmAdmin(roles) { return Array.isArray(roles) && roles.includes('realm-admin'); } -export function isSystemAdmin(roles) { - return Array.isArray(roles) && roles.includes('system-admin'); +export function isSystemAdmin(user) { + return Boolean(user?.is_system_admin); } export function canUseClient({ user, membership, roles, client, realm }) { @@ -13,6 +13,11 @@ export function canUseClient({ user, membership, roles, client, realm }) { const requiredRoles = Array.isArray(client.required_roles) ? client.required_roles : []; const roleOk = requiredRoles.length === 0 || requiredRoles.some((role) => roles.includes(role)); + if (client.virtual && client.client_id === 'admin') { + if (isSystemAdmin(user)) return true; + return Boolean(membership && membership.status === 'active' && roles.includes('realm-admin')); + } + if (client.access_mode === 'public') return true; if (!membership || membership.status !== 'active') return false; diff --git a/server/src/lib/realm.js b/server/src/lib/realm.js @@ -23,7 +23,6 @@ async function migrateRealm(db, label) { } async function migrateSystem(db) { - await migrateRealm(db, 'system'); return runMigrations(db, { dir: migrationDir(db.dialect, 'system'), namespace: 'system', @@ -51,54 +50,9 @@ async function ensureRole(db, slug, name, now) { return id; } -async function ensureClientRole(db, clientId, roleSlug) { - const role = await db.get('SELECT id FROM roles WHERE slug = {slug}', { slug: roleSlug }); - if (!role) return; - const existing = await db.get( - 'SELECT client_id FROM oidc_client_roles WHERE client_id = {clientId} AND role_id = {roleId}', - { clientId, roleId: role.id } - ); - if (existing) return; - await db.run( - 'INSERT INTO oidc_client_roles (client_id, role_id) VALUES ({clientId}, {roleId})', - { clientId, roleId: role.id } - ); -} - -async function ensureAdminClient(db, now) { - let client = await db.get('SELECT id FROM oidc_clients WHERE client_id = {clientId}', { - clientId: 'admin-ui', - }); - if (!client) { - client = { id: crypto.randomUUID() }; - await db.run( - `INSERT INTO oidc_clients - (id, client_id, name, redirect_uris, scopes, access_mode, enabled, created_at, updated_at) - VALUES - ({id}, {clientId}, {name}, {redirectUris}, {scopes}, 'members', 1, {createdAt}, {updatedAt})`, - { - id: client.id, - clientId: 'admin-ui', - name: 'Admin UI', - redirectUris: '[]', - scopes: 'openid profile email', - createdAt: now, - updatedAt: now, - } - ); - } - - await ensureClientRole(db, client.id, 'realm-admin'); - await ensureClientRole(db, client.id, 'system-admin'); -} - -async function seedRealmDefaults(db, kind) { +async function seedRealmDefaults(db) { const now = Date.now(); await ensureRole(db, 'realm-admin', 'Realm administrator', now); - if (kind === 'system') { - await ensureRole(db, 'system-admin', 'System administrator', now); - } - await ensureAdminClient(db, now); } async function writeRealmSettings(db, settings) { @@ -120,39 +74,6 @@ async function writeRealmSettings(db, settings) { ); } -async function ensureSystemRealm() { - const settings = await systemDb.get('SELECT id FROM realm_settings WHERE id = 1'); - if (!settings) { - await writeRealmSettings(systemDb, { - slug: 'system', - displayName: 'System', - kind: 'system', - }); - } - - const registry = await systemDb.get('SELECT id FROM realms WHERE id = {id}', { id: 'system' }); - if (!registry) { - await systemDb.run( - `INSERT INTO realms (id, slug, db_file, owner_user_id, created_at) - VALUES ({id}, {slug}, NULL, NULL, {createdAt})`, - { id: 'system', slug: 'system', createdAt: Date.now() } - ); - } - - await seedRealmDefaults(systemDb, 'system'); - - const hosts = await systemDb.get('SELECT COUNT(*) AS count FROM realm_hosts'); - if (Number(hosts.count) === 0) { - const now = Date.now(); - for (const host of ['localhost', '127.0.0.1', '[::1]']) { - await systemDb.run( - 'INSERT INTO realm_hosts (host, realm_id, created_at) VALUES ({host}, {realmId}, {createdAt})', - { host, realmId: 'system', createdAt: now } - ); - } - } -} - export function normalizeHost(host) { let value = String(host || '').trim().toLowerCase(); if (!value) return ''; @@ -186,7 +107,6 @@ export async function initRealms(cfg) { systemDb = await openDatabase({ dialect, path: systemPath }); await migrateSystem(systemDb); - await ensureSystemRealm(); } export async function closeRealms() { @@ -207,11 +127,6 @@ export function getSystemDatabase() { } export async function openRealmDatabase(realm) { - if (realm.id === 'system') { - if (!systemDb) throw new Error('realm registry is not initialized'); - return systemDb; - } - const cached = realmDbs.get(realm.id); if (cached) return cached; @@ -225,7 +140,7 @@ export async function openRealmDatabase(realm) { const db = await openDatabase({ dialect, path: fullPath }); await migrateRealm(db, `realm ${realm.slug}`); - await seedRealmDefaults(db, 'realm'); + await seedRealmDefaults(db); realmDbs.set(realm.id, db); return db; } @@ -255,6 +170,20 @@ export async function resolveRealm({ host, slug } = {}) { const normalizedHost = normalizeHost(host); if (normalizedHost) { + const byClientHost = await systemDb.get( + `SELECT r.id, r.slug, r.db_file, r.owner_user_id + FROM oidc_client_hosts h + JOIN realms r ON r.id = h.realm_id + WHERE h.host = {host}`, + { host: normalizedHost } + ); + if (byClientHost) { + if (slug && slug !== byClientHost.slug) { + throw new HttpError(404, 'unknown_realm', 'Unknown realm'); + } + return byClientHost; + } + const byHost = await systemDb.get( `SELECT r.id, r.slug, r.db_file, r.owner_user_id FROM realm_hosts h @@ -311,7 +240,7 @@ export async function createRealm({ branding, allowSessionDurationChoice, }); - await seedRealmDefaults(db, 'realm'); + await seedRealmDefaults(db); } catch (e) { await db.close(); fs.rmSync(fullPath, { force: true }); @@ -351,6 +280,45 @@ export async function addRealmHost(realmId, host) { ); } +export async function addOidcClientHost(realmId, clientId, host) { + if (!systemDb) throw new Error('realm registry is not initialized'); + const normalized = normalizeHost(host); + if (!normalized || normalized !== String(host).trim().toLowerCase()) { + throw new Error(`invalid client hostname: ${JSON.stringify(host)}`); + } + await systemDb.run( + `INSERT INTO oidc_client_hosts (host, realm_id, client_id, created_at) + VALUES ({host}, {realmId}, {clientId}, {createdAt})`, + { host: normalized, realmId, clientId, createdAt: Date.now() } + ); +} + +export async function findOidcClientHost(host) { + if (!systemDb) throw new Error('realm registry is not initialized'); + const normalized = normalizeHost(host); + if (!normalized) return null; + return systemDb.get( + `SELECT h.host, h.realm_id, h.client_id, r.slug, r.db_file, r.owner_user_id + FROM oidc_client_hosts h + JOIN realms r ON r.id = h.realm_id + WHERE h.host = {host}`, + { host: normalized } + ); +} + +export async function findRealmHost(host) { + if (!systemDb) throw new Error('realm registry is not initialized'); + const normalized = normalizeHost(host); + if (!normalized) return null; + return systemDb.get( + `SELECT r.id, r.slug, r.db_file, r.owner_user_id + FROM realm_hosts h + JOIN realms r ON r.id = h.realm_id + WHERE h.host = {host}`, + { host: normalized } + ); +} + export async function addRealmEmailDomain(realmId, domain, { verified = true } = {}) { if (!systemDb) throw new Error('realm registry is not initialized'); const normalized = normalizeEmailDomain(domain); diff --git a/server/src/lib/session.js b/server/src/lib/session.js @@ -152,11 +152,6 @@ export async function authenticateRequest({ } const membership = await getMembership(realmDb, user.id); - if (!membership || membership.status !== 'active') { - await destroySession(realmDb, token); - clearSessionCookie(res, req, realm); - return null; - } if (now - session.last_seen_at >= TOUCH_INTERVAL_MS) { const expiresAt = now + session.ttl * 1000; diff --git a/server/src/lib/users.js b/server/src/lib/users.js @@ -15,7 +15,7 @@ export function emailDomain(email) { return at > 0 && at < normalized.length - 1 ? normalized.slice(at + 1) : null; } -export async function createUser(db, { username, displayName = null, homeRealmId = null }) { +export async function createUser(db, { username, displayName = null, homeRealmId = null, isSystemAdmin = false }) { const normalized = normalizeUsername(username); if (!normalized) throw new Error('username is required'); const existing = await db.get( @@ -28,15 +28,16 @@ export async function createUser(db, { username, displayName = null, homeRealmId const now = Date.now(); await db.run( `INSERT INTO users - (id, username, username_normalized, display_name, status, home_realm_id, profile, created_at, updated_at) + (id, username, username_normalized, display_name, status, home_realm_id, is_system_admin, profile, created_at, updated_at) VALUES - ({id}, {username}, {normalized}, {displayName}, 'active', {homeRealmId}, '{}', {createdAt}, {updatedAt})`, + ({id}, {username}, {normalized}, {displayName}, 'active', {homeRealmId}, {isSystemAdmin}, '{}', {createdAt}, {updatedAt})`, { id, username, normalized, displayName: displayName || username, homeRealmId, + isSystemAdmin: isSystemAdmin ? 1 : 0, createdAt: now, updatedAt: now, } @@ -47,7 +48,7 @@ export async function createUser(db, { username, displayName = null, homeRealmId export async function findUserById(db, id) { return db.get( `SELECT id, username, username_normalized, display_name, status, home_realm_id, - profile, last_login_at, created_at, updated_at + is_system_admin, profile, last_login_at, created_at, updated_at FROM users WHERE id = {id}`, { id } @@ -58,7 +59,7 @@ export async function findUserByEmail(db, email) { const normalized = normalizeEmail(email); return db.get( `SELECT u.id, u.username, u.username_normalized, u.display_name, u.status, - u.home_realm_id, u.profile, u.last_login_at, + u.home_realm_id, u.is_system_admin, u.profile, u.last_login_at, e.email, e.email_normalized FROM users u JOIN user_emails e ON e.user_id = u.id @@ -71,7 +72,7 @@ export async function findUserByUsername(db, username) { const normalized = normalizeUsername(username); return db.get( `SELECT id, username, username_normalized, display_name, status, - home_realm_id, profile, last_login_at + home_realm_id, is_system_admin, profile, last_login_at FROM users WHERE username_normalized = {username}`, { username: normalized } @@ -176,6 +177,13 @@ export async function getPasswordCredential(db, userId) { ); } +export async function setSystemAdmin(db, userId, value = true) { + await db.run( + 'UPDATE users SET is_system_admin = {value}, updated_at = {now} WHERE id = {userId}', + { value: value ? 1 : 0, now: Date.now(), userId } + ); +} + export async function updateLastLogin(db, userId, now = Date.now()) { await db.run( 'UPDATE users SET last_login_at = {now}, updated_at = {now} WHERE id = {userId}', diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -1,12 +1,14 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; +import crypto from 'node:crypto'; import fs from 'node:fs/promises'; import http from 'node:http'; import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { createLocalJWKSet, jwtVerify } from 'jose'; const serverDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); @@ -81,15 +83,24 @@ function startServer(env) { }); } -function request(port, { method = 'GET', path: requestPath = '/', host, body, cookie } = {}) { +function request( + port, + { method = 'GET', path: requestPath = '/', host, body, form, cookie, bearer, headers: extraHeaders = {} } = {} +) { return new Promise((resolve, reject) => { - const payload = body === undefined ? null : JSON.stringify(body); - const headers = { host }; - if (payload !== null) { + let payload = null; + const headers = { host, ...extraHeaders }; + if (body !== undefined) { + payload = JSON.stringify(body); headers['content-type'] = 'application/json'; headers['content-length'] = Buffer.byteLength(payload); + } else if (form !== undefined) { + payload = new URLSearchParams(form).toString(); + headers['content-type'] = 'application/x-www-form-urlencoded'; + headers['content-length'] = Buffer.byteLength(payload); } if (cookie) headers.cookie = cookie; + if (bearer) headers.authorization = `Bearer ${bearer}`; const req = http.request( { host: '127.0.0.1', port, method, path: requestPath, headers }, @@ -114,10 +125,22 @@ function request(port, { method = 'GET', path: requestPath = '/', host, body, co }); } -function sessionCookie(response) { +function responseCookies(response) { const values = response.headers['set-cookie']; - if (!values || values.length === 0) return null; - return values[0].split(';')[0]; + return Array.isArray(values) ? values.map((value) => value.split(';')[0]) : []; +} + +function mergeCookies(existing, response) { + const jar = new Map(); + for (const pair of existing ? existing.split('; ') : []) { + const index = pair.indexOf('='); + if (index !== -1) jar.set(pair.slice(0, index), pair.slice(index + 1)); + } + for (const pair of responseCookies(response)) { + const index = pair.indexOf('='); + if (index !== -1) jar.set(pair.slice(0, index), pair.slice(index + 1)); + } + return [...jar.entries()].map(([name, value]) => `${name}=${value}`).join('; '); } function maxAge(response) { @@ -127,24 +150,39 @@ function maxAge(response) { return match ? Number(match[1]) : null; } -test('HTTP login, session, provider and logout flows', async (t) => { +function pkce() { + const verifier = crypto.randomBytes(32).toString('base64url'); + const challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); + return { verifier, challenge }; +} + +function locationQuery(response) { + return new URL(response.headers.location, 'http://localhost'); +} + +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(); + const publicUrl = `http://identity.test:${port}`; const env = { AUTH_DATABASE_PATH: path.join(dir, 'system.sqlite'), AUTH_REALMS_PATH: path.join(dir, 'realms'), AUTH_PORT: String(port), + AUTH_PUBLIC_URL: publicUrl, }; + const origin = (host) => `http://${host}:${port}`; let server = null; + try { await runNode('scripts/seed-demo.js', env); server = await startServer(env); - const acme = (options = {}) => - request(port, { host: 'acme.localhost', ...options }); - const globex = (options = {}) => - request(port, { host: 'globex.localhost', ...options }); + const identity = (options = {}) => + request(port, { host: `identity.test:${port}`, ...options }); + const acme = (options = {}) => request(port, { host: `acme.localhost:${port}`, ...options }); + const globex = (options = {}) => request(port, { host: `globex.localhost:${port}`, ...options }); + const app = (options = {}) => request(port, { host: `app.acme.localhost:${port}`, ...options }); await t.test('realm metadata is served for a realm hostname', async () => { const response = await acme({ path: '/api/v1/realm' }); @@ -154,11 +192,48 @@ test('HTTP login, session, provider and logout flows', async (t) => { }); await t.test('hostname wins over a conflicting path slug', async () => { - const response = await acme({ path: '/api/v1/realm?realm=system' }); + const response = await acme({ path: '/api/v1/realm?realm=globex' }); assert.equal(response.status, 404); assert.equal(response.json.error.code, 'unknown_realm'); }); + await t.test('client discovery works on identity, realm and client hosts', async () => { + const canonical = await identity({ + path: '/oidc/acme/internal-app/openid-configuration', + }); + assert.equal(canonical.status, 200); + assert.equal(canonical.json.client_id, 'internal-app'); + assert.equal(canonical.json.issuer, `${publicUrl}/oidc/acme`); + assert.equal( + canonical.json.authorization_endpoint, + `${origin('identity.test')}/oidc/acme/internal-app/authorize` + ); + + const realmHost = await acme({ path: '/oidc/internal-app/openid-configuration' }); + assert.equal(realmHost.status, 200); + assert.equal( + realmHost.json.token_endpoint, + `${origin('acme.localhost')}/oidc/internal-app/token` + ); + + const clientHost = await app({ path: '/oidc/openid-configuration' }); + assert.equal(clientHost.status, 200); + assert.equal(clientHost.json.client_id, 'internal-app'); + assert.equal(clientHost.json.token_endpoint, `${origin('app.acme.localhost')}/oidc/token`); + }); + + await t.test('virtual clients are discoverable', async () => { + const admin = await acme({ path: '/oidc/admin/openid-configuration' }); + assert.equal(admin.status, 200); + assert.equal(admin.json.virtual, true); + assert.equal(admin.json.access_mode, 'admin'); + + const account = await acme({ path: '/oidc/account/openid-configuration' }); + assert.equal(account.status, 200); + assert.equal(account.json.virtual, true); + assert.equal(account.json.access_mode, 'public'); + }); + await t.test('identifier resolution selects password or upstream OIDC', async () => { const password = await acme({ method: 'POST', @@ -182,24 +257,28 @@ test('HTTP login, session, provider and logout flows', async (t) => { const response = await acme({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'alice@acme.test', password: 'demo' }, + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, }); assert.equal(response.status, 200); assert.equal(response.json.user.username, 'alice'); assert.equal(maxAge(response), 12 * 60 * 60); - const cookie = sessionCookie(response); + const cookie = mergeCookies('', response); const session = await acme({ path: '/api/v1/session', cookie }); assert.equal(session.status, 200); assert.equal(session.json.user.username, 'alice'); - assert.deepEqual(session.json.roles, []); }); await t.test('long sessions are only issued when requested', async () => { const response = await acme({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'alice@acme.test', password: 'demo', long_session: true }, + body: { + client_id: 'internal-app', + identifier: 'alice@acme.test', + password: 'demo', + long_session: true, + }, }); assert.equal(response.status, 200); assert.equal(maxAge(response), 7 * 24 * 60 * 60); @@ -209,24 +288,24 @@ test('HTTP login, session, provider and logout flows', async (t) => { const response = await acme({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'alice@acme.test', password: 'wrong' }, + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'wrong' }, }); assert.equal(response.status, 401); assert.equal(response.json.error.code, 'invalid_credentials'); }); - await t.test('membership is required for a realm', async () => { - const denied = await globex({ + await t.test('membership is required where the client demands it', async () => { + const denied = await acme({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'guest@personal.test', password: 'demo' }, + body: { client_id: 'members-app', identifier: 'contractor@personal.test', password: 'demo' }, }); assert.equal(denied.status, 401); const allowed = await acme({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'guest@personal.test', password: 'demo' }, + body: { client_id: 'public-app', identifier: 'guest@personal.test', password: 'demo' }, }); assert.equal(allowed.status, 200); }); @@ -235,7 +314,7 @@ test('HTTP login, session, provider and logout flows', async (t) => { const response = await acme({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'someone@sso.acme.test', password: 'demo' }, + body: { client_id: 'internal-app', identifier: 'someone@sso.acme.test', password: 'demo' }, }); assert.equal(response.status, 403); assert.equal(response.json.error.code, 'provider_required'); @@ -245,31 +324,226 @@ test('HTTP login, session, provider and logout flows', async (t) => { const response = await globex({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'contractor@personal.test', password: 'demo' }, + body: { client_id: 'members-app', identifier: 'contractor@personal.test', password: 'demo' }, }); assert.equal(response.status, 200); const session = await globex({ path: '/api/v1/session', - cookie: sessionCookie(response), + cookie: mergeCookies('', response), }); assert.equal(session.status, 200); assert.ok(session.json.roles.includes('realm-admin')); }); + await t.test('authorization code flow issues verifiable tokens', async () => { + const { verifier, challenge } = pkce(); + const redirectUri = `${origin('app.acme.localhost')}/callback`; + const authorizePath = + `/oidc/authorize?response_type=code&client_id=internal-app` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20profile%20email` + + `&state=state-1&nonce=nonce-1&code_challenge=${challenge}&code_challenge_method=S256`; + + const first = await app({ path: authorizePath }); + assert.equal(first.status, 302); + assert.equal(locationQuery(first).pathname, '/oidc/login'); + let jar = mergeCookies('', first); + + const login = await app({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + cookie: jar, + }); + assert.equal(login.status, 200); + assert.equal(login.json.pending_auth_request, true); + jar = mergeCookies(jar, login); + + const second = await app({ path: authorizePath, cookie: jar }); + assert.equal(second.status, 302); + const redirected = locationQuery(second); + assert.equal(redirected.origin + redirected.pathname, redirectUri); + assert.equal(redirected.searchParams.get('state'), 'state-1'); + const code = redirected.searchParams.get('code'); + assert.ok(code); + + const tokenResponse = await app({ + method: 'POST', + path: '/oidc/token', + form: { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: 'internal-app', + code_verifier: verifier, + }, + }); + assert.equal(tokenResponse.status, 200); + assert.ok(tokenResponse.json.id_token); + assert.ok(tokenResponse.json.access_token); + + const jwks = await app({ path: '/oidc/jwks' }); + const keySet = createLocalJWKSet(jwks.json); + const { payload } = await jwtVerify(tokenResponse.json.id_token, keySet, { + issuer: `${publicUrl}/oidc/acme`, + audience: 'internal-app', + }); + assert.equal(payload.preferred_username, 'alice'); + assert.equal(payload.email, 'alice@acme.test'); + assert.equal(payload.nonce, 'nonce-1'); + + const userinfo = await app({ + path: '/oidc/userinfo', + bearer: tokenResponse.json.access_token, + }); + assert.equal(userinfo.status, 200); + assert.equal(userinfo.json.preferred_username, 'alice'); + + const reuse = await app({ + method: 'POST', + path: '/oidc/token', + form: { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: 'internal-app', + code_verifier: verifier, + }, + }); + assert.equal(reuse.status, 400); + assert.equal(reuse.json.error, 'invalid_grant'); + }); + + await t.test('public clients allow non-members through authorize', async () => { + const { verifier, challenge } = pkce(); + const redirectUri = `${origin('public.localhost')}/callback`; + const authorizePath = + `/oidc/public-app/authorize?response_type=code&client_id=public-app` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` + + `&state=state-2&code_challenge=${challenge}&code_challenge_method=S256`; + + const first = await acme({ path: authorizePath }); + assert.equal(first.status, 302); + let jar = mergeCookies('', first); + + const login = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'public-app', identifier: 'contractor@personal.test', password: 'demo' }, + cookie: jar, + }); + assert.equal(login.status, 200); + assert.equal(login.json.pending_auth_request, true); + jar = mergeCookies(jar, login); + + const second = await acme({ path: authorizePath, cookie: jar }); + assert.equal(second.status, 302); + const code = locationQuery(second).searchParams.get('code'); + assert.ok(code); + + const tokenResponse = await acme({ + method: 'POST', + path: '/oidc/public-app/token', + form: { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: 'public-app', + code_verifier: verifier, + }, + }); + assert.equal(tokenResponse.status, 200); + }); + + await t.test('system admins can use the admin virtual client', async () => { + const redirectUri = `${origin('acme.localhost')}/oidc/admin/callback`; + const { verifier, challenge } = pkce(); + const authorizePath = + `/oidc/admin/authorize?response_type=code&client_id=admin` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20profile` + + `&state=state-3&code_challenge=${challenge}&code_challenge_method=S256`; + + const first = await acme({ path: authorizePath }); + assert.equal(first.status, 302); + let jar = mergeCookies('', first); + + const login = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'admin', identifier: 'admin@system.test', password: 'demo' }, + cookie: jar, + }); + assert.equal(login.status, 200); + jar = mergeCookies(jar, login); + + const second = await acme({ path: authorizePath, cookie: jar }); + assert.equal(second.status, 302); + const code = locationQuery(second).searchParams.get('code'); + assert.ok(code); + + const tokenResponse = await acme({ + method: 'POST', + path: '/oidc/admin/token', + form: { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: 'admin', + code_verifier: verifier, + }, + }); + assert.equal(tokenResponse.status, 200); + }); + + await t.test('confidential clients authenticate with client_secret_basic', async () => { + const { verifier, challenge } = pkce(); + const redirectUri = `${origin('confidential.localhost')}/callback`; + const authorizePath = + `/oidc/confidential-app/authorize?response_type=code&client_id=confidential-app` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` + + `&state=state-4&code_challenge=${challenge}&code_challenge_method=S256`; + + const first = await acme({ path: authorizePath }); + let jar = mergeCookies('', first); + const login = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'confidential-app', identifier: 'alice@acme.test', password: 'demo' }, + cookie: jar, + }); + jar = mergeCookies(jar, login); + const second = await acme({ path: authorizePath, cookie: jar }); + const code = locationQuery(second).searchParams.get('code'); + + const tokenResponse = await acme({ + method: 'POST', + path: '/oidc/confidential-app/token', + form: { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + code_verifier: verifier, + }, + headers: { + authorization: `Basic ${Buffer.from('confidential-app:demo-secret').toString('base64')}`, + }, + }); + assert.equal(tokenResponse.status, 200); + }); + await t.test('logout removes only the current realm session', async () => { const acmeLogin = await acme({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'alice@acme.test', password: 'demo' }, + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, }); - const acmeCookie = sessionCookie(acmeLogin); + const acmeCookie = mergeCookies('', acmeLogin); const globexLogin = await globex({ method: 'POST', path: '/api/v1/login/password', - body: { identifier: 'contractor@personal.test', password: 'demo' }, + body: { client_id: 'members-app', identifier: 'contractor@personal.test', password: 'demo' }, }); - const globexCookie = sessionCookie(globexLogin); + const globexCookie = mergeCookies('', globexLogin); const logout = await acme({ method: 'POST', diff --git a/server/test/policy.test.js b/server/test/policy.test.js @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { canManageUser, canUseClient, isRealmAdmin } from '../src/lib/policy.js'; +import { canManageUser, canUseClient, isRealmAdmin, isSystemAdmin } from '../src/lib/policy.js'; const realm = { id: 'realm-a' }; const user = { id: 'u1', status: 'active', home_realm_id: 'realm-a' }; @@ -60,6 +60,46 @@ test('disabled users and clients are denied', () => { ); }); +test('virtual admin clients accept system admins and realm admins', () => { + const adminClient = { ...client('admin'), virtual: true, client_id: 'admin' }; + const systemAdmin = { ...guest, is_system_admin: 1 }; + + assert.equal( + canUseClient({ user: systemAdmin, membership: null, roles: [], client: adminClient, realm }), + true + ); + assert.equal( + canUseClient({ + user: guest, + membership: activeMembership, + roles: ['realm-admin'], + client: adminClient, + realm, + }), + true + ); + assert.equal( + canUseClient({ + user: guest, + membership: activeMembership, + roles: [], + client: adminClient, + realm, + }), + false + ); +}); + +test('virtual account clients accept every active user', () => { + const accountClient = { ...client('public'), virtual: true, client_id: 'account' }; + assert.equal( + canUseClient({ user: guest, membership: null, roles: [], client: accountClient, realm }), + true + ); + assert.equal(isSystemAdmin({ is_system_admin: 1 }), true); + assert.equal(isSystemAdmin({ is_system_admin: 0 }), false); +}); + test('realm admins manage home users fully and guests by membership only', () => { assert.equal(isRealmAdmin(['realm-admin']), true); assert.equal( diff --git a/server/test/session.test.js b/server/test/session.test.js @@ -129,7 +129,7 @@ test('expired sessions are rejected and removed', async () => { } }); -test('disabled users and suspended memberships lose access', async () => { +test('disabled users lose access and suspended memberships are returned', async () => { const { dir, realm, realmDb, systemDb, userId } = await setup(); try { const { token } = await createSession(realmDb, { userId, ttl: SHORT_SESSION_TTL }); @@ -152,10 +152,15 @@ test('disabled users and suspended memberships lose access', async () => { status: 'suspended', id: userId, }); - assert.equal( - await authenticateRequest({ systemDb, realmDb, req, res: mockResponse(), realm }), - null - ); + const fresh = await createSession(realmDb, { userId, ttl: SHORT_SESSION_TTL }); + const auth = await authenticateRequest({ + systemDb, + realmDb, + req: mockRequest(`${sessionCookieName(realm)}=${fresh.token}`), + res: mockResponse(), + realm, + }); + assert.equal(auth.membership.status, 'suspended'); } finally { await closeRealms(); await fs.rm(dir, { recursive: true, force: true }); diff --git a/server/web/src/main.ts b/server/web/src/main.ts @@ -3,22 +3,29 @@ import { Admin } from './screen/admin'; import { Login } from './screen/login'; const routes: m.RouteDefs = { - '/realms/:realm/login': { - render: (vnode) => m(Login, { realm: (vnode.attrs as any).realm }), + '/oidc/:realm/:clientId/login': { + render: (vnode) => + m(Login, { + realm: (vnode.attrs as any).realm, + clientId: (vnode.attrs as any).clientId, + }), }, - '/realms/:realm/admin': { - render: (vnode) => m(Admin, { realm: (vnode.attrs as any).realm }), + '/oidc/:clientId/login': { + render: (vnode) => m(Login, { clientId: (vnode.attrs as any).clientId }), }, - '/login': { + '/oidc/login': { render: () => m(Login, {}), }, + '/realms/:realm/admin': { + render: (vnode) => m(Admin, { realm: (vnode.attrs as any).realm }), + }, '/admin': { render: () => m(Admin, {}), }, '/': { - onmatch: () => m.route.set('/login'), + onmatch: () => m.route.set('/oidc/login'), }, }; m.route.prefix = ''; -m.route(document.body, '/login', routes); +m.route(document.body, '/oidc/login', routes); diff --git a/server/web/src/screen/login.tsx b/server/web/src/screen/login.tsx @@ -1,7 +1,14 @@ import m from 'mithril'; -import { getRealm, resolveLogin, signInPassword, type LoginResolution, type RealmInfo } from '../util/api'; +import { + getClientDiscovery, + resolveLogin, + signInPassword, + type ClientDiscovery, + type LoginResolution, + type PasswordLoginResult, +} from '../util/api'; -type Step = 'identifier' | 'password' | 'oidc'; +type Step = 'identifier' | 'password' | 'oidc' | 'done'; interface TextFieldAttrs { id: string; @@ -35,28 +42,33 @@ const TextField: m.Component<TextFieldAttrs> = { }, }; -export const Login: m.Component<{ realm?: string }> = { +export const Login: m.Component<{ realm?: string; clientId?: string }> = { realmSlug: null as string | null, - realm: null as RealmInfo | null, + clientId: null as string | null, + discovery: null as ClientDiscovery | null, step: 'identifier' as Step, identifier: '', password: '', longSession: false, provider: null as LoginResolution['provider'] | null, + signedIn: null as PasswordLoginResult['user'] | null, error: null as Error | null, pending: false, oninit(this: any, vnode: any) { this.realmSlug = vnode.attrs.realm ?? null; - this.loadRealm(); + this.clientId = vnode.attrs.clientId ?? null; + this.loadClient(); }, - async loadRealm(this: any) { + async loadClient(this: any) { this.error = null; try { - const realm = await getRealm(this.realmSlug); - this.realm = realm; - document.title = realm.display_name; + const discovery = await getClientDiscovery(this.realmSlug, this.clientId); + this.discovery = discovery; + this.realmSlug = discovery.realm; + this.clientId = discovery.client_id; + document.title = discovery.display_name; } catch (e) { this.error = e as Error; } @@ -67,9 +79,7 @@ export const Login: m.Component<{ realm?: string }> = { this.pending = true; this.error = null; try { - const result = await resolveLogin(this.realmSlug, this.identifier); - this.realm = result.realm; - document.title = result.realm.display_name; + const result = await resolveLogin(this.realmSlug, this.clientId, this.identifier); if (result.next === 'oidc' && result.provider) { this.provider = result.provider; this.step = 'oidc'; @@ -87,8 +97,29 @@ export const Login: m.Component<{ realm?: string }> = { this.pending = true; this.error = null; try { - await signInPassword(this.realmSlug, this.identifier, this.password, this.longSession); - m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/admin` : '/admin'); + const result = await signInPassword( + this.realmSlug, + this.clientId, + this.identifier, + this.password, + this.longSession + ); + + if (result.pending_auth_request) { + const current = m.route.get() || ''; + m.route.set(current.replace(/\/login$/, '/authorize')); + return; + } + + if (this.clientId === 'admin') { + m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/admin` : '/admin'); + return; + } + + this.signedIn = result.user; + this.step = 'done'; + this.pending = false; + m.redraw(); } catch (e) { this.error = e as Error; this.pending = false; @@ -106,11 +137,11 @@ export const Login: m.Component<{ realm?: string }> = { }, view(this: any) { - const branding = this.realm?.branding || {}; + const branding = this.discovery?.branding || {}; const primary = typeof branding.primary_color === 'string' ? branding.primary_color : '#25A'; const style = { '--realm-primary': primary } as any; - if (!this.realm && this.error) { + if (!this.discovery && this.error) { return ( <div class="auth-page" style={style}> <div class="auth-card"> @@ -121,7 +152,7 @@ export const Login: m.Component<{ realm?: string }> = { ); } - const title = this.realm?.display_name || 'Sign in'; + const title = this.discovery?.display_name || 'Sign in'; return ( <div class="auth-page" style={style}> @@ -131,15 +162,16 @@ export const Login: m.Component<{ realm?: string }> = { ) : null} <h1>{title}</h1> - {this.step === 'identifier' ? this.renderIdentifier(title) : null} + {this.step === 'identifier' ? this.renderIdentifier() : null} {this.step === 'password' ? this.renderPassword() : null} {this.step === 'oidc' ? this.renderProvider() : null} + {this.step === 'done' ? this.renderDone() : null} </div> </div> ); }, - renderIdentifier(this: any, title: string) { + renderIdentifier(this: any) { return ( <form onsubmit={(e: Event) => { @@ -189,7 +221,7 @@ export const Login: m.Component<{ realm?: string }> = { this.password = value; }} /> - {this.realm?.allow_session_duration_choice ? ( + {this.discovery?.allow_session_duration_choice !== false ? ( <label class="auth-choice"> <input type="checkbox" @@ -221,7 +253,9 @@ export const Login: m.Component<{ realm?: string }> = { <div> <p class="auth-identifier">{this.identifier}</p> <p class="auth-note"> - {provider ? `This account signs in with ${provider.display_name}.` : 'This account signs in with an identity provider.'} + {provider + ? `This account signs in with ${provider.display_name}.` + : 'This account signs in with an identity provider.'} </p> <div class="auth-actions"> <button class="auth-link" type="button" onclick={() => this.back()}> @@ -234,4 +268,13 @@ export const Login: m.Component<{ realm?: string }> = { </div> ); }, + + renderDone(this: any) { + const user = this.signedIn; + return ( + <div> + <p class="auth-note">Signed in as {user?.display_name || user?.username}</p> + </div> + ); + }, }; diff --git a/server/web/src/util/api.ts b/server/web/src/util/api.ts @@ -5,6 +5,19 @@ export interface RealmInfo { allow_session_duration_choice: boolean; } +export interface ClientDiscovery { + issuer: string; + client_id: string; + client_name: string; + realm: string; + display_name: string; + branding: Record<string, string>; + access_mode: string; + virtual: boolean; + require_pkce: boolean; + allow_session_duration_choice: boolean; +} + export interface LoginResolution { realm: RealmInfo; next: 'password' | 'oidc'; @@ -14,6 +27,17 @@ export interface LoginResolution { }; } +export interface PasswordLoginResult { + realm: RealmInfo; + user: { + id: string; + username: string; + display_name: string | null; + }; + expires_at: number; + pending_auth_request: boolean; +} + export interface SessionInfo { realm: RealmInfo; user: { @@ -61,23 +85,44 @@ export function getRealm(realm?: string | null): Promise<RealmInfo> { return request<RealmInfo>(`/api/v1/realm${query}`); } -export function resolveLogin(realm: string | null, identifier: string): Promise<LoginResolution> { +export function getClientDiscovery( + realm?: string | null, + clientId?: string | null +): Promise<ClientDiscovery> { + if (realm && clientId) { + return request<ClientDiscovery>( + `/oidc/${encodeURIComponent(realm)}/${encodeURIComponent(clientId)}/openid-configuration` + ); + } + if (clientId) { + return request<ClientDiscovery>(`/oidc/${encodeURIComponent(clientId)}/openid-configuration`); + } + return request<ClientDiscovery>('/oidc/openid-configuration'); +} + +export function resolveLogin( + realm: string | null, + clientId: string, + identifier: string +): Promise<LoginResolution> { return request<LoginResolution>('/api/v1/login/resolve', { method: 'POST', - body: JSON.stringify({ realm: realm || undefined, identifier }), + body: JSON.stringify({ realm: realm || undefined, client_id: clientId, identifier }), }); } export function signInPassword( realm: string | null, + clientId: string, identifier: string, password: string, longSession: boolean -): Promise<SessionInfo> { - return request<SessionInfo>('/api/v1/login/password', { +): Promise<PasswordLoginResult> { + return request<PasswordLoginResult>('/api/v1/login/password', { method: 'POST', body: JSON.stringify({ realm: realm || undefined, + client_id: clientId, identifier, password, long_session: longSession,