auth

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

commit e9d7dfc04665127661e0eaa96dbb88bcf98bda48
parent 557b3f5ea573e8e88092b94cb62152dfd9e81b2e
Author: finwo <finwo@pm.me>
Date:   Fri, 20 Nov 2026 20:31:35 +0100

server: identity provider CRUD and provider-domain mapping (P2)

Diffstat:
Aserver/src/controller/admin/realm-providers.js | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/src/lib/admin-realm-providers.js | 465+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/test/http.test.js | 400+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 1006 insertions(+), 0 deletions(-)

diff --git a/server/src/controller/admin/realm-providers.js b/server/src/controller/admin/realm-providers.js @@ -0,0 +1,141 @@ +import { app } from '../../app.js'; +import { authenticateAdminRequest } from '../../lib/admin-auth.js'; +import { + connectAdminProviderDomain, + createAdminRealmProvider, + deleteAdminRealmProvider, + disconnectAdminProviderDomain, + getAdminRealmProvider, + listAdminRealmProviders, + normalizeCreateProviderInput, + normalizeUpdateProviderInput, + updateAdminRealmProvider, +} from '../../lib/admin-realm-providers.js'; +import { HttpError } from '../../lib/http/http-error.js'; + +const NO_STORE = { 'cache-control': 'no-store' }; + +function assertDomainBody(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 !== 'domain') { + throw new HttpError(400, 'invalid_request', `Unknown field: ${field}`); + } + } +} + +export default [ + { + method: 'get', + path: '/api/v1/admin/realms/:realm/providers', + name: 'admin.realm-providers.list', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const providers = await listAdminRealmProviders({ realmDb: auth.realmDb }); + + return new app.HttpOk({ providers }, NO_STORE); + }, + }, + { + method: 'post', + path: '/api/v1/admin/realms/:realm/providers', + name: 'admin.realm-providers.create', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const input = normalizeCreateProviderInput(req.body || {}); + const provider = await createAdminRealmProvider({ realmDb: auth.realmDb, input }); + + return new app.HttpOk({ ok: true, provider }, NO_STORE); + }, + }, + { + method: 'get', + path: '/api/v1/admin/realms/:realm/providers/:provider', + name: 'admin.realm-providers.get', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const provider = await getAdminRealmProvider({ realmDb: auth.realmDb, slug: req.params.provider }); + if (!provider) { + throw new HttpError(404, 'provider_not_found', 'Identity provider not found'); + } + + return new app.HttpOk({ provider }, NO_STORE); + }, + }, + { + method: 'patch', + path: '/api/v1/admin/realms/:realm/providers/:provider', + name: 'admin.realm-providers.update', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const input = normalizeUpdateProviderInput(req.body || {}); + const provider = await updateAdminRealmProvider({ + realmDb: auth.realmDb, + slug: req.params.provider, + input, + }); + + return new app.HttpOk({ ok: true, provider }, NO_STORE); + }, + }, + { + method: 'delete', + path: '/api/v1/admin/realms/:realm/providers/:provider', + name: 'admin.realm-providers.delete', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const result = await deleteAdminRealmProvider({ realmDb: auth.realmDb, slug: req.params.provider }); + + return new app.HttpOk({ ok: true, ...result }, NO_STORE); + }, + }, + { + method: 'post', + path: '/api/v1/admin/realms/:realm/providers/:provider/domains', + name: 'admin.realm-providers.connect-domain', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + assertDomainBody(req.body || {}); + const result = await connectAdminProviderDomain({ + systemDb: auth.systemDb, + realm: auth.realm, + realmDb: auth.realmDb, + slug: req.params.provider, + domain: req.body.domain, + }); + + return new app.HttpOk({ ok: true, ...result }, NO_STORE); + }, + }, + { + method: 'delete', + path: '/api/v1/admin/realms/:realm/providers/:provider/domains/:domain', + name: 'admin.realm-providers.disconnect-domain', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const result = await disconnectAdminProviderDomain({ + realmDb: auth.realmDb, + slug: req.params.provider, + domain: req.params.domain, + }); + + return new app.HttpOk({ ok: true, ...result }, NO_STORE); + }, + }, +]; diff --git a/server/src/lib/admin-realm-providers.js b/server/src/lib/admin-realm-providers.js @@ -0,0 +1,465 @@ +import crypto from 'node:crypto'; +import { normalizeScopes } from './admin-clients.js'; +import { HttpError } from './http/http-error.js'; +import { getRealmEmailDomain, validateRealmEmailDomain } from './realm.js'; + +const SLUG_MAX_LENGTH = 63; +const NAME_MAX_LENGTH = 120; +const CLIENT_ID_MAX_LENGTH = 255; +const SECRET_MAX_LENGTH = 255; +const ISSUER_MAX_LENGTH = 512; +const SLUG_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/; +const PRINTABLE_PATTERN = /^[\x21-\x7e]+$/; + +const PROVIDER_COLUMNS = + 'id, slug, display_name, issuer, client_id, client_secret, scopes, enabled, created_at, updated_at'; + +function invalidRequest(message) { + return new HttpError(400, 'invalid_request', message); +} + +function notFound(message = 'Identity provider not found', code = 'provider_not_found') { + return new HttpError(404, code, message); +} + +function conflict(message, code) { + return new HttpError(409, code, message); +} + +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function assertBody(body) { + if (!isPlainObject(body)) { + throw invalidRequest('Request body must be a JSON object'); + } +} + +function assertKnownFields(body, allowed) { + for (const field of Object.keys(body)) { + if (!allowed.has(field)) { + throw invalidRequest(`Unknown field: ${field}`); + } + } +} + +function validateSlug(value) { + if (typeof value !== 'string') { + throw invalidRequest('slug must be a string'); + } + const slug = value.trim().toLowerCase(); + if (!slug || slug.length > SLUG_MAX_LENGTH || !SLUG_PATTERN.test(slug)) { + throw invalidRequest( + 'slug must contain only lowercase letters, digits, and hyphens, and must start and end with a letter or digit' + ); + } + return slug; +} + +function validateDisplayName(value) { + if (typeof value !== 'string') { + throw invalidRequest('display_name must be a string'); + } + const name = value.trim(); + if (!name || name.length > NAME_MAX_LENGTH) { + throw invalidRequest(`display_name must be between 1 and ${NAME_MAX_LENGTH} characters`); + } + return name; +} + +function validateIssuer(value) { + if (typeof value !== 'string') { + throw invalidRequest('issuer must be a string'); + } + const issuer = value.trim(); + if (!issuer || issuer.length > ISSUER_MAX_LENGTH) { + throw invalidRequest(`issuer must be between 1 and ${ISSUER_MAX_LENGTH} characters`); + } + if (issuer.endsWith('/')) { + throw invalidRequest('issuer must not end with a slash'); + } + + let parsed; + try { + parsed = new URL(issuer); + } catch { + throw invalidRequest('issuer must be an absolute URL'); + } + if (parsed.protocol !== 'https:') { + throw invalidRequest('issuer must use https'); + } + if (parsed.username || parsed.password) { + throw invalidRequest('issuer must not contain credentials'); + } + if (parsed.search) { + throw invalidRequest('issuer must not contain a query'); + } + if (parsed.hash) { + throw invalidRequest('issuer must not contain a fragment'); + } + if (!parsed.hostname.includes('.')) { + throw invalidRequest('issuer must include a complete hostname such as https://idp.example.com'); + } + return issuer; +} + +function validateProviderClientId(value) { + if (typeof value !== 'string') { + throw invalidRequest('client_id must be a string'); + } + const clientId = value.trim(); + if (!clientId || clientId.length > CLIENT_ID_MAX_LENGTH) { + throw invalidRequest(`client_id must be between 1 and ${CLIENT_ID_MAX_LENGTH} characters`); + } + if (!PRINTABLE_PATTERN.test(clientId)) { + throw invalidRequest('client_id must contain only printable non-whitespace characters'); + } + return clientId; +} + +function validateSecret(value) { + if (typeof value !== 'string' || value.trim() === '') { + throw invalidRequest('client_secret must be a non-empty string'); + } + if (value.length > SECRET_MAX_LENGTH) { + throw invalidRequest(`client_secret must be ${SECRET_MAX_LENGTH} characters or fewer`); + } + return value; +} + +function validateEnabled(value) { + if (typeof value !== 'boolean') { + throw invalidRequest('enabled must be a boolean'); + } + return value; +} + +function normalizeEmailDomainKey(domain) { + return String(domain || '').trim().toLowerCase().replace(/\.$/, ''); +} + +export function normalizeCreateProviderInput(body) { + assertBody(body); + assertKnownFields( + body, + new Set([ + 'slug', + 'display_name', + 'issuer', + 'client_id', + 'client_secret', + 'scopes', + 'enabled', + ]) + ); + + if (!Object.hasOwn(body, 'display_name')) { + throw invalidRequest('display_name is required'); + } + if (!Object.hasOwn(body, 'issuer')) { + throw invalidRequest('issuer is required'); + } + if (!Object.hasOwn(body, 'client_id')) { + throw invalidRequest('client_id is required'); + } + if (body.client_secret !== undefined && body.client_secret !== null && typeof body.client_secret !== 'string') { + throw invalidRequest('client_secret must be a string'); + } + + return { + slug: validateSlug(body.slug), + displayName: validateDisplayName(body.display_name), + issuer: validateIssuer(body.issuer), + clientId: validateProviderClientId(body.client_id), + clientSecret: + body.client_secret === undefined || body.client_secret === null + ? null + : validateSecret(body.client_secret), + scopes: normalizeScopes(body.scopes), + enabled: validateEnabled(body.enabled === undefined ? true : body.enabled), + }; +} + +export function normalizeUpdateProviderInput(body) { + assertBody(body); + if (Object.hasOwn(body, 'slug')) { + throw invalidRequest('slug cannot be updated'); + } + assertKnownFields( + body, + new Set(['display_name', 'issuer', 'client_id', 'client_secret', 'scopes', 'enabled']) + ); + + const result = {}; + if (Object.hasOwn(body, 'display_name')) { + result.displayName = validateDisplayName(body.display_name); + } + if (Object.hasOwn(body, 'issuer')) result.issuer = validateIssuer(body.issuer); + if (Object.hasOwn(body, 'client_id')) result.clientId = validateProviderClientId(body.client_id); + if (Object.hasOwn(body, 'scopes')) result.scopes = normalizeScopes(body.scopes); + if (Object.hasOwn(body, 'enabled')) result.enabled = validateEnabled(body.enabled); + if (Object.hasOwn(body, 'client_secret')) { + result.secret = + body.client_secret === null + ? { mode: 'clear' } + : { mode: 'set', value: validateSecret(body.client_secret) }; + } + + if (Object.keys(result).length === 0) { + throw invalidRequest('At least one field must be provided'); + } + return result; +} + +function serializeProvider(row, domains) { + return { + id: row.id, + slug: row.slug, + display_name: row.display_name, + issuer: row.issuer, + client_id: row.client_id, + scopes: row.scopes, + enabled: Boolean(row.enabled), + has_secret: row.client_secret !== null && String(row.client_secret) !== '', + domains, + created_at: row.created_at, + updated_at: row.updated_at, + }; +} + +export async function getAdminProviderRow(realmDb, slug) { + return realmDb.get( + `SELECT ${PROVIDER_COLUMNS} FROM identity_providers WHERE slug = {slug}`, + { slug } + ); +} + +async function loadProviderDomains(realmDb, providerId) { + const rows = await realmDb.all( + 'SELECT domain FROM email_domain_providers WHERE provider_id = {providerId} ORDER BY domain ASC', + { providerId } + ); + return rows.map((row) => row.domain); +} + +export async function listAdminRealmProviders({ realmDb }) { + const rows = await realmDb.all( + `SELECT ${PROVIDER_COLUMNS} FROM identity_providers ORDER BY display_name ASC, slug ASC` + ); + const mappings = await realmDb.all( + 'SELECT provider_id, domain FROM email_domain_providers ORDER BY domain ASC' + ); + + const domainsByProvider = new Map(); + for (const mapping of mappings) { + const current = domainsByProvider.get(mapping.provider_id) || []; + current.push(mapping.domain); + domainsByProvider.set(mapping.provider_id, current); + } + + return rows.map((row) => serializeProvider(row, domainsByProvider.get(row.id) || [])); +} + +export async function getAdminRealmProvider({ realmDb, slug }) { + const row = await getAdminProviderRow(realmDb, slug); + if (!row) return null; + return serializeProvider(row, await loadProviderDomains(realmDb, row.id)); +} + +function mapProviderDatabaseError(error) { + if (/UNIQUE constraint failed: identity_providers\.slug/.test(String(error?.message || ''))) { + return conflict('This slug is already used by a provider in the realm.', 'provider_slug_exists'); + } + throw error; +} + +export async function createAdminRealmProvider({ realmDb, input }) { + const existing = await getAdminProviderRow(realmDb, input.slug); + if (existing) { + throw conflict('This slug is already used by a provider in the realm.', 'provider_slug_exists'); + } + + const id = crypto.randomUUID(); + const now = Date.now(); + try { + await realmDb.run( + `INSERT INTO identity_providers + (id, slug, display_name, issuer, client_id, client_secret, scopes, enabled, created_at, updated_at) + VALUES + ({id}, {slug}, {displayName}, {issuer}, {clientId}, {clientSecret}, {scopes}, {enabled}, {createdAt}, {updatedAt})`, + { + id, + slug: input.slug, + displayName: input.displayName, + issuer: input.issuer, + clientId: input.clientId, + clientSecret: input.clientSecret, + scopes: input.scopes, + enabled: input.enabled ? 1 : 0, + createdAt: now, + updatedAt: now, + } + ); + } catch (error) { + mapProviderDatabaseError(error); + } + + return serializeProvider( + { + id, + slug: input.slug, + display_name: input.displayName, + issuer: input.issuer, + client_id: input.clientId, + client_secret: input.clientSecret, + scopes: input.scopes, + enabled: input.enabled ? 1 : 0, + created_at: now, + updated_at: now, + }, + [] + ); +} + +export async function updateAdminRealmProvider({ realmDb, slug, input }) { + const row = await getAdminProviderRow(realmDb, slug); + if (!row) { + throw notFound(); + } + + const next = { + displayName: input.displayName ?? row.display_name, + issuer: input.issuer ?? row.issuer, + clientId: input.clientId ?? row.client_id, + scopes: input.scopes ?? row.scopes, + enabled: input.enabled ?? Boolean(row.enabled), + }; + let clientSecret = row.client_secret; + if (input.secret) { + clientSecret = input.secret.mode === 'clear' ? null : input.secret.value; + } + const now = Date.now(); + + await realmDb.run( + `UPDATE identity_providers + SET display_name = {displayName}, issuer = {issuer}, client_id = {clientId}, + client_secret = {clientSecret}, scopes = {scopes}, enabled = {enabled}, + updated_at = {updatedAt} + WHERE id = {id}`, + { + displayName: next.displayName, + issuer: next.issuer, + clientId: next.clientId, + clientSecret, + scopes: next.scopes, + enabled: next.enabled ? 1 : 0, + updatedAt: now, + id: row.id, + } + ); + + return serializeProvider( + { + ...row, + display_name: next.displayName, + issuer: next.issuer, + client_id: next.clientId, + client_secret: clientSecret, + scopes: next.scopes, + enabled: next.enabled ? 1 : 0, + updated_at: now, + }, + await loadProviderDomains(realmDb, row.id) + ); +} + +export async function deleteAdminRealmProvider({ realmDb, slug }) { + const row = await getAdminProviderRow(realmDb, slug); + if (!row) { + throw notFound(); + } + + let unlinkedDomains = []; + await realmDb.transaction(async (tx) => { + const mappings = await tx.all( + 'SELECT domain FROM email_domain_providers WHERE provider_id = {providerId} ORDER BY domain ASC', + { providerId: row.id } + ); + unlinkedDomains = mappings.map((mapping) => mapping.domain); + // email_domain_providers cascade-deletes through the ON DELETE CASCADE FK. + await tx.run('DELETE FROM identity_providers WHERE id = {id}', { id: row.id }); + }); + + return { removed: true, slug: row.slug, unlinked_domains: unlinkedDomains }; +} + +async function requireAdminProvider(realmDb, slug) { + const row = await getAdminProviderRow(realmDb, slug); + if (!row) { + throw notFound(); + } + return row; +} + +export async function connectAdminProviderDomain({ systemDb, realm, realmDb, slug, domain }) { + const normalized = validateRealmEmailDomain(domain); + const provider = await requireAdminProvider(realmDb, slug); + + const emailDomain = await getRealmEmailDomain(systemDb, realm.id, normalized); + if (!emailDomain || !emailDomain.verified) { + throw conflict( + 'Email domain must be a verified email domain of this realm.', + 'domain_unavailable' + ); + } + + const existing = await realmDb.get( + 'SELECT provider_id FROM email_domain_providers WHERE domain = {domain}', + { domain: normalized } + ); + if (existing) { + if (existing.provider_id === provider.id) { + return { domain: normalized, already_connected: true }; + } + throw conflict( + 'This email domain is already connected to another provider.', + 'domain_in_use' + ); + } + + try { + await realmDb.run( + 'INSERT INTO email_domain_providers (domain, provider_id, created_at) VALUES ({domain}, {providerId}, {createdAt})', + { domain: normalized, providerId: provider.id, createdAt: Date.now() } + ); + } catch (error) { + if (/UNIQUE constraint failed: email_domain_providers\.domain/.test(String(error?.message || ''))) { + throw conflict( + 'This email domain is already connected to another provider.', + 'domain_in_use' + ); + } + throw error; + } + + return { domain: normalized }; +} + +export async function disconnectAdminProviderDomain({ realmDb, slug, domain }) { + const normalized = normalizeEmailDomainKey(domain); + const provider = await requireAdminProvider(realmDb, slug); + + if (!normalized) { + throw notFound('Email domain is not connected to this provider.', 'domain_not_found'); + } + const result = await realmDb.run( + 'DELETE FROM email_domain_providers WHERE domain = {domain} AND provider_id = {providerId}', + { domain: normalized, providerId: provider.id } + ); + if (!result.changes) { + throw notFound('Email domain is not connected to this provider.', 'domain_not_found'); + } + + return { removed: true, domain: normalized }; +} diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -5315,6 +5315,406 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { } }); + await t.test('admin realm identity provider management', async () => { + const systemAdmin = await adminToken(); + const acmeAdmin = await adminToken('it@acme.test'); + + const providersBase = '/api/v1/admin/realms/acme/providers'; + const createdSlugs = []; + const connectedDomains = []; + const createdEmailDomains = []; + + const providerPath = (slug) => `${providersBase}/${encodeURIComponent(slug)}`; + const domainPath = (slug, domain) => + `${providerPath(slug)}/domains/${encodeURIComponent(domain)}`; + const deleteProvider = (admin, slug) => + adminRequest(admin, { method: 'DELETE', path: providerPath(slug) }); + const disconnectDomain = (admin, slug, domain) => + adminRequest(admin, { method: 'DELETE', path: domainPath(slug, domain) }); + const deleteEmailDomain = (domain) => + adminRequest(systemAdmin, { + method: 'DELETE', + path: `/api/v1/admin/realms/acme/email-domains/${encodeURIComponent(domain)}`, + }); + + try { + const list = await adminRequest(systemAdmin, { path: providersBase }); + assert.equal(list.status, 200); + assert.ok(Array.isArray(list.json.providers)); + const seeded = list.json.providers.find((entry) => entry.slug === 'example-sso'); + assert.ok(seeded, 'seeded example-sso present'); + assert.equal(seeded.display_name, 'Example SSO'); + assert.equal(seeded.issuer, 'https://idp.example.com'); + assert.equal(seeded.client_id, 'demo'); + assert.equal(seeded.scopes, 'openid email profile'); + assert.equal(seeded.has_secret, true); + assert.equal(seeded.enabled, true); + assert.deepEqual(seeded.domains, ['sso.acme.test']); + assert.ok(!('client_secret' in seeded), 'no client_secret field in payload'); + assert.ok(!list.text.includes('demo-secret'), 'stored secret never serialized'); + + const crossList = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/globex/providers', + }); + assert.equal(crossList.status, 403); + assert.equal(crossList.json.error.code, 'forbidden'); + const unknownRealm = await adminRequest(systemAdmin, { + path: '/api/v1/admin/realms/does-not-exist/providers', + }); + assert.equal(unknownRealm.status, 404); + const anonymous = await identity({ path: providersBase }); + assert.equal(anonymous.status, 401); + + const created = await adminRequest(acmeAdmin, { + method: 'POST', + path: providersBase, + body: { + slug: ' PADDLED-SSO ', + display_name: ' Paddled SSO ', + issuer: 'https://idp.paddled.test', + client_id: 'paddled', + }, + }); + assert.equal(created.status, 200); + assert.equal(created.json.ok, true); + assert.equal(created.json.provider.slug, 'paddled-sso'); + assert.equal(created.json.provider.display_name, 'Paddled SSO'); + assert.equal(created.json.provider.enabled, true); + assert.equal(created.json.provider.scopes, 'openid profile email'); + assert.equal(created.json.provider.has_secret, false); + assert.deepEqual(created.json.provider.domains, []); + assert.equal(typeof created.json.provider.id, 'string'); + createdSlugs.push('paddled-sso'); + + for (const slug of ['', 'Bad Slug', '-lead', 'trail-', 'a'.repeat(64)]) { + const bad = await adminRequest(acmeAdmin, { + method: 'POST', + path: providersBase, + body: { slug, display_name: 'X', issuer: 'https://x.test', client_id: 'x' }, + }); + assert.equal(bad.status, 400, `slug ${JSON.stringify(slug)} rejected`); + } + const duplicate = await adminRequest(acmeAdmin, { + method: 'POST', + path: providersBase, + body: { + slug: 'example-sso', + display_name: 'Duplicate', + issuer: 'https://dup.example.test', + client_id: 'dup', + }, + }); + assert.equal(duplicate.status, 409); + assert.equal(duplicate.json.error.code, 'provider_slug_exists'); + + const unknownField = await adminRequest(acmeAdmin, { + method: 'POST', + path: providersBase, + body: { + slug: 'field-test', + display_name: 'Field Test', + issuer: 'https://fields.example.test', + client_id: 'ft', + extra: true, + }, + }); + assert.equal(unknownField.status, 400); + assert.equal(unknownField.json.error.message, 'Unknown field: extra'); + + for (const issuer of [ + 'http://idp.example.test', + 'https://idp.example.test/', + 'https://user:pw@idp.example.test', + 'https://idp.example.test?x=1', + 'https://idp.example.test#frag', + 'https://singlelabel', + 'not-a-url', + ]) { + const bad = await adminRequest(acmeAdmin, { + method: 'POST', + path: providersBase, + body: { slug: 'issuer-test', display_name: 'Issuer Test', issuer, client_id: 'it' }, + }); + assert.equal(bad.status, 400, `issuer ${JSON.stringify(issuer)} rejected`); + } + const badClientId = await adminRequest(acmeAdmin, { + method: 'POST', + path: providersBase, + body: { + slug: 'client-id-test', + display_name: 'Client Id Test', + issuer: 'https://cid.example.test', + client_id: 'has space', + }, + }); + assert.equal(badClientId.status, 400); + + const withSecret = await adminRequest(acmeAdmin, { + method: 'POST', + path: providersBase, + body: { + slug: 'secret-sso', + display_name: 'Secret SSO', + issuer: 'https://idp.secret.test', + client_id: 'sec', + client_secret: 's3cr3t value', + }, + }); + assert.equal(withSecret.status, 200); + assert.equal(withSecret.json.provider.has_secret, true); + assert.ok(!withSecret.text.includes('s3cr3t'), 'create response hides the secret'); + createdSlugs.push('secret-sso'); + + const replaced = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: providerPath('secret-sso'), + body: { client_secret: 'rotated-secret' }, + }); + assert.equal(replaced.status, 200); + assert.equal(replaced.json.provider.has_secret, true); + assert.ok(!replaced.text.includes('rotated-secret'), 'patch response hides the secret'); + + const cleared = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: providerPath('secret-sso'), + body: { client_secret: null }, + }); + assert.equal(cleared.status, 200); + assert.equal(cleared.json.provider.has_secret, false); + + const emptySecret = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: providerPath('secret-sso'), + body: { client_secret: '' }, + }); + assert.equal(emptySecret.status, 400); + + const slugPatch = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: providerPath('paddled-sso'), + body: { slug: 'other-slug' }, + }); + assert.equal(slugPatch.status, 400); + assert.equal(slugPatch.json.error.message, 'slug cannot be updated'); + + const emptyPatch = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: providerPath('paddled-sso'), + body: {}, + }); + assert.equal(emptyPatch.status, 400); + + const ghostPatch = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: providerPath('ghost-sso'), + body: { display_name: 'Ghost' }, + }); + assert.equal(ghostPatch.status, 404); + assert.equal(ghostPatch.json.error.code, 'provider_not_found'); + + const ghostGet = await adminRequest(acmeAdmin, { path: providerPath('ghost-sso') }); + assert.equal(ghostGet.status, 404); + + const disabled = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: providerPath('example-sso'), + body: { enabled: false }, + }); + assert.equal(disabled.status, 200); + assert.equal(disabled.json.provider.enabled, false); + const reEnabled = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: providerPath('example-sso'), + body: { enabled: true }, + }); + assert.equal(reEnabled.json.provider.enabled, true); + + const single = await adminRequest(acmeAdmin, { path: providerPath('example-sso') }); + assert.equal(single.status, 200); + assert.deepEqual(single.json.provider.domains, ['sso.acme.test']); + + const connect = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('paddled-sso')}/domains`, + body: { domain: 'Acme.Test' }, + }); + assert.equal(connect.status, 200); + assert.equal(connect.json.domain, 'acme.test'); + connectedDomains.push({ slug: 'paddled-sso', domain: 'acme.test' }); + + const reConnect = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('paddled-sso')}/domains`, + body: { domain: 'acme.test' }, + }); + assert.equal(reConnect.status, 200); + assert.equal(reConnect.json.already_connected, true); + + const connectUnknown = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('paddled-sso')}/domains`, + body: { domain: 'nowhere.example.test' }, + }); + assert.equal(connectUnknown.status, 409); + assert.equal(connectUnknown.json.error.code, 'domain_unavailable'); + + const connectBadDomain = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('paddled-sso')}/domains`, + body: { domain: 'not a domain' }, + }); + assert.equal(connectBadDomain.status, 400); + + const connectExtraField = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('paddled-sso')}/domains`, + body: { domain: 'acme.test', extra: 1 }, + }); + assert.equal(connectExtraField.status, 400); + + const pending = await adminRequest(acmeAdmin, { + method: 'POST', + path: '/api/v1/admin/realms/acme/email-domains', + body: { domain: 'prov-pending.acme.test' }, + }); + assert.equal(pending.status, 200); + createdEmailDomains.push('prov-pending.acme.test'); + + const connectPending = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('paddled-sso')}/domains`, + body: { domain: 'prov-pending.acme.test' }, + }); + assert.equal(connectPending.status, 409); + assert.equal(connectPending.json.error.code, 'domain_unavailable'); + + const verifyPending = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: '/api/v1/admin/realms/acme/email-domains/prov-pending.acme.test', + body: { verified: true }, + }); + assert.equal(verifyPending.status, 200); + + const connectNowVerified = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('paddled-sso')}/domains`, + body: { domain: 'prov-pending.acme.test' }, + }); + assert.equal(connectNowVerified.status, 200); + connectedDomains.push({ slug: 'paddled-sso', domain: 'prov-pending.acme.test' }); + + const conflictConnect = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('secret-sso')}/domains`, + body: { domain: 'acme.test' }, + }); + assert.equal(conflictConnect.status, 409); + assert.equal(conflictConnect.json.error.code, 'domain_in_use'); + + const ghostConnect = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('ghost-sso')}/domains`, + body: { domain: 'acme.test' }, + }); + assert.equal(ghostConnect.status, 404); + assert.equal(ghostConnect.json.error.code, 'provider_not_found'); + + const disconnected = await adminRequest(acmeAdmin, { + method: 'DELETE', + path: domainPath('paddled-sso', 'prov-pending.acme.test'), + }); + assert.equal(disconnected.status, 200); + assert.equal(disconnected.json.removed, true); + assert.equal(disconnected.json.domain, 'prov-pending.acme.test'); + + const disconnectAgain = await adminRequest(acmeAdmin, { + method: 'DELETE', + path: domainPath('paddled-sso', 'prov-pending.acme.test'), + }); + assert.equal(disconnectAgain.status, 404); + assert.equal(disconnectAgain.json.error.code, 'domain_not_found'); + + const disconnectGhostProvider = await adminRequest(acmeAdmin, { + method: 'DELETE', + path: domainPath('ghost-sso', 'acme.test'), + }); + assert.equal(disconnectGhostProvider.status, 404); + assert.equal(disconnectGhostProvider.json.error.code, 'provider_not_found'); + + const cascadeProvider = await adminRequest(acmeAdmin, { + method: 'POST', + path: providersBase, + body: { + slug: 'cascade-sso', + display_name: 'Cascade SSO', + issuer: 'https://idp.cascade.test', + client_id: 'cas', + }, + }); + assert.equal(cascadeProvider.status, 200); + const cascadeDomain = await adminRequest(acmeAdmin, { + method: 'POST', + path: '/api/v1/admin/realms/acme/email-domains', + body: { domain: 'cascade.acme.test' }, + }); + assert.equal(cascadeDomain.status, 200); + createdEmailDomains.push('cascade.acme.test'); + const verifyCascade = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: '/api/v1/admin/realms/acme/email-domains/cascade.acme.test', + body: { verified: true }, + }); + assert.equal(verifyCascade.status, 200); + const cascadeConnect = await adminRequest(acmeAdmin, { + method: 'POST', + path: `${providerPath('cascade-sso')}/domains`, + body: { domain: 'cascade.acme.test' }, + }); + assert.equal(cascadeConnect.status, 200); + + const deleted = await adminRequest(acmeAdmin, { + method: 'DELETE', + path: providerPath('cascade-sso'), + }); + assert.equal(deleted.status, 200); + assert.equal(deleted.json.removed, true); + assert.deepEqual(deleted.json.unlinked_domains, ['cascade.acme.test']); + const mappingRows = withRealmDatabase(env, 'acme', (database) => + database + .prepare('SELECT COUNT(*) AS count FROM email_domain_providers WHERE domain = ?') + .get('cascade.acme.test').count + ); + assert.equal(mappingRows, 0, 'cascade removed the mapping row'); + + const deletedAgain = await adminRequest(acmeAdmin, { + method: 'DELETE', + path: providerPath('cascade-sso'), + }); + assert.equal(deletedAgain.status, 404); + + const finalList = await adminRequest(systemAdmin, { path: providersBase }); + assert.ok( + !finalList.json.providers.some((entry) => entry.slug === 'cascade-sso'), + 'deleted provider is gone from the list' + ); + } finally { + for (const entry of connectedDomains) { + await disconnectDomain(systemAdmin, entry.slug, entry.domain); + } + for (const slug of createdSlugs) { + await deleteProvider(systemAdmin, slug); + } + for (const domain of createdEmailDomains) { + await deleteEmailDomain(domain); + } + await adminRequest(systemAdmin, { + method: 'PATCH', + path: providerPath('example-sso'), + body: { enabled: true }, + }); + } + }); + await t.test('system branding updates Admin settings and discovery precedence', async () => { const systemAdmin = await adminToken(); const acmeAdmin = await adminToken('it@acme.test');