auth

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

commit af68471286432223bfa34759d301b241303146cc
parent 541335a99d5d5064d6e4fad2387dcc1979235cef
Author: finwo <finwo@pm.me>
Date:   Wed,  4 Nov 2026 00:38:40 +0100

Added system branding management

Diffstat:
Aapp/admin/src/component/settings-target-selector.tsx | 44++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/main.ts | 3+++
Mapp/admin/src/screen/admin.tsx | 31++++++++++++++++++++++++-------
Mapp/admin/src/screen/settings.tsx | 33+++++++++++++++++++++++++--------
Aapp/admin/src/screen/system-settings.tsx | 253+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/util/api.ts | 11+++++++++++
Mapp/admin/src/util/auth.ts | 22++++++++++++++++++++++
Aserver/migrations/sqlite/system/008_system_settings.sql | 14++++++++++++++
Aserver/src/controller/admin/system-settings.js | 44++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/controller/oidc.js | 3+++
Aserver/src/lib/system-settings.js | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/test/http.test.js | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/test/system-settings.test.js | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 792 insertions(+), 15 deletions(-)

diff --git a/app/admin/src/component/settings-target-selector.tsx b/app/admin/src/component/settings-target-selector.tsx @@ -0,0 +1,44 @@ +import m from 'mithril'; +import { SelectMenu, type SelectMenuOption } from '@component/select-menu'; +import type { AdminRealm } from '../util/api'; + +interface SettingsTargetSelectorAttrs { + realms: AdminRealm[] | null; + selectedSystem: boolean; + selectedRealm: AdminRealm | null; + onchange: (target: string) => void; +} + +export const SettingsTargetSelector: m.Component<SettingsTargetSelectorAttrs> = { + view({ attrs }) { + const { realms, selectedSystem, selectedRealm } = attrs; + + if (!realms || realms.length === 0) { + if (selectedSystem) { + return <span class="realm-current">System branding</span>; + } + if (selectedRealm) { + return <span class="realm-current">{selectedRealm.display_name}</span>; + } + return null; + } + + const options: SelectMenuOption[] = [ + { value: 'system', label: 'System branding' }, + ...realms.map((realm) => ({ value: realm.slug, label: realm.display_name })), + ]; + + return ( + <div class="realm-select"> + <span>Settings</span> + <SelectMenu + autoWidth + ariaLabel="Settings" + value={selectedSystem ? 'system' : selectedRealm?.slug || ''} + options={options} + onchange={attrs.onchange} + /> + </div> + ); + }, +}; diff --git a/app/admin/src/main.ts b/app/admin/src/main.ts @@ -46,6 +46,9 @@ const routes: m.RouteDefs = { '/settings/:realm': { render: () => m(Admin, {}), }, + '/system-settings': { + render: () => m(Admin, {}), + }, '/callback': { render: () => m(AdminCallback, {}), }, diff --git a/app/admin/src/screen/admin.tsx b/app/admin/src/screen/admin.tsx @@ -26,6 +26,7 @@ import { GlobalUserPage } from './global-user'; import { UserPage } from './user'; import { UsersPage } from './users'; import { SettingsPage } from './settings'; +import { SystemSettingsPage } from './system-settings'; function currentPath() { return (m.route.get() || '/').split('?')[0]; @@ -245,7 +246,9 @@ export const Admin: m.Component = { const clients = path === '/clients' || path.startsWith('/clients/'); const sessions = path === '/sessions' || path.startsWith('/sessions/'); const users = path === '/users' || path.startsWith('/users/'); - const settings = path === '/settings' || path.startsWith('/settings/'); + const systemSettings = path === '/system-settings'; + const realmSettings = path === '/settings' || path.startsWith('/settings/'); + const settings = systemSettings || realmSettings; const title = clients ? path.includes('/edit/') ? 'Edit client | Administration' @@ -256,9 +259,11 @@ export const Admin: m.Component = { ? userDetailPath() || globalUserDetailPath() ? 'User | Administration' : 'Users | Administration' - : settings - ? 'Realm settings | Administration' - : 'Administration'; + : systemSettings + ? 'System settings | Administration' + : settings + ? 'Realm settings | Administration' + : 'Administration'; document.title = title; }, @@ -280,7 +285,9 @@ export const Admin: m.Component = { const sessions = path === '/sessions' || path.startsWith('/sessions/'); const clients = path === '/clients' || path.startsWith('/clients/'); const users = path === '/users' || path.startsWith('/users/'); - const settings = path === '/settings' || path.startsWith('/settings/'); + const systemSettings = path === '/system-settings'; + const realmSettings = path === '/settings' || path.startsWith('/settings/'); + const settings = systemSettings || realmSettings; const realmSlug = sessionsRealm(); const clientRealmSlug = clientsRealm(); const userRealmSlug = usersRealm(); @@ -297,7 +304,11 @@ export const Admin: m.Component = { ? `/clients/${encodeURIComponent(firstRealm)}` : '/clients'; const usersHref = firstRealm ? `/users/${encodeURIComponent(firstRealm)}` : '/users'; - const settingsHref = firstRealm ? `/settings/${encodeURIComponent(firstRealm)}` : '/settings'; + const settingsHref = this.systemAdmin + ? '/system-settings' + : firstRealm + ? `/settings/${encodeURIComponent(firstRealm)}` + : '/settings'; const navItems: NavItem[] = [ { @@ -453,11 +464,17 @@ export const Admin: m.Component = { isSystemAdmin={Boolean(this.systemAdmin)} isGlobal={isGlobalUsers} /> - ) : settings ? ( + ) : systemSettings ? ( + <SystemSettingsPage + realms={this.realms} + onAuthExpired={() => this.authExpired()} + /> + ) : realmSettings ? ( <SettingsPage realmSlug={settingsRealmSlug} realms={this.realms} realmsError={this.realmsError} + isSystemAdmin={Boolean(this.systemAdmin)} onAuthExpired={() => this.authExpired()} onRealmsChanged={() => this.reloadRealms()} /> diff --git a/app/admin/src/screen/settings.tsx b/app/admin/src/screen/settings.tsx @@ -8,6 +8,7 @@ import { validateBrandingFields, } from '@util/branding'; import { RealmSelector } from '../component/realm-selector'; +import { SettingsTargetSelector } from '../component/settings-target-selector'; import { loadAdminRealmSettings, updateAdminRealmSettings } from '../util/auth'; import type { AdminRealm, AdminRealmSettings } from '../util/api'; @@ -15,6 +16,7 @@ interface SettingsAttrs { realmSlug: string | null; realms: AdminRealm[] | null; realmsError: Error | null; + isSystemAdmin: boolean; onAuthExpired: () => void; onRealmsChanged: () => Promise<void>; } @@ -210,7 +212,7 @@ export const SettingsPage: m.Component<SettingsAttrs> = { }, view(this: any) { - const { realms, realmsError, realmSlug } = this.attrs; + const { realms, realmsError, realmSlug, isSystemAdmin } = this.attrs; const selected = realms?.find((realm) => realm.slug === realmSlug) || realms?.[0] || null; const previewLogo = logoUrlError(this.form.logo_url) ? '' : this.form.logo_url.trim(); @@ -219,13 +221,28 @@ export const SettingsPage: m.Component<SettingsAttrs> = { return ( <div> <PageHeader row title="Realm settings" subtitle="Realm name, branding, and login behavior."> - <RealmSelector - realms={realms} - selected={selected} - onchange={(slug: string) => { - m.route.set(`/settings/${encodeURIComponent(slug)}`); - }} - /> + {isSystemAdmin ? ( + <SettingsTargetSelector + realms={realms} + selectedSystem={false} + selectedRealm={selected} + onchange={(target: string) => { + if (target === 'system') { + m.route.set('/system-settings'); + return; + } + m.route.set(`/settings/${encodeURIComponent(target)}`); + }} + /> + ) : ( + <RealmSelector + realms={realms} + selected={selected} + onchange={(slug: string) => { + m.route.set(`/settings/${encodeURIComponent(slug)}`); + }} + /> + )} </PageHeader> {realmsError ? ( diff --git a/app/admin/src/screen/system-settings.tsx b/app/admin/src/screen/system-settings.tsx @@ -0,0 +1,253 @@ +import m from 'mithril'; +import { PageHeader } from '@component/page-header'; +import { SettingsTargetSelector } from '../component/settings-target-selector'; +import { + brandingFromInput, + brandingValidationErrorField, + logoUrlError, + normalizePreviewColor, + validateBrandingFields, +} from '@util/branding'; +import { loadAdminSystemSettings, updateAdminSystemSettings } from '../util/auth'; +import type { AdminRealm, AdminSystemSettings } from '../util/api'; + +interface SystemSettingsAttrs { + realms: AdminRealm[] | null; + onAuthExpired: () => void; +} + +interface SystemSettingsFormValue { + logo_url: string; + primary_color: string; +} + +interface SystemSettingsValidation { + message: string; + field: 'logo_url' | 'primary_color'; +} + +function formFromSettings(settings: AdminSystemSettings): SystemSettingsFormValue { + return { + logo_url: settings.logo_url || '', + primary_color: settings.primary_color || '', + }; +} + +function fieldFromError(message: string | null | undefined): SystemSettingsValidation['field'] | null { + return brandingValidationErrorField(message); +} + +export const SystemSettingsPage: m.Component<SystemSettingsAttrs> = { + attrs: null as SystemSettingsAttrs | null, + loading: false, + loaded: false, + settings: null as AdminSystemSettings | null, + form: { + logo_url: '', + primary_color: '', + } as SystemSettingsFormValue, + error: null as Error | null, + formError: null as Error | string | null, + invalidField: null as SystemSettingsValidation['field'] | null, + notice: null as string | null, + pending: false, + + oninit(this: any, vnode: m.Vnode<SystemSettingsAttrs>) { + this.attrs = vnode.attrs; + this.load(); + }, + + async load(this: any) { + this.loading = true; + this.loaded = false; + this.error = null; + this.formError = null; + this.notice = null; + this.settings = null; + this.invalidField = null; + this.form = { + logo_url: '', + primary_color: '', + }; + m.redraw(); + + try { + const settings = await loadAdminSystemSettings(); + this.settings = settings; + this.form = formFromSettings(settings); + this.loaded = true; + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs?.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + this.loading = false; + m.redraw(); + } + }, + + async submit(this: any) { + const validationError = validateBrandingFields(this.form); + if (validationError) { + this.formError = validationError.message; + this.invalidField = validationError.field; + this.notice = null; + m.redraw(); + return; + } + + this.pending = true; + this.formError = null; + this.invalidField = null; + this.notice = null; + m.redraw(); + + try { + const settings = await updateAdminSystemSettings(brandingFromInput(this.form)); + this.settings = settings; + this.form = formFromSettings(settings); + this.notice = 'System branding saved.'; + } catch (e: any) { + if (e?.status === 401 || (e?.status === 400 && e?.code !== 'invalid_request')) { + this.attrs?.onAuthExpired(); + return; + } + this.formError = e as Error; + this.invalidField = fieldFromError(e?.message); + } finally { + this.pending = false; + m.redraw(); + } + }, + + view(this: any) { + const realms = this.attrs?.realms || null; + const previewLogo = logoUrlError(this.form.logo_url) ? '' : this.form.logo_url.trim(); + const previewColor = normalizePreviewColor(this.form.primary_color); + + return ( + <div> + <PageHeader + row + title="System branding" + subtitle="Global logo and primary color for the identity provider." + > + <SettingsTargetSelector + realms={realms} + selectedSystem + selectedRealm={null} + onchange={(target: string) => { + if (target === 'system') return; + m.route.set(`/settings/${encodeURIComponent(target)}`); + }} + /> + </PageHeader> + + {this.error ? ( + <div class="alert" role="alert"> + <p>{this.error.message}</p> + <button class="button-secondary" type="button" onclick={() => this.load()}> + Try again + </button> + </div> + ) : null} + + {this.notice ? ( + <div class="notice" role="status"> + {this.notice} + </div> + ) : null} + + {this.loading ? ( + <div class="panel" aria-busy="true"> + <div class="skeleton skeleton-title"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + </div> + ) : this.loaded ? ( + <section class="panel"> + <h2>Global branding</h2> + <p class="note"> + Used as the system fallback. Realm branding overrides these values, and client + branding overrides realm branding. + </p> + <div class="settings-form"> + {this.formError ? ( + <div class="alert" role="alert"> + {typeof this.formError === 'string' ? this.formError : this.formError.message} + </div> + ) : null} + + <div class="field-grid"> + <div class="form-field"> + <span class="field-label">Logo URL</span> + <input + class="field-control" + type="url" + value={this.form.logo_url} + placeholder="https://app.example.test/logo.svg" + maxlength="2048" + disabled={this.pending} + aria-invalid={this.invalidField === 'logo_url' ? 'true' : null} + oninput={(event: Event) => { + this.form.logo_url = (event.target as HTMLInputElement).value; + this.invalidField = null; + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Primary color</span> + <input + class="field-control" + value={this.form.primary_color} + placeholder="#25a" + maxlength="7" + spellcheck="false" + disabled={this.pending} + aria-invalid={this.invalidField === 'primary_color' ? 'true' : null} + oninput={(event: Event) => { + this.form.primary_color = (event.target as HTMLInputElement).value; + this.invalidField = null; + }} + /> + </div> + </div> + + <div class="branding-preview" aria-hidden="true"> + <span class={`branding-logo-preview${previewLogo ? '' : ' is-empty'}`}> + {previewLogo ? ( + <img + src={previewLogo} + alt="" + onerror={(event: Event) => { + (event.target as HTMLImageElement).style.visibility = 'hidden'; + }} + /> + ) : null} + </span> + <span + class={`branding-color-preview${previewColor ? '' : ' is-empty'}`} + style={previewColor ? { background: previewColor } : {}} + ></span> + </div> + + <div class="settings-actions"> + <button + class="button" + type="button" + disabled={this.pending} + onclick={() => this.submit()} + > + {this.pending ? 'Saving' : 'Save changes'} + </button> + </div> + </div> + </section> + ) : null} + </div> + ); + }, +}; diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -27,6 +27,17 @@ export interface AdminRealmSettingsInput { primary_color?: string | null; } +export interface AdminSystemSettings { + logo_url: string | null; + primary_color: string | null; + updated_at: number; +} + +export interface AdminSystemSettingsInput { + logo_url?: string | null; + primary_color?: string | null; +} + export interface AdminRole { slug: string; name: string; diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts @@ -17,6 +17,8 @@ import { type AdminRealmSettingsInput, type AdminRealmUser, type AdminRole, + type AdminSystemSettings, + type AdminSystemSettingsInput, type AdminSession, type AdminUserBan, type AdminUserDetail, @@ -305,3 +307,23 @@ export async function updateAdminRealmSettings( ); return response.settings; } + +export async function loadAdminSystemSettings(): Promise<AdminSystemSettings> { + const response = await adminJson<{ settings: AdminSystemSettings }>( + '/api/v1/admin/system/settings' + ); + return response.settings; +} + +export async function updateAdminSystemSettings( + input: AdminSystemSettingsInput +): Promise<AdminSystemSettings> { + const response = await adminJson<{ ok: boolean; settings: AdminSystemSettings }>( + '/api/v1/admin/system/settings', + { + method: 'PATCH', + body: JSON.stringify(input), + } + ); + return response.settings; +} diff --git a/server/migrations/sqlite/system/008_system_settings.sql b/server/migrations/sqlite/system/008_system_settings.sql @@ -0,0 +1,14 @@ +CREATE TABLE system_settings ( + id INTEGER PRIMARY KEY CHECK (id = 1), + branding TEXT NOT NULL DEFAULT '{}', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); + +INSERT INTO system_settings (id, branding, created_at, updated_at) +VALUES ( + 1, + '{}', + CAST(strftime('%s', 'now') AS INTEGER) * 1000, + CAST(strftime('%s', 'now') AS INTEGER) * 1000 +); diff --git a/server/src/controller/admin/system-settings.js b/server/src/controller/admin/system-settings.js @@ -0,0 +1,44 @@ +import { app } from '../../app.js'; +import { authenticateAdminSession } from '../../lib/admin-auth.js'; +import { HttpError } from '../../lib/http/http-error.js'; +import { isSystemAdmin } from '../../lib/policy.js'; +import { + getAdminSystemSettings, + updateAdminSystemSettings, +} from '../../lib/system-settings.js'; + +function requireSystemAdmin(user) { + if (!isSystemAdmin(user)) { + throw new HttpError(403, 'forbidden', 'System administrator access is required'); + } +} + +export default [ + { + method: 'get', + path: '/api/v1/admin/system/settings', + name: 'admin.system-settings.get', + async handler(req) { + const auth = await authenticateAdminSession(req); + requireSystemAdmin(auth.user); + const settings = await getAdminSystemSettings(auth.systemDb); + + return new app.HttpOk({ settings }, { 'cache-control': 'no-store' }); + }, + }, + { + method: 'patch', + path: '/api/v1/admin/system/settings', + name: 'admin.system-settings.update', + async handler(req) { + const auth = await authenticateAdminSession(req); + requireSystemAdmin(auth.user); + const settings = await updateAdminSystemSettings({ + systemDb: auth.systemDb, + body: req.body || {}, + }); + + return new app.HttpOk({ ok: true, settings }, { 'cache-control': 'no-store' }); + }, + }, +]; diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js @@ -40,6 +40,7 @@ import { import { canUseClient } from '../lib/policy.js'; import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../lib/realm.js'; import { issueRefreshToken, rotateRefreshToken } from '../lib/refresh-tokens.js'; +import { getSystemBranding } from '../lib/system-settings.js'; import { authenticateRequest, bindSessionRealm, @@ -117,9 +118,11 @@ function systemCallbacks(context, client) { } async function discovery(context, client) { + const systemBranding = await getSystemBranding(getSystemDatabase()); const realm = context.realm ? await realmMetadata(context.realm) : null; const urls = endpointUrls(context); const branding = { + ...systemBranding, ...(realm?.branding || {}), ...normalizeBrandingObject(client.branding), }; diff --git a/server/src/lib/system-settings.js b/server/src/lib/system-settings.js @@ -0,0 +1,103 @@ +import { + applyBrandingPatch, + hasBrandingPatch, + normalizeBrandingObject, + normalizeBrandingPatch, + serializeBranding, +} from './admin-branding.js'; +import { HttpError } from './http/http-error.js'; + +const ALLOWED_FIELDS = new Set(['logo_url', 'primary_color']); + +function invalidRequest(message) { + return new HttpError(400, 'invalid_request', message); +} + +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function serializeSettings(row) { + return { + ...serializeBranding(row.branding), + updated_at: row.updated_at, + }; +} + +export function normalizeSystemSettingsPatch(body) { + if (!isPlainObject(body)) { + throw invalidRequest('Request body must be a JSON object'); + } + + for (const field of Object.keys(body)) { + if (!ALLOWED_FIELDS.has(field)) { + throw invalidRequest(`Unknown field: ${field}`); + } + } + + if (Object.keys(body).length === 0) { + throw invalidRequest('At least one setting must be provided'); + } + + return normalizeBrandingPatch(body); +} + +async function loadSystemSettingsRow(systemDb) { + const row = await systemDb.get( + `SELECT branding, created_at, updated_at + FROM system_settings + WHERE id = 1` + ); + if (row) return row; + + const now = Date.now(); + await systemDb.run( + `INSERT INTO system_settings + (id, branding, created_at, updated_at) + VALUES + (1, '{}', {createdAt}, {updatedAt})`, + { createdAt: now, updatedAt: now } + ); + + const created = await systemDb.get( + `SELECT branding, created_at, updated_at + FROM system_settings + WHERE id = 1` + ); + if (!created) { + throw new HttpError(500, 'internal_error', 'System settings are unavailable'); + } + return created; +} + +export async function getSystemBranding(systemDb) { + const row = await loadSystemSettingsRow(systemDb); + return normalizeBrandingObject(row.branding); +} + +export async function getAdminSystemSettings(systemDb) { + const row = await loadSystemSettingsRow(systemDb); + return serializeSettings(row); +} + +export async function updateAdminSystemSettings({ systemDb, body, now = Date.now() }) { + const input = normalizeSystemSettingsPatch(body); + + return systemDb.transaction(async (tx) => { + const current = await loadSystemSettingsRow(tx); + const branding = hasBrandingPatch(input) + ? applyBrandingPatch(current.branding, input) + : current.branding; + + await tx.run( + `UPDATE system_settings + SET branding = {branding}, + updated_at = {now} + WHERE id = 1`, + { branding, now } + ); + + const updated = await loadSystemSettingsRow(tx); + return serializeSettings(updated); + }); +} diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -4286,6 +4286,140 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { } } }); + + await t.test('system branding updates Admin settings and discovery precedence', async () => { + const systemAdmin = await adminToken(); + const acmeAdmin = await adminToken('it@acme.test'); + const readSystemBranding = () => + withSystemDatabase(env, (database) => + database.prepare('SELECT branding FROM system_settings WHERE id = 1').get().branding + ); + const writeSystemBranding = (value) => + withSystemDatabase(env, (database) => { + database.prepare('UPDATE system_settings SET branding = ? WHERE id = 1').run(value); + }); + const readRealmBranding = () => + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT branding FROM realm_settings WHERE id = 1').get().branding + ); + const writeRealmBranding = (value) => + withRealmDatabase(env, 'acme', (database) => { + database.prepare('UPDATE realm_settings SET branding = ? WHERE id = 1').run(value); + }); + const readClientBranding = () => + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT branding FROM oidc_clients WHERE client_id = ?').get('internal-app') + .branding + ); + const writeClientBranding = (value) => + withRealmDatabase(env, 'acme', (database) => { + database + .prepare('UPDATE oidc_clients SET branding = ? WHERE client_id = ?') + .run(value, 'internal-app'); + }); + + const originalSystemBranding = readSystemBranding(); + const originalRealmBranding = readRealmBranding(); + const originalClientBranding = readClientBranding(); + + try { + const initial = await adminRequest(systemAdmin, { + path: '/api/v1/admin/system/settings', + }); + assert.equal(initial.status, 200); + assert.equal(initial.json.settings.logo_url, null); + assert.equal(initial.json.settings.primary_color, null); + + const unauthenticated = await identity({ + path: '/api/v1/admin/system/settings', + }); + assert.equal(unauthenticated.status, 401); + assert.equal(unauthenticated.json.error.code, 'invalid_token'); + + const forbidden = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: '/api/v1/admin/system/settings', + body: { primary_color: '#123456' }, + }); + assert.equal(forbidden.status, 403); + assert.equal(forbidden.json.error.code, 'forbidden'); + + const realmHost = await request(port, { + host: `acme.localhost:${port}`, + bearer: systemAdmin.access_token, + path: '/api/v1/admin/system/settings', + }); + assert.equal(realmHost.status, 404); + + for (const body of [ + {}, + { display_name: 'Auth' }, + { primary_color: 'red' }, + { logo_url: 'http://system.test/logo.svg' }, + ]) { + const invalid = await adminRequest(systemAdmin, { + method: 'PATCH', + path: '/api/v1/admin/system/settings', + body, + }); + assert.equal(invalid.status, 400); + assert.equal(invalid.json.error.code, 'invalid_request'); + } + + const updated = await adminRequest(systemAdmin, { + method: 'PATCH', + path: '/api/v1/admin/system/settings', + body: { primary_color: '#123456' }, + }); + assert.equal(updated.status, 200); + assert.equal(updated.json.ok, true); + assert.equal(updated.json.settings.primary_color, '#123456'); + + const logoUpdated = await adminRequest(systemAdmin, { + method: 'PATCH', + path: '/api/v1/admin/system/settings', + body: { logo_url: 'https://system.test/logo.svg' }, + }); + assert.equal(logoUpdated.status, 200); + assert.equal(logoUpdated.json.settings.logo_url, 'https://system.test/logo.svg'); + + const systemDiscovery = await identity({ + path: '/oidc/account/openid-configuration', + }); + assert.equal(systemDiscovery.status, 200); + assert.equal(systemDiscovery.json.branding.logo_url, 'https://system.test/logo.svg'); + assert.equal(systemDiscovery.json.branding.primary_color, '#123456'); + + writeRealmBranding(JSON.stringify({ primary_color: '#aabbcc' })); + const realmDiscovery = await acme({ + path: '/oidc/account/openid-configuration', + }); + assert.equal(realmDiscovery.status, 200); + assert.equal(realmDiscovery.json.branding.logo_url, 'https://system.test/logo.svg'); + assert.equal(realmDiscovery.json.branding.primary_color, '#aabbcc'); + + writeClientBranding(JSON.stringify({ primary_color: '#ff0000' })); + const clientDiscovery = await acme({ + path: '/oidc/internal-app/openid-configuration', + }); + assert.equal(clientDiscovery.status, 200); + assert.equal(clientDiscovery.json.branding.logo_url, 'https://system.test/logo.svg'); + assert.equal(clientDiscovery.json.branding.primary_color, '#ff0000'); + + const cleared = await adminRequest(systemAdmin, { + method: 'PATCH', + path: '/api/v1/admin/system/settings', + body: { logo_url: '', primary_color: null }, + }); + assert.equal(cleared.status, 200); + assert.equal(cleared.json.settings.logo_url, null); + assert.equal(cleared.json.settings.primary_color, null); + } finally { + writeSystemBranding(originalSystemBranding); + writeRealmBranding(originalRealmBranding); + writeClientBranding(originalClientBranding); + } + }); } finally { if (server) { server.kill('SIGTERM'); diff --git a/server/test/system-settings.test.js b/server/test/system-settings.test.js @@ -0,0 +1,112 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { + closeRealms, + getSystemDatabase, + initRealms, +} from '../src/lib/realm.js'; +import { + getAdminSystemSettings, + getSystemBranding, + updateAdminSystemSettings, +} from '../src/lib/system-settings.js'; + +async function withSystemDatabase(fn) { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-system-settings-')); + try { + await initRealms({ + database: { + dialect: 'sqlite', + path: path.join(dir, 'system.sqlite'), + realms: path.join(dir, 'realms'), + }, + }); + await fn(getSystemDatabase()); + } finally { + await closeRealms(); + await fs.rm(dir, { recursive: true, force: true }); + } +} + +test('system settings expose and persist global branding', async () => { + await withSystemDatabase(async (systemDb) => { + assert.deepEqual(await getSystemBranding(systemDb), {}); + + const initial = await getAdminSystemSettings(systemDb); + assert.equal(initial.logo_url, null); + assert.equal(initial.primary_color, null); + assert.equal(typeof initial.updated_at, 'number'); + + const updated = await updateAdminSystemSettings({ + systemDb, + body: { primary_color: '#25A' }, + }); + assert.equal(updated.primary_color, '#2255aa'); + assert.equal(updated.logo_url, null); + + assert.deepEqual(await getSystemBranding(systemDb), { primary_color: '#2255aa' }); + }); +}); + +test('system settings patch unknown branding keys and clear values', async () => { + await withSystemDatabase(async (systemDb) => { + await systemDb.run( + `UPDATE system_settings + SET branding = {branding} + WHERE id = 1`, + { + branding: JSON.stringify({ + primary_color: '#2255aa', + custom_asset: 'https://system.test/custom.png', + }), + } + ); + + const updated = await updateAdminSystemSettings({ + systemDb, + body: { logo_url: 'https://system.test/logo.svg' }, + }); + assert.equal(updated.primary_color, '#2255aa'); + assert.equal(updated.logo_url, 'https://system.test/logo.svg'); + + const row = await systemDb.get('SELECT branding FROM system_settings WHERE id = 1'); + assert.deepEqual(JSON.parse(row.branding), { + primary_color: '#2255aa', + custom_asset: 'https://system.test/custom.png', + logo_url: 'https://system.test/logo.svg', + }); + + const cleared = await updateAdminSystemSettings({ + systemDb, + body: { logo_url: '', primary_color: null }, + }); + assert.equal(cleared.logo_url, null); + assert.equal(cleared.primary_color, null); + assert.deepEqual(JSON.parse((await systemDb.get('SELECT branding FROM system_settings WHERE id = 1')).branding), { + custom_asset: 'https://system.test/custom.png', + }); + }); +}); + +test('system settings validate branding input', async () => { + await withSystemDatabase(async (systemDb) => { + for (const body of [ + {}, + { display_name: 'Auth' }, + { primary_color: 'red' }, + { logo_url: 'http://system.test/logo.svg' }, + ]) { + await assert.rejects( + () => updateAdminSystemSettings({ systemDb, body }), + (error) => { + assert.equal(error.status, 400); + assert.equal(error.code, 'invalid_request'); + return true; + } + ); + } + }); +});