auth

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

admin-realm-providers.js (16932B)


      1 import crypto from 'node:crypto';
      2 import { normalizeScopes } from './admin-clients.js';
      3 import { inClause } from './db/query.js';
      4 import { HttpError } from './http/http-error.js';
      5 import { pagedResult, searchClause } from './pagination.js';
      6 import { getRealmEmailDomain, validateRealmEmailDomain } from './realm.js';
      7 import { encryptSecret, hasSecretKey, isEncrypted, secretStorageUnavailable } from './secrets.js';
      8 
      9 const SLUG_MAX_LENGTH = 63;
     10 const NAME_MAX_LENGTH = 120;
     11 const CLIENT_ID_MAX_LENGTH = 255;
     12 const SECRET_MAX_LENGTH = 255;
     13 const ISSUER_MAX_LENGTH = 512;
     14 const SLUG_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
     15 const PRINTABLE_PATTERN = /^[\x21-\x7e]+$/;
     16 
     17 const PROVIDER_COLUMNS =
     18   'id, slug, display_name, issuer, client_id, client_secret, scopes, enabled, created_at, updated_at';
     19 
     20 function invalidRequest(message) {
     21   return new HttpError(400, 'invalid_request', message);
     22 }
     23 
     24 function notFound(message = 'Identity provider not found', code = 'provider_not_found') {
     25   return new HttpError(404, code, message);
     26 }
     27 
     28 function conflict(message, code) {
     29   return new HttpError(409, code, message);
     30 }
     31 
     32 function isPlainObject(value) {
     33   return value !== null && typeof value === 'object' && !Array.isArray(value);
     34 }
     35 
     36 function assertBody(body) {
     37   if (!isPlainObject(body)) {
     38     throw invalidRequest('Request body must be a JSON object');
     39   }
     40 }
     41 
     42 function assertKnownFields(body, allowed) {
     43   for (const field of Object.keys(body)) {
     44     if (!allowed.has(field)) {
     45       throw invalidRequest(`Unknown field: ${field}`);
     46     }
     47   }
     48 }
     49 
     50 function validateSlug(value) {
     51   if (typeof value !== 'string') {
     52     throw invalidRequest('slug must be a string');
     53   }
     54   const slug = value.trim().toLowerCase();
     55   if (!slug || slug.length > SLUG_MAX_LENGTH || !SLUG_PATTERN.test(slug)) {
     56     throw invalidRequest(
     57       'slug must contain only lowercase letters, digits, and hyphens, and must start and end with a letter or digit'
     58     );
     59   }
     60   return slug;
     61 }
     62 
     63 function validateDisplayName(value) {
     64   if (typeof value !== 'string') {
     65     throw invalidRequest('display_name must be a string');
     66   }
     67   const name = value.trim();
     68   if (!name || name.length > NAME_MAX_LENGTH) {
     69     throw invalidRequest(`display_name must be between 1 and ${NAME_MAX_LENGTH} characters`);
     70   }
     71   return name;
     72 }
     73 
     74 function validateIssuer(value) {
     75   if (typeof value !== 'string') {
     76     throw invalidRequest('issuer must be a string');
     77   }
     78   const issuer = value.trim();
     79   if (!issuer || issuer.length > ISSUER_MAX_LENGTH) {
     80     throw invalidRequest(`issuer must be between 1 and ${ISSUER_MAX_LENGTH} characters`);
     81   }
     82   if (issuer.endsWith('/')) {
     83     throw invalidRequest('issuer must not end with a slash');
     84   }
     85 
     86   let parsed;
     87   try {
     88     parsed = new URL(issuer);
     89   } catch {
     90     throw invalidRequest('issuer must be an absolute URL');
     91   }
     92   if (parsed.protocol !== 'https:') {
     93     throw invalidRequest('issuer must use https');
     94   }
     95   if (parsed.username || parsed.password) {
     96     throw invalidRequest('issuer must not contain credentials');
     97   }
     98   if (parsed.search) {
     99     throw invalidRequest('issuer must not contain a query');
    100   }
    101   if (parsed.hash) {
    102     throw invalidRequest('issuer must not contain a fragment');
    103   }
    104   if (!parsed.hostname.includes('.')) {
    105     throw invalidRequest('issuer must include a complete hostname such as https://idp.example.com');
    106   }
    107   return issuer;
    108 }
    109 
    110 function validateProviderClientId(value) {
    111   if (typeof value !== 'string') {
    112     throw invalidRequest('client_id must be a string');
    113   }
    114   const clientId = value.trim();
    115   if (!clientId || clientId.length > CLIENT_ID_MAX_LENGTH) {
    116     throw invalidRequest(`client_id must be between 1 and ${CLIENT_ID_MAX_LENGTH} characters`);
    117   }
    118   if (!PRINTABLE_PATTERN.test(clientId)) {
    119     throw invalidRequest('client_id must contain only printable non-whitespace characters');
    120   }
    121   return clientId;
    122 }
    123 
    124 function validateSecret(value) {
    125   if (typeof value !== 'string' || value.trim() === '') {
    126     throw invalidRequest('client_secret must be a non-empty string');
    127   }
    128   if (value.length > SECRET_MAX_LENGTH) {
    129     throw invalidRequest(`client_secret must be ${SECRET_MAX_LENGTH} characters or fewer`);
    130   }
    131   return value;
    132 }
    133 
    134 function validateEnabled(value) {
    135   if (typeof value !== 'boolean') {
    136     throw invalidRequest('enabled must be a boolean');
    137   }
    138   return value;
    139 }
    140 
    141 function normalizeEmailDomainKey(domain) {
    142   return String(domain || '').trim().toLowerCase().replace(/\.$/, '');
    143 }
    144 
    145 export function normalizeCreateProviderInput(body) {
    146   assertBody(body);
    147   assertKnownFields(
    148     body,
    149     new Set([
    150       'slug',
    151       'display_name',
    152       'issuer',
    153       'client_id',
    154       'client_secret',
    155       'scopes',
    156       'enabled',
    157     ])
    158   );
    159 
    160   if (!Object.hasOwn(body, 'display_name')) {
    161     throw invalidRequest('display_name is required');
    162   }
    163   if (!Object.hasOwn(body, 'issuer')) {
    164     throw invalidRequest('issuer is required');
    165   }
    166   if (!Object.hasOwn(body, 'client_id')) {
    167     throw invalidRequest('client_id is required');
    168   }
    169   if (body.client_secret !== undefined && body.client_secret !== null && typeof body.client_secret !== 'string') {
    170     throw invalidRequest('client_secret must be a string');
    171   }
    172 
    173   return {
    174     slug: validateSlug(body.slug),
    175     displayName: validateDisplayName(body.display_name),
    176     issuer: validateIssuer(body.issuer),
    177     clientId: validateProviderClientId(body.client_id),
    178     clientSecret:
    179       body.client_secret === undefined || body.client_secret === null
    180         ? null
    181         : validateSecret(body.client_secret),
    182     scopes: normalizeScopes(body.scopes),
    183     enabled: validateEnabled(body.enabled === undefined ? true : body.enabled),
    184   };
    185 }
    186 
    187 export function normalizeUpdateProviderInput(body) {
    188   assertBody(body);
    189   if (Object.hasOwn(body, 'slug')) {
    190     throw invalidRequest('slug cannot be updated');
    191   }
    192   assertKnownFields(
    193     body,
    194     new Set(['display_name', 'issuer', 'client_id', 'client_secret', 'scopes', 'enabled'])
    195   );
    196 
    197   const result = {};
    198   if (Object.hasOwn(body, 'display_name')) {
    199     result.displayName = validateDisplayName(body.display_name);
    200   }
    201   if (Object.hasOwn(body, 'issuer')) result.issuer = validateIssuer(body.issuer);
    202   if (Object.hasOwn(body, 'client_id')) result.clientId = validateProviderClientId(body.client_id);
    203   if (Object.hasOwn(body, 'scopes')) result.scopes = normalizeScopes(body.scopes);
    204   if (Object.hasOwn(body, 'enabled')) result.enabled = validateEnabled(body.enabled);
    205   if (Object.hasOwn(body, 'client_secret')) {
    206     result.secret =
    207       body.client_secret === null
    208         ? { mode: 'clear' }
    209         : { mode: 'set', value: validateSecret(body.client_secret) };
    210   }
    211 
    212   if (Object.keys(result).length === 0) {
    213     throw invalidRequest('At least one field must be provided');
    214   }
    215   return result;
    216 }
    217 
    218 function serializeProvider(row, domains) {
    219   return {
    220     id: row.id,
    221     slug: row.slug,
    222     display_name: row.display_name,
    223     issuer: row.issuer,
    224     client_id: row.client_id,
    225     scopes: row.scopes,
    226     enabled: Boolean(row.enabled),
    227     has_secret: row.client_secret !== null && String(row.client_secret) !== '',
    228     domains,
    229     created_at: row.created_at,
    230     updated_at: row.updated_at,
    231   };
    232 }
    233 
    234 export async function getAdminProviderRow(realmDb, slug) {
    235   return realmDb.get(
    236     `SELECT ${PROVIDER_COLUMNS} FROM identity_providers WHERE slug = {slug}`,
    237     { slug }
    238   );
    239 }
    240 
    241 async function loadProviderDomains(realmDb, providerId) {
    242   const rows = await realmDb.all(
    243     'SELECT domain, created_at FROM email_domain_providers WHERE provider_id = {providerId} ORDER BY domain ASC',
    244     { providerId }
    245   );
    246   return rows.map((row) => ({ domain: row.domain, created_at: row.created_at }));
    247 }
    248 
    249 export async function listAdminRealmProviders({ realmDb }) {
    250   const rows = await realmDb.all(
    251     `SELECT ${PROVIDER_COLUMNS} FROM identity_providers ORDER BY display_name ASC, slug ASC`
    252   );
    253   const mappings = await realmDb.all(
    254     'SELECT provider_id, domain, created_at FROM email_domain_providers ORDER BY domain ASC'
    255   );
    256 
    257   const domainsByProvider = new Map();
    258   for (const mapping of mappings) {
    259     const current = domainsByProvider.get(mapping.provider_id) || [];
    260     current.push({ domain: mapping.domain, created_at: mapping.created_at });
    261     domainsByProvider.set(mapping.provider_id, current);
    262   }
    263 
    264   return rows.map((row) => serializeProvider(row, domainsByProvider.get(row.id) || []));
    265 }
    266 
    267 const PROVIDER_SEARCH_COLUMNS = ['display_name', 'slug', 'issuer'];
    268 
    269 export async function listAdminRealmProvidersPage({ realmDb, pagination }) {
    270   const params = { limit: pagination.limit, offset: pagination.offset };
    271   let filter = '1 = 1';
    272   if (pagination.q) {
    273     const search = searchClause(pagination.q, PROVIDER_SEARCH_COLUMNS);
    274     filter += ` AND ${search.clause}`;
    275     Object.assign(params, search.params);
    276   }
    277 
    278   const rows = await realmDb.all(
    279     `SELECT ${PROVIDER_COLUMNS}
    280        FROM identity_providers
    281       WHERE ${filter}
    282       ORDER BY display_name ASC, slug ASC
    283       LIMIT {limit} OFFSET {offset}`,
    284     params
    285   );
    286   const count = await realmDb.get(
    287     `SELECT COUNT(*) AS total FROM identity_providers WHERE ${filter}`,
    288     params
    289   );
    290 
    291   const providers = [];
    292   if (rows.length > 0) {
    293     const pageClause = inClause('providerId', rows.map((row) => row.id));
    294     const mappings = await realmDb.all(
    295       `SELECT provider_id, domain, created_at
    296          FROM email_domain_providers
    297         WHERE provider_id IN (${pageClause.sql})
    298         ORDER BY domain ASC`,
    299       pageClause.params
    300     );
    301     const domainsByProvider = new Map();
    302     for (const mapping of mappings) {
    303       const current = domainsByProvider.get(mapping.provider_id) || [];
    304       current.push({ domain: mapping.domain, created_at: mapping.created_at });
    305       domainsByProvider.set(mapping.provider_id, current);
    306     }
    307     for (const row of rows) {
    308       providers.push(serializeProvider(row, domainsByProvider.get(row.id) || []));
    309     }
    310   }
    311 
    312   return pagedResult('providers', providers, {
    313     limit: pagination.limit,
    314     offset: pagination.offset,
    315     total: count.total,
    316   });
    317 }
    318 
    319 export async function getAdminRealmProvider({ realmDb, slug }) {
    320   const row = await getAdminProviderRow(realmDb, slug);
    321   if (!row) return null;
    322   return serializeProvider(row, await loadProviderDomains(realmDb, row.id));
    323 }
    324 
    325 function mapProviderDatabaseError(error) {
    326   if (/UNIQUE constraint failed: identity_providers\.slug/.test(String(error?.message || ''))) {
    327     return conflict('This slug is already used by a provider in the realm.', 'provider_slug_exists');
    328   }
    329   throw error;
    330 }
    331 
    332 export async function createAdminRealmProvider({ realmDb, realmId, input }) {
    333   const existing = await getAdminProviderRow(realmDb, input.slug);
    334   if (existing) {
    335     throw conflict('This slug is already used by a provider in the realm.', 'provider_slug_exists');
    336   }
    337   if (input.clientSecret !== null && !hasSecretKey()) {
    338     throw secretStorageUnavailable();
    339   }
    340 
    341   const id = crypto.randomUUID();
    342   const storedSecret =
    343     input.clientSecret === null
    344       ? null
    345       : encryptSecret(input.clientSecret, { realmId, providerId: id });
    346   const now = Date.now();
    347   try {
    348     await realmDb.run(
    349       `INSERT INTO identity_providers
    350         (id, slug, display_name, issuer, client_id, client_secret, scopes, enabled, created_at, updated_at)
    351        VALUES
    352         ({id}, {slug}, {displayName}, {issuer}, {clientId}, {clientSecret}, {scopes}, {enabled}, {createdAt}, {updatedAt})`,
    353       {
    354         id,
    355         slug: input.slug,
    356         displayName: input.displayName,
    357         issuer: input.issuer,
    358         clientId: input.clientId,
    359         clientSecret: storedSecret,
    360         scopes: input.scopes,
    361         enabled: input.enabled ? 1 : 0,
    362         createdAt: now,
    363         updatedAt: now,
    364       }
    365     );
    366   } catch (error) {
    367     mapProviderDatabaseError(error);
    368   }
    369 
    370   return serializeProvider(
    371     {
    372       id,
    373       slug: input.slug,
    374       display_name: input.displayName,
    375       issuer: input.issuer,
    376       client_id: input.clientId,
    377       client_secret: storedSecret,
    378       scopes: input.scopes,
    379       enabled: input.enabled ? 1 : 0,
    380       created_at: now,
    381       updated_at: now,
    382     },
    383     []
    384   );
    385 }
    386 
    387 export async function updateAdminRealmProvider({ realmDb, realmId, slug, input }) {
    388   const row = await getAdminProviderRow(realmDb, slug);
    389   if (!row) {
    390     throw notFound();
    391   }
    392 
    393   const next = {
    394     displayName: input.displayName ?? row.display_name,
    395     issuer: input.issuer ?? row.issuer,
    396     clientId: input.clientId ?? row.client_id,
    397     scopes: input.scopes ?? row.scopes,
    398     enabled: input.enabled ?? Boolean(row.enabled),
    399   };
    400   let clientSecret = row.client_secret;
    401   if (input.secret) {
    402     if (input.secret.mode === 'clear') {
    403       clientSecret = null;
    404     } else {
    405       if (!hasSecretKey()) {
    406         throw secretStorageUnavailable();
    407       }
    408       clientSecret = encryptSecret(input.secret.value, { realmId, providerId: row.id });
    409     }
    410   } else if (clientSecret && !isEncrypted(clientSecret) && hasSecretKey()) {
    411     clientSecret = encryptSecret(clientSecret, { realmId, providerId: row.id });
    412   }
    413   const now = Date.now();
    414 
    415   await realmDb.run(
    416     `UPDATE identity_providers
    417         SET display_name = {displayName}, issuer = {issuer}, client_id = {clientId},
    418             client_secret = {clientSecret}, scopes = {scopes}, enabled = {enabled},
    419             updated_at = {updatedAt}
    420       WHERE id = {id}`,
    421     {
    422       displayName: next.displayName,
    423       issuer: next.issuer,
    424       clientId: next.clientId,
    425       clientSecret,
    426       scopes: next.scopes,
    427       enabled: next.enabled ? 1 : 0,
    428       updatedAt: now,
    429       id: row.id,
    430     }
    431   );
    432 
    433   return serializeProvider(
    434     {
    435       ...row,
    436       display_name: next.displayName,
    437       issuer: next.issuer,
    438       client_id: next.clientId,
    439       client_secret: clientSecret,
    440       scopes: next.scopes,
    441       enabled: next.enabled ? 1 : 0,
    442       updated_at: now,
    443     },
    444     await loadProviderDomains(realmDb, row.id)
    445   );
    446 }
    447 
    448 export async function deleteAdminRealmProvider({ realmDb, slug }) {
    449   const row = await getAdminProviderRow(realmDb, slug);
    450   if (!row) {
    451     throw notFound();
    452   }
    453 
    454   let unlinkedDomains = [];
    455   await realmDb.transaction(async (tx) => {
    456     const mappings = await tx.all(
    457       'SELECT domain FROM email_domain_providers WHERE provider_id = {providerId} ORDER BY domain ASC',
    458       { providerId: row.id }
    459     );
    460     unlinkedDomains = mappings.map((mapping) => mapping.domain);
    461     // email_domain_providers cascade-deletes through the ON DELETE CASCADE FK.
    462     await tx.run('DELETE FROM identity_providers WHERE id = {id}', { id: row.id });
    463   });
    464 
    465   return { removed: true, slug: row.slug, unlinked_domains: unlinkedDomains };
    466 }
    467 
    468 async function requireAdminProvider(realmDb, slug) {
    469   const row = await getAdminProviderRow(realmDb, slug);
    470   if (!row) {
    471     throw notFound();
    472   }
    473   return row;
    474 }
    475 
    476 export async function connectAdminProviderDomain({ systemDb, realm, realmDb, slug, domain }) {
    477   const normalized = validateRealmEmailDomain(domain);
    478   const provider = await requireAdminProvider(realmDb, slug);
    479 
    480   const emailDomain = await getRealmEmailDomain(systemDb, realm.id, normalized);
    481   if (!emailDomain || !emailDomain.verified) {
    482     throw conflict(
    483       'Email domain must be a verified email domain of this realm.',
    484       'domain_unavailable'
    485     );
    486   }
    487 
    488   const existing = await realmDb.get(
    489     'SELECT provider_id FROM email_domain_providers WHERE domain = {domain}',
    490     { domain: normalized }
    491   );
    492   if (existing) {
    493     if (existing.provider_id === provider.id) {
    494       return { domain: normalized, already_connected: true };
    495     }
    496     throw conflict(
    497       'This email domain is already connected to another provider.',
    498       'domain_in_use'
    499     );
    500   }
    501 
    502   try {
    503     await realmDb.run(
    504       'INSERT INTO email_domain_providers (domain, provider_id, created_at) VALUES ({domain}, {providerId}, {createdAt})',
    505       { domain: normalized, providerId: provider.id, createdAt: Date.now() }
    506     );
    507   } catch (error) {
    508     if (/UNIQUE constraint failed: email_domain_providers\.domain/.test(String(error?.message || ''))) {
    509       throw conflict(
    510         'This email domain is already connected to another provider.',
    511         'domain_in_use'
    512       );
    513     }
    514     throw error;
    515   }
    516 
    517   return { domain: normalized };
    518 }
    519 
    520 export async function disconnectAdminProviderDomain({ realmDb, slug, domain }) {
    521   const normalized = normalizeEmailDomainKey(domain);
    522   const provider = await requireAdminProvider(realmDb, slug);
    523 
    524   if (!normalized) {
    525     throw notFound('Email domain is not connected to this provider.', 'domain_not_found');
    526   }
    527   const result = await realmDb.run(
    528     'DELETE FROM email_domain_providers WHERE domain = {domain} AND provider_id = {providerId}',
    529     { domain: normalized, providerId: provider.id }
    530   );
    531   if (!result.changes) {
    532     throw notFound('Email domain is not connected to this provider.', 'domain_not_found');
    533   }
    534 
    535   return { removed: true, domain: normalized };
    536 }