auth

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

commit 981d3a348f7fab13bd4cf3d442fe58e5a847dd90
parent 7a04adeb3e6cc6dc68c9d88488be63ecd73fd6be
Author: finwo <finwo@pm.me>
Date:   Sun,  8 Nov 2026 01:41:27 +0100

Implemented realm client-host management

Diffstat:
Aapp/admin/src/component/client-hosts.tsx | 407+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/screen/client-edit.tsx | 9+++++++++
Mapp/admin/src/screen/hosts.tsx | 47++---------------------------------------------
Mapp/admin/src/util/api.ts | 20++++++++++++++++++++
Mapp/admin/src/util/auth.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/util/format.ts | 5+++++
Aapp/admin/src/util/hosts.ts | 39+++++++++++++++++++++++++++++++++++++++
Aserver/src/controller/admin/client-hosts.js | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/src/lib/admin-client-hosts.js | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/realm.js | 21+++++++++++++++++++++
Mserver/src/lib/session.js | 18++++++++++++++++++
Mserver/test/http.test.js | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 989 insertions(+), 45 deletions(-)

diff --git a/app/admin/src/component/client-hosts.tsx b/app/admin/src/component/client-hosts.tsx @@ -0,0 +1,407 @@ +import m from 'mithril'; +import { Modal } from '@component/modal'; +import { + createAdminClientHost, + deleteAdminClientHost, + loadAdminClientHosts, +} from '../util/auth'; +import { type AdminClientHost } from '../util/api'; +import { formatDate } from '../util/format'; +import { hostFormatError, normalizeHostValue } from '../util/hosts'; + +interface ClientHostsAttrs { + realmSlug: string; + clientId: string; + clientName: string; + canEdit: boolean; + onAuthExpired: () => void; +} + +function hostRequestError(e: any): boolean { + return e?.status === 401 || (e?.status === 400 && e?.code !== 'invalid_request'); +} + +function clientKey(realmSlug: string, clientId: string) { + return `${realmSlug}:${clientId}`; +} + +export const ClientHostsPanel: m.Component<ClientHostsAttrs> = { + attrs: null as ClientHostsAttrs | null, + loadedKey: null as string | null, + loading: false, + hosts: null as AdminClientHost[] | null, + error: null as Error | null, + notice: null as string | null, + search: '', + + addOpen: false, + addValue: '', + addError: null as Error | string | null, + addInvalid: false, + creating: false, + + removeTarget: null as string | null, + removeConfirm: '', + removeError: null as Error | null, + removing: false, + + oninit(this: any, vnode: m.Vnode<ClientHostsAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + onupdate(this: any, vnode: m.Vnode<ClientHostsAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + ensure(this: any) { + const { realmSlug, clientId } = this.attrs; + const key = clientKey(realmSlug, clientId); + if (key === this.loadedKey) return; + this.loadedKey = key; + this.load(realmSlug, clientId); + }, + + async load(this: any, realmSlug: string, clientId: string) { + const key = clientKey(realmSlug, clientId); + this.loading = true; + this.error = null; + this.notice = null; + this.hosts = null; + this.search = ''; + m.redraw(); + + try { + const hosts = await loadAdminClientHosts(realmSlug, clientId); + if (this.loadedKey !== key) return; + this.hosts = hosts; + } catch (e: any) { + if (this.loadedKey !== key) return; + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + if (this.loadedKey === key) this.loading = false; + m.redraw(); + } + }, + + resetAdd(this: any) { + this.addOpen = false; + this.addValue = ''; + this.addError = null; + this.addInvalid = false; + this.creating = false; + }, + + openAdd(this: any) { + this.resetAdd(); + this.addOpen = true; + m.redraw(); + }, + + async submitAdd(this: any) { + const { realmSlug, clientId } = this.attrs; + const formatError = hostFormatError(this.addValue); + if (formatError) { + this.addError = formatError; + this.addInvalid = true; + m.redraw(); + return; + } + + const host = normalizeHostValue(this.addValue); + this.creating = true; + this.addError = null; + this.addInvalid = false; + m.redraw(); + + try { + const response = await createAdminClientHost(realmSlug, clientId, host); + if (this.loadedKey !== clientKey(realmSlug, clientId)) { + this.resetAdd(); + return; + } + this.hosts = [response.host, ...(this.hosts || [])]; + this.notice = `Host ${response.host.host} added.`; + this.resetAdd(); + } catch (e: any) { + if (hostRequestError(e)) { + this.attrs.onAuthExpired(); + return; + } + this.addError = (e as Error).message || 'Unable to add host.'; + this.addInvalid = true; + } finally { + this.creating = false; + m.redraw(); + } + }, + + resetRemove(this: any) { + this.removeTarget = null; + this.removeConfirm = ''; + this.removeError = null; + this.removing = false; + }, + + openRemove(this: any, host: string) { + this.resetRemove(); + this.removeTarget = host; + m.redraw(); + }, + + async submitRemove(this: any) { + const { realmSlug, clientId } = this.attrs; + const target = this.removeTarget; + if (!target || this.removing) return; + if (normalizeHostValue(this.removeConfirm) !== target) return; + + this.removing = true; + this.removeError = null; + m.redraw(); + + try { + const result = await deleteAdminClientHost(realmSlug, clientId, target); + if (this.loadedKey === clientKey(realmSlug, clientId)) { + this.hosts = (this.hosts || []).filter((entry) => entry.host !== result.host); + this.notice = `Host ${result.host} removed.`; + } + this.resetRemove(); + } catch (e: any) { + if (hostRequestError(e)) { + this.attrs.onAuthExpired(); + return; + } + this.removeError = e as Error; + } finally { + this.removing = false; + m.redraw(); + } + }, + + view(this: any) { + const { clientName, canEdit } = this.attrs; + const hosts = this.hosts as AdminClientHost[] | null; + const term = this.search.trim().toLowerCase(); + const visible = hosts ? hosts.filter((entry) => !term || entry.host.includes(term)) : []; + + return ( + <section class="panel" aria-label="Client hosts"> + <h2>Hosts</h2> + <p class="note">Hostnames that resolve to this client.</p> + + {this.notice ? ( + <div class="notice" role="status"> + {this.notice} + </div> + ) : null} + + {this.error ? ( + <div class="alert" role="alert"> + <p>{this.error.message}</p> + <button + class="button-secondary" + type="button" + onclick={() => this.load(this.attrs.realmSlug, this.attrs.clientId)} + > + Try again + </button> + </div> + ) : null} + + {this.loading || !hosts ? ( + <div aria-busy="true"> + <div class="skeleton skeleton-title"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + </div> + ) : ( + <div> + <div class="table-toolbar"> + <div class="table-search"> + <input + type="search" + value={this.search} + aria-label="Search hosts" + placeholder="Search hosts" + oninput={(event: Event) => { + this.search = (event.target as HTMLInputElement).value; + }} + /> + </div> + {canEdit ? ( + <div class="table-actions"> + <button class="button" type="button" onclick={() => this.openAdd()}> + Add host + </button> + </div> + ) : null} + </div> + + <div class="data-table-wrap"> + <table class="data-table data-table-static host-table"> + <thead> + <tr> + <th class="data-table-primary host-name-column" scope="col">Hostname</th> + <th class="host-added-column" scope="col">Added</th> + {canEdit ? <th class="host-action-column" scope="col">Actions</th> : null} + </tr> + </thead> + <tbody> + {visible.map((entry: AdminClientHost) => ( + <tr> + <td class="data-table-primary host-name-column" data-label="Hostname"> + <span class="host-name">{entry.host}</span> + </td> + <td class="host-added-column" data-label="Added"> + <span class="host-added">{formatDate(entry.created_at)}</span> + </td> + {canEdit ? ( + <td class="host-action-column" data-label="Actions"> + <div class="host-row-action"> + <button + class="action-button is-danger" + type="button" + onclick={() => this.openRemove(entry.host)} + > + Remove + </button> + </div> + </td> + ) : null} + </tr> + ))} + </tbody> + </table> + {hosts.length > 0 && visible.length === 0 ? ( + <div class="empty"> + <p>No hosts match this search.</p> + </div> + ) : hosts.length === 0 ? ( + <div class="empty"> + <p>No hosts are assigned to this client.</p> + </div> + ) : null} + </div> + </div> + )} + + {this.addOpen ? ( + <Modal title="Add host" onClose={() => this.resetAdd()}> + <form + onsubmit={(event: Event) => { + event.preventDefault(); + this.submitAdd(); + }} + > + {this.addError ? ( + <div class="alert" role="alert"> + {typeof this.addError === 'string' ? this.addError : this.addError.message} + </div> + ) : null} + + <div class="form-field"> + <span class="field-label">Hostname</span> + <input + class="field-control" + type="text" + value={this.addValue} + maxlength="253" + placeholder="app.acme.test" + autocomplete="off" + spellcheck="false" + data-modal-autofocus + disabled={this.creating} + aria-invalid={this.addInvalid ? 'true' : null} + oninput={(event: Event) => { + this.addValue = (event.target as HTMLInputElement).value; + this.addError = null; + this.addInvalid = false; + }} + /> + </div> + <p class="modal-note"> + Lowercase hostname. Do not include a scheme, port, path or wildcard. + </p> + + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.creating} + onclick={() => this.resetAdd()} + > + Cancel + </button> + <button class="button" type="submit" disabled={this.creating}> + {this.creating ? 'Adding' : 'Add host'} + </button> + </div> + </form> + </Modal> + ) : null} + + {this.removeTarget ? ( + <Modal title="Remove host" onClose={() => this.resetRemove()}> + <p class="modal-note"> + Remove {this.removeTarget}? This hostname will stop resolving to {clientName}. + Sessions for this client on that host will end. Client settings and users are + unaffected. + </p> + {this.removeError ? ( + <div class="alert" role="alert"> + {this.removeError.message} + </div> + ) : null} + + <div class="form-field"> + <span class="field-label">Confirm hostname</span> + <input + class="field-control" + type="text" + value={this.removeConfirm} + maxlength="253" + placeholder={this.removeTarget} + autocomplete="off" + spellcheck="false" + data-modal-autofocus + disabled={this.removing} + oninput={(event: Event) => { + this.removeConfirm = (event.target as HTMLInputElement).value; + this.removeError = null; + }} + /> + </div> + <p class="modal-note">Type the hostname exactly to confirm.</p> + + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.removing} + onclick={() => this.resetRemove()} + > + Cancel + </button> + <button + class="button-danger" + type="button" + disabled={ + this.removing || + normalizeHostValue(this.removeConfirm) !== this.removeTarget + } + onclick={() => this.submitRemove()} + > + {this.removing ? 'Removing' : 'Remove host'} + </button> + </div> + </Modal> + ) : null} + </section> + ); + }, +}; diff --git a/app/admin/src/screen/client-edit.tsx b/app/admin/src/screen/client-edit.tsx @@ -14,6 +14,7 @@ import { toClientInput, validateClientBranding, } from '../component/client-form'; +import { ClientHostsPanel } from '../component/client-hosts'; import { deleteAdminClient, loadAdminClients, @@ -380,6 +381,14 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { )} </section> + <ClientHostsPanel + realmSlug={this.attrs.realmSlug || ''} + clientId={clientId || ''} + clientName={client.name} + canEdit={Boolean(selected?.can_edit)} + onAuthExpired={this.attrs.onAuthExpired} + /> + <section class="panel danger-zone"> <h2>Danger zone</h2> <p class="note"> diff --git a/app/admin/src/screen/hosts.tsx b/app/admin/src/screen/hosts.tsx @@ -10,6 +10,8 @@ import { loadAdminRealmHosts, } from '../util/auth'; import { type AdminRealm, type AdminRealmHost } from '../util/api'; +import { formatDate } from '../util/format'; +import { hostFormatError, normalizeHostValue } from '../util/hosts'; interface HostsAttrs { realmSlug: string | null; @@ -19,51 +21,6 @@ interface HostsAttrs { onAuthExpired: () => void; } -function formatDate(value: number | null | undefined) { - if (!value) return 'Unknown'; - return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' }).format(new Date(value)); -} - -function normalizeHostValue(raw: string) { - return raw.trim().toLowerCase(); -} - -function hostFormatError(raw: string): string | null { - const value = raw.trim(); - const host = normalizeHostValue(value); - - if (!host) return 'Hostname is required.'; - if (/\s/.test(value)) return 'Hostname must not contain spaces.'; - if (host.includes('://') || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) { - return 'Hostname must not include a scheme such as https://.'; - } - if (host.includes('@')) return 'Hostname must not include @.'; - if (host.includes('/')) return 'Hostname must not include a path.'; - if (host.includes('*')) return 'Wildcard hostnames are not supported.'; - if (host.startsWith('[')) { - if (!host.endsWith(']')) return 'Enter a valid IPv6 hostname.'; - } else if (host.includes(':')) { - return 'Hostname must not include a port.'; - } - if (host.length > 253) return 'Hostname must be 253 characters or fewer.'; - if (host.startsWith('.') || host.endsWith('.')) { - return 'Hostname must not start or end with a dot.'; - } - - if (!host.startsWith('[')) { - const labels = host.split('.'); - if (labels.length < 2) return 'Enter a complete hostname such as login.acme.test.'; - for (const label of labels) { - if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) { - return 'Hostname labels must use lowercase letters, numbers and hyphens.'; - } - if (label.length > 63) return 'Each hostname label must be 63 characters or fewer.'; - } - } - - return null; -} - function hostRequestError(e: any): boolean { return e?.status === 401 || (e?.status === 400 && e?.code !== 'invalid_request'); } diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -63,6 +63,26 @@ export interface AdminRealmHostDeleteResponse { host: string; } +export interface AdminClientHost { + host: string; + created_at: number; +} + +export interface AdminClientHostListResponse { + hosts: AdminClientHost[]; +} + +export interface AdminClientHostCreateResponse { + ok: boolean; + host: AdminClientHost; +} + +export interface AdminClientHostDeleteResponse { + ok: boolean; + removed: boolean; + host: string; +} + export type AdminRealmEmailDomainStatus = 'pending' | 'verified'; export interface AdminRealmEmailDomain { diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts @@ -9,6 +9,10 @@ import { type AdminClientInput, type AdminClientResponse, type AdminClientSecretResponse, + type AdminClientHost, + type AdminClientHostCreateResponse, + type AdminClientHostDeleteResponse, + type AdminClientHostListResponse, type AdminGlobalUser, type AdminGlobalUserDetail, type AdminMeUser, @@ -128,6 +132,45 @@ export async function deleteAdminRealmHost( ); } +export async function loadAdminClientHosts( + realmSlug: string, + clientId: string +): Promise<AdminClientHost[]> { + const realm = encodeURIComponent(realmSlug); + const client = encodeURIComponent(clientId); + const response = await adminJson<AdminClientHostListResponse>( + `/api/v1/admin/realms/${realm}/clients/${client}/hosts` + ); + return response.hosts; +} + +export async function createAdminClientHost( + realmSlug: string, + clientId: string, + host: string +): Promise<AdminClientHostCreateResponse> { + const realm = encodeURIComponent(realmSlug); + const client = encodeURIComponent(clientId); + return adminJson<AdminClientHostCreateResponse>( + `/api/v1/admin/realms/${realm}/clients/${client}/hosts`, + { method: 'POST', body: JSON.stringify({ host }) } + ); +} + +export async function deleteAdminClientHost( + realmSlug: string, + clientId: string, + host: string +): Promise<AdminClientHostDeleteResponse> { + const realm = encodeURIComponent(realmSlug); + const client = encodeURIComponent(clientId); + const encoded = encodeURIComponent(host); + return adminJson<AdminClientHostDeleteResponse>( + `/api/v1/admin/realms/${realm}/clients/${client}/hosts/${encoded}`, + { method: 'DELETE' } + ); +} + export async function loadAdminRealmEmailDomains( realmSlug: string ): Promise<AdminRealmEmailDomain[]> { diff --git a/app/admin/src/util/format.ts b/app/admin/src/util/format.ts @@ -6,6 +6,11 @@ export function formatTime(value: number | null | undefined) { }).format(new Date(value)); } +export function formatDate(value: number | null | undefined) { + if (!value) return 'Unknown'; + return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' }).format(new Date(value)); +} + export function scopeLabel(type: string) { if (type === 'global') return 'Canonical session'; if (type === 'realm') return 'Realm session'; diff --git a/app/admin/src/util/hosts.ts b/app/admin/src/util/hosts.ts @@ -0,0 +1,39 @@ +export function normalizeHostValue(raw: string) { + return raw.trim().toLowerCase(); +} + +export function hostFormatError(raw: string): string | null { + const value = raw.trim(); + const host = normalizeHostValue(value); + + if (!host) return 'Hostname is required.'; + if (/\s/.test(value)) return 'Hostname must not contain spaces.'; + if (host.includes('://') || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) { + return 'Hostname must not include a scheme such as https://.'; + } + if (host.includes('@')) return 'Hostname must not include @.'; + if (host.includes('/')) return 'Hostname must not include a path.'; + if (host.includes('*')) return 'Wildcard hostnames are not supported.'; + if (host.startsWith('[')) { + if (!host.endsWith(']')) return 'Enter a valid IPv6 hostname.'; + } else if (host.includes(':')) { + return 'Hostname must not include a port.'; + } + if (host.length > 253) return 'Hostname must be 253 characters or fewer.'; + if (host.startsWith('.') || host.endsWith('.')) { + return 'Hostname must not start or end with a dot.'; + } + + if (!host.startsWith('[')) { + const labels = host.split('.'); + if (labels.length < 2) return 'Enter a complete hostname such as login.acme.test.'; + for (const label of labels) { + if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) { + return 'Hostname labels must use lowercase letters, numbers and hyphens.'; + } + if (label.length > 63) return 'Each hostname label must be 63 characters or fewer.'; + } + } + + return null; +} diff --git a/server/src/controller/admin/client-hosts.js b/server/src/controller/admin/client-hosts.js @@ -0,0 +1,83 @@ +import { app } from '../../app.js'; +import { authenticateAdminRequest } from '../../lib/admin-auth.js'; +import { + addAdminClientHost, + deleteAdminClientHost, + listAdminClientHosts, +} from '../../lib/admin-client-hosts.js'; +import { normalizeReservedHosts } from '../../lib/admin-realm-hosts.js'; +import { HttpError } from '../../lib/http/http-error.js'; +import { isSystemAdmin } from '../../lib/policy.js'; + +const reservedHosts = normalizeReservedHosts(app.config); + +function assertBody(body) { + if (body === null || typeof body !== 'object' || Array.isArray(body)) { + throw new HttpError(400, 'invalid_request', 'Request body must be a JSON object'); + } + for (const field of Object.keys(body)) { + if (field !== 'host') { + throw new HttpError(400, 'invalid_request', `Unknown field: ${field}`); + } + } +} + +export default [ + { + method: 'get', + path: '/api/v1/admin/realms/:realm/clients/:clientId/hosts', + name: 'admin.client-hosts.list', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const hosts = await listAdminClientHosts({ + systemDb: auth.systemDb, + realm: auth.realm, + clientId: req.params.clientId, + }); + + return new app.HttpOk({ hosts }, { 'cache-control': 'no-store' }); + }, + }, + { + method: 'post', + path: '/api/v1/admin/realms/:realm/clients/:clientId/hosts', + name: 'admin.client-hosts.create', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const body = req.body || {}; + assertBody(body); + const host = await addAdminClientHost({ + systemDb: auth.systemDb, + realm: auth.realm, + clientId: req.params.clientId, + host: body.host, + isSystemAdmin: isSystemAdmin(auth.user), + reservedHosts, + }); + + return new app.HttpOk({ ok: true, host }, { 'cache-control': 'no-store' }); + }, + }, + { + method: 'delete', + path: '/api/v1/admin/realms/:realm/clients/:clientId/hosts/:host', + name: 'admin.client-hosts.delete', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const result = await deleteAdminClientHost({ + systemDb: auth.systemDb, + realm: auth.realm, + clientId: req.params.clientId, + host: req.params.host, + }); + + return new app.HttpOk({ ok: true, ...result }, { 'cache-control': 'no-store' }); + }, + }, +]; diff --git a/server/src/lib/admin-client-hosts.js b/server/src/lib/admin-client-hosts.js @@ -0,0 +1,116 @@ +import { HttpError } from './http/http-error.js'; +import { + addOidcClientHost, + findClientRealm, + findOidcClientHost, + findRealmHost, + listOidcClientHosts, + normalizeHost, + removeOidcClientHost, + validateRealmHostname, +} from './realm.js'; +import { isSystemClient } from './oidc/clients.js'; +import { normalizeReservedHosts } from './admin-realm-hosts.js'; +import { destroyClientHostSessions } from './session.js'; + +function invalidRequest(message) { + return new HttpError(400, 'invalid_request', message); +} + +async function assertClientUsable(clientId, realm) { + if (isSystemClient(clientId)) { + throw new HttpError(400, 'reserved_client_id', 'This client_id is reserved'); + } + const mapping = await findClientRealm(clientId); + if (!mapping || mapping.realm_id !== realm.id) { + throw new HttpError(404, 'client_not_found', 'Client is not available in this realm.'); + } +} + +export async function listAdminClientHosts({ systemDb, realm, clientId }) { + await assertClientUsable(clientId, realm); + const rows = await listOidcClientHosts(systemDb, clientId); + return rows.map((row) => ({ host: row.host, created_at: row.created_at })); +} + +export async function addAdminClientHost({ + systemDb, + realm, + clientId, + host, + isSystemAdmin = false, + reservedHosts, +}) { + await assertClientUsable(clientId, realm); + const normalized = validateRealmHostname(host); + + if (reservedHosts && reservedHosts.has(normalized)) { + throw new HttpError( + 409, + 'host_reserved', + 'This hostname is reserved for the authentication service.' + ); + } + + const clientHost = await findOidcClientHost(normalized); + if (clientHost) { + if (clientHost.client_id === clientId) { + throw new HttpError( + 409, + 'host_in_use', + 'This hostname is already assigned to this client.' + ); + } + throw new HttpError( + 409, + 'host_in_use', + 'This hostname is already assigned to a client application.' + ); + } + + const existing = await findRealmHost(normalized); + if (existing) { + if (existing.id === realm.id) { + throw new HttpError( + 409, + 'host_in_use', + 'This hostname is already assigned to this realm.' + ); + } + throw new HttpError( + 409, + 'host_in_use', + isSystemAdmin + ? `This hostname is already assigned to ${existing.slug}.` + : 'This hostname is already assigned to another realm.' + ); + } + + const createdAt = Date.now(); + try { + await addOidcClientHost(clientId, normalized); + } catch { + throw new HttpError(409, 'host_in_use', 'This hostname is already assigned.'); + } + + return { host: normalized, created_at: createdAt }; +} + +export async function deleteAdminClientHost({ systemDb, realm, clientId, host }) { + await assertClientUsable(clientId, realm); + const normalized = normalizeHost(host); + if (!normalized) throw invalidRequest('host is required'); + + const removed = await removeOidcClientHost(systemDb, clientId, normalized); + if (!removed) { + throw new HttpError(404, 'host_not_found', 'Host is not assigned to this client.'); + } + + await destroyClientHostSessions(systemDb, { + realmId: realm.id, + clientId, + host: normalized, + }); + + return { removed: true, host: normalized }; +} diff --git a/server/src/lib/realm.js b/server/src/lib/realm.js @@ -460,6 +460,27 @@ export async function findRealmHost(host) { ); } +export async function listOidcClientHosts(systemDb, clientId) { + if (!systemDb) throw new Error('realm registry is not initialized'); + return systemDb.all( + `SELECT host, created_at FROM oidc_client_hosts + WHERE client_id = {clientId} + ORDER BY created_at DESC, host ASC`, + { clientId } + ); +} + +export async function removeOidcClientHost(systemDb, clientId, host) { + if (!systemDb) throw new Error('realm registry is not initialized'); + const normalized = normalizeHost(host); + if (!normalized) return false; + const result = await systemDb.run( + 'DELETE FROM oidc_client_hosts WHERE host = {host} AND client_id = {clientId}', + { host: normalized, clientId } + ); + return result.changes > 0; +} + 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 @@ -574,6 +574,24 @@ export async function destroySessionById(systemDb, sessionId, now = Date.now()) }); } +export async function destroyClientHostSessions( + systemDb, + { realmId, clientId, host, now = Date.now() } +) { + return systemDb.transaction(async (tx) => { + const sessions = await tx.all( + `SELECT id, group_id FROM sessions + WHERE scope_type = 'client' AND realm_id = {realmId} + AND client_id = {clientId} AND scope_host = {host}`, + { realmId, clientId, host } + ); + for (const session of sessions) { + await removeSession(tx, session, now); + } + return { destroyed: sessions.length }; + }); +} + 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 @@ -4830,6 +4830,232 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { } }); + await t.test('admin client host management', async () => { + const systemAdmin = await adminToken(); + const acmeAdmin = await adminToken('it@acme.test'); + const globexAdmin = await adminToken('contractor@personal.test'); + const added = []; + + const hostPath = (host) => + `/api/v1/admin/realms/acme/clients/internal-app/hosts${ + host ? `/${encodeURIComponent(host)}` : '' + }`; + const cleanupHost = async (host) => { + await adminRequest(systemAdmin, { method: 'DELETE', path: hostPath(host) }); + }; + const sessionCount = () => + withSystemDatabase(env, (database) => + database + .prepare( + 'SELECT COUNT(*) AS c FROM sessions WHERE scope_host = ? AND client_id = ?' + ) + .get('portal.internal.acme.test', 'internal-app').c + ); + + try { + const list = await adminRequest(systemAdmin, { path: hostPath() }); + assert.equal(list.status, 200); + assert.ok(Array.isArray(list.json.hosts)); + const seeded = list.json.hosts.find((entry) => entry.host === 'app.acme.localhost'); + assert.ok(seeded, 'seeded app.acme.localhost present'); + assert.equal(typeof seeded.created_at, 'number'); + + const crossRealmList = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/globex/clients/internal-app/hosts', + }); + assert.equal(crossRealmList.status, 403); + assert.equal(crossRealmList.json.error.code, 'forbidden'); + + const foreignList = await adminRequest(globexAdmin, { + path: '/api/v1/admin/realms/acme/clients/internal-app/hosts', + }); + assert.equal(foreignList.status, 403); + + const unknownRealm = await adminRequest(systemAdmin, { + path: '/api/v1/admin/realms/does-not-exist/clients/internal-app/hosts', + }); + assert.equal(unknownRealm.status, 404); + + const unknownClient = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/clients/does-not-exist/hosts', + }); + assert.equal(unknownClient.status, 404); + assert.equal(unknownClient.json.error.code, 'client_not_found'); + + const foreignClient = await adminRequest(systemAdmin, { + path: '/api/v1/admin/realms/acme/clients/globex-members-app/hosts', + }); + assert.equal(foreignClient.status, 404); + assert.equal(foreignClient.json.error.code, 'client_not_found'); + + const reservedClient = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/clients/admin/hosts', + }); + assert.equal(reservedClient.status, 400); + assert.equal(reservedClient.json.error.code, 'reserved_client_id'); + + const created = await adminRequest(acmeAdmin, { + method: 'POST', + path: hostPath(), + body: { host: ' Portal.Internal.Acme.test ' }, + }); + assert.equal(created.status, 200); + assert.equal(created.json.ok, true); + assert.equal(created.json.host.host, 'portal.internal.acme.test'); + assert.equal(typeof created.json.host.created_at, 'number'); + added.push('portal.internal.acme.test'); + + const listed = await adminRequest(acmeAdmin, { path: hostPath() }); + assert.ok(listed.json.hosts.some((entry) => entry.host === 'portal.internal.acme.test')); + + for (const host of [ + 'HTTPS://portal.internal.acme.test', + 'portal.internal.acme.test:8443', + 'portal.internal.acme.test/path', + '*.acme.test', + 'user@portal.internal.acme.test', + 'two words.test', + 'nodot', + 'trailing.dot.test.', + 'UPPER.acme.test!', + ]) { + const invalid = await adminRequest(acmeAdmin, { + method: 'POST', + path: hostPath(), + body: { host }, + }); + assert.equal(invalid.status, 400, `expected 400 for ${host}`); + assert.equal(invalid.json.error.code, 'invalid_request'); + } + + const emptyBody = await adminRequest(acmeAdmin, { + method: 'POST', + path: hostPath(), + body: {}, + }); + assert.equal(emptyBody.status, 400); + assert.equal(emptyBody.json.error.code, 'invalid_request'); + + const unknownField = await adminRequest(acmeAdmin, { + method: 'POST', + path: hostPath(), + body: { hostname: 'ok.acme.test' }, + }); + assert.equal(unknownField.status, 400); + assert.equal(unknownField.json.error.code, 'invalid_request'); + + const sameClient = await adminRequest(acmeAdmin, { + method: 'POST', + path: hostPath(), + body: { host: 'app.acme.localhost' }, + }); + assert.equal(sameClient.status, 409); + assert.equal(sameClient.json.error.code, 'host_in_use'); + assert.match(sameClient.json.error.message, /this client/i); + + const realmCollision = await adminRequest(acmeAdmin, { + method: 'POST', + path: hostPath(), + body: { host: 'acme.localhost' }, + }); + assert.equal(realmCollision.status, 409); + assert.equal(realmCollision.json.error.code, 'host_in_use'); + assert.match(realmCollision.json.error.message, /this realm/i); + + const reserved = await adminRequest(systemAdmin, { + method: 'POST', + path: hostPath(), + body: { host: 'identity.test' }, + }); + assert.equal(reserved.status, 409); + assert.equal(reserved.json.error.code, 'host_reserved'); + + withSystemDatabase(env, (database) => { + database + .prepare( + 'INSERT INTO oidc_client_hosts (host, client_id, created_at) VALUES (?, ?, ?)' + ) + .run('confidential.acme.test', 'confidential-app', Date.now()); + }); + const otherClient = await adminRequest(acmeAdmin, { + method: 'POST', + path: hostPath(), + body: { host: 'confidential.acme.test' }, + }); + assert.equal(otherClient.status, 409); + assert.equal(otherClient.json.error.code, 'host_in_use'); + assert.match(otherClient.json.error.message, /client application/i); + withSystemDatabase(env, (database) => { + database.prepare('DELETE FROM oidc_client_hosts WHERE host = ?').run('confidential.acme.test'); + }); + + withSystemDatabase(env, (database) => { + const realm = database.prepare("SELECT id FROM realms WHERE slug = 'acme'").get(); + database + .prepare( + 'INSERT INTO session_groups (id, host, active_session_id, created_at, last_seen_at) VALUES (?, ?, ?, ?, ?)' + ) + .run('ch-test-group', 'portal.internal.acme.test', 'ch-test-session', Date.now(), Date.now()); + database + .prepare( + `INSERT INTO sessions + (id, public_id, group_id, user_id, scope_type, scope_host, realm_id, client_id, + ttl, auth_time, created_at, expires_at, last_seen_at) + VALUES (?, ?, ?, ?, 'client', ?, ?, 'internal-app', ?, ?, ?, ?, ?)` + ) + .run( + 'ch-test-session', + 'ch-test-public', + 'ch-test-group', + 'ch-test-user', + 'portal.internal.acme.test', + realm.id, + 3600, + Date.now(), + Date.now(), + Date.now() + 3600000, + Date.now() + ); + }); + assert.equal(sessionCount(), 1, 'seeded client session present'); + + const removed = await adminRequest(acmeAdmin, { + method: 'DELETE', + path: hostPath('portal.internal.acme.test'), + }); + assert.equal(removed.status, 200); + assert.equal(removed.json.ok, true); + assert.equal(removed.json.removed, true); + assert.equal(removed.json.host, 'portal.internal.acme.test'); + assert.equal(sessionCount(), 0, 'client sessions on the removed host are terminated'); + const groupGone = withSystemDatabase( + env, + (database) => + database.prepare('SELECT COUNT(*) AS c FROM session_groups WHERE id = ?').get('ch-test-group').c + ); + assert.equal(groupGone, 0, 'empty session group is removed'); + const index = added.indexOf('portal.internal.acme.test'); + if (index >= 0) added.splice(index, 1); + + const again = await adminRequest(acmeAdmin, { + method: 'DELETE', + path: hostPath('portal.internal.acme.test'), + }); + assert.equal(again.status, 404); + assert.equal(again.json.error.code, 'host_not_found'); + + const wrongRealmRemove = await adminRequest(acmeAdmin, { + method: 'DELETE', + path: '/api/v1/admin/realms/globex/clients/internal-app/hosts/app.acme.localhost', + }); + assert.equal(wrongRealmRemove.status, 403); + } finally { + for (const host of added) { + await cleanupHost(host); + } + } + }); + await t.test('admin realm email domain management', async () => { const systemAdmin = await adminToken(); const acmeAdmin = await adminToken('it@acme.test');