/** * Authentication for the observability UI, shared by the standalone server * (`server.js`) and the embedded handler (`handler.js`). It runs after the host * guard (`host-guard.js`) and before anything else: static assets, the SSR * document, the RPC route (`/api/rpc`) and the stream route * (`/api/stream/:id`). * * Modes (`WORKFLOW_WEB_AUTH`, or the `auth.mode` option): * * - unset (`local`): no authentication, but only for loopback clients. The * client's socket address must be loopback when the server knows it, and the * `Host` header must name a loopback address. Every other request gets a * `403` telling the operator to configure authentication. * - `none`: no authentication for anyone who reaches the server. An explicit * opt-in, for deployments that sit behind their own access control. * - `jwt`: every request carries a JWT, in a header or a cookie, which is * verified against a JWKS URL, issuer and audience. For a reverse proxy or * another application's server that attaches its own signed token. * - `oidc`: an OpenID Connect authorization code login with PKCE, and an * encrypted session cookie. * * Configured but invalid settings throw from `createAuth`, so the server * refuses to start rather than serving without them. * * Access is `write` or `read`. Read access refuses the RPC methods that change * runs or hooks (see `app/lib/rpc-access.ts`); the decision travels to the * React Router app in the load context as `auth`. * * Internal: ships in the package for `server.js` and `handler.js` but is not in * the `exports` map. */ import { createHash, hkdfSync, randomBytes, timingSafeEqual, } from 'node:crypto'; import { isIP } from 'node:net'; import { createRemoteJWKSet, EncryptJWT, jwtDecrypt, jwtVerify } from 'jose'; import { matchesAllowList, parseHostHeader } from './host-guard.js'; /** Asymmetric JWS algorithms a JWKS can verify. */ export const SUPPORTED_ALGORITHMS = Object.freeze([ 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'EdDSA', ]); export const DEFAULT_CLOCK_TOLERANCE_SECONDS = 5; export const MAX_CLOCK_TOLERANCE_SECONDS = 300; export const DEFAULT_SESSION_MAX_AGE_SECONDS = 8 * 60 * 60; export const MIN_SESSION_MAX_AGE_SECONDS = 60; export const MAX_SESSION_MAX_AGE_SECONDS = 30 * 24 * 60 * 60; export const MIN_SESSION_SECRET_LENGTH = 32; export const LOGIN_TIMEOUT_SECONDS = 10 * 60; export const DEFAULT_SCOPES = Object.freeze(['openid', 'email', 'profile']); export const DEFAULT_GROUPS_CLAIM = 'groups'; export const DEFAULT_TOKEN_HEADER = 'authorization'; export const DEFAULT_COOKIE_NAME = 'workflow_web_session'; /** Longest token read from a request; longer ones are rejected unparsed. */ export const MAX_TOKEN_LENGTH = 16 * 1024; const DISCOVERY_TIMEOUT_MS = 10_000; const TOKEN_ENDPOINT_TIMEOUT_MS = 10_000; /** Paths under the basename that the `oidc` mode serves itself. */ export const AUTH_PATHS = Object.freeze({ login: '/_auth/login', callback: '/_auth/callback', logout: '/_auth/logout', }); const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']); const MODES = new Set(['none', 'jwt', 'oidc']); const SESSION_AUDIENCE = 'workflow-web:session'; const LOGIN_AUDIENCE = 'workflow-web:login'; /** * Environment variable names, by option. Every one starts with * `WORKFLOW_WEB_AUTH`, so a stray one is detectable while the mode is unset. */ export const AUTH_ENV = Object.freeze({ mode: 'WORKFLOW_WEB_AUTH', issuer: 'WORKFLOW_WEB_AUTH_ISSUER', audience: 'WORKFLOW_WEB_AUTH_AUDIENCE', jwksUrl: 'WORKFLOW_WEB_AUTH_JWKS_URL', algorithms: 'WORKFLOW_WEB_AUTH_ALGORITHMS', clockTolerance: 'WORKFLOW_WEB_AUTH_CLOCK_TOLERANCE', tokenHeader: 'WORKFLOW_WEB_AUTH_TOKEN_HEADER', tokenCookie: 'WORKFLOW_WEB_AUTH_TOKEN_COOKIE', discoveryUrl: 'WORKFLOW_WEB_AUTH_DISCOVERY_URL', clientId: 'WORKFLOW_WEB_AUTH_CLIENT_ID', clientSecret: 'WORKFLOW_WEB_AUTH_CLIENT_SECRET', redirectUri: 'WORKFLOW_WEB_AUTH_REDIRECT_URI', scopes: 'WORKFLOW_WEB_AUTH_SCOPES', sessionSecret: 'WORKFLOW_WEB_AUTH_SESSION_SECRET', sessionMaxAge: 'WORKFLOW_WEB_AUTH_SESSION_MAX_AGE', cookieName: 'WORKFLOW_WEB_AUTH_COOKIE_NAME', cookieSecure: 'WORKFLOW_WEB_AUTH_COOKIE_SECURE', allowedSubjects: 'WORKFLOW_WEB_AUTH_ALLOWED_SUBJECTS', allowedEmails: 'WORKFLOW_WEB_AUTH_ALLOWED_EMAILS', allowedDomains: 'WORKFLOW_WEB_AUTH_ALLOWED_DOMAINS', allowedGroups: 'WORKFLOW_WEB_AUTH_ALLOWED_GROUPS', groupsClaim: 'WORKFLOW_WEB_AUTH_GROUPS_CLAIM', requiredClaims: 'WORKFLOW_WEB_AUTH_REQUIRED_CLAIMS', writeGroups: 'WORKFLOW_WEB_AUTH_WRITE_GROUPS', }); /** Read access for everyone, in every mode. */ export const READ_ONLY_ENV = 'WORKFLOW_WEB_READ_ONLY'; const JWT_ONLY = ['jwksUrl', 'tokenHeader', 'tokenCookie']; const OIDC_ONLY = [ 'discoveryUrl', 'clientId', 'clientSecret', 'redirectUri', 'scopes', 'sessionSecret', 'sessionMaxAge', 'cookieName', 'cookieSecure', ]; /** Thrown by `createAuth` for a configuration it refuses to serve with. */ export class WorkflowWebAuthConfigError extends Error { /** @param {string[]} problems */ constructor(problems) { super( `Invalid workflow web UI authentication configuration:\n${problems .map((p) => ` - ${p}`) .join('\n')}` ); this.name = 'WorkflowWebAuthConfigError'; this.problems = problems; } } // --- Configuration ----------------------------------------------------------- /** * Read the auth options from environment variables, in the shape of the `auth` * option. Returns undefined when none is set. * * @param {Record} env */ export function readAuthEnv(env) { /** @type {Record} */ const out = {}; for (const [key, name] of Object.entries(AUTH_ENV)) { const value = env[name]; if (value !== undefined && value !== '') out[key] = value; } return Object.keys(out).length > 0 ? out : undefined; } /** * @param {unknown} value * @param {RegExp} [separator] * @returns {string[]} */ function toList(value, separator = /,/) { if (value === undefined || value === null) return []; const items = Array.isArray(value) ? value : String(value).split(separator); return items.map((item) => String(item).trim()).filter(Boolean); } /** * @param {unknown} value * @param {string} label * @param {string[]} problems * @returns {boolean | undefined} */ function toBoolean(value, label, problems) { if (value === undefined || value === '') return undefined; if (typeof value === 'boolean') return value; const text = String(value).trim().toLowerCase(); if (text === '1' || text === 'true') return true; if (text === '0' || text === 'false') return false; problems.push( `${label} must be true or false (or 1 or 0), got ${JSON.stringify(value)}` ); return undefined; } /** * @param {unknown} value * @param {string} label * @param {{ min: number, max: number, fallback: number }} range * @param {string[]} problems */ function toInteger(value, label, { min, max, fallback }, problems) { if (value === undefined) return fallback; const text = String(value).trim(); const parsed = typeof value === 'number' ? value : Number(text); if ( !/^\d+$/.test(text) || !Number.isInteger(parsed) || parsed < min || parsed > max ) { problems.push( `${label} must be a whole number of seconds from ${min} to ${max}, got ${JSON.stringify(value)}` ); return fallback; } return parsed; } /** Loopback host names and addresses, for which plain `http:` is accepted. */ export function isLoopbackHostname(hostname) { const name = hostname.replace(/^\[|\]$/g, '').toLowerCase(); if (name === 'localhost' || name.endsWith('.localhost')) return true; return isLoopbackAddress(name); } /** Whether an IP address is a loopback address (`127.0.0.0/8`, `::1`). */ export function isLoopbackAddress(address) { if (typeof address !== 'string') return false; let ip = address.trim().toLowerCase(); if (ip.startsWith('::ffff:')) ip = ip.slice('::ffff:'.length); if (isIP(ip) === 4) return ip.startsWith('127.'); if (isIP(ip) === 6) { return ip === '::1' || ip === '0:0:0:0:0:0:0:1'; } return false; } /** * Parse a URL the server fetches keys or endpoints from: `https:`, or `http:` * on a loopback host. * * @param {unknown} value * @param {string} label * @param {string[]} problems * @returns {URL | undefined} */ function toFetchUrl(value, label, problems) { if (value === undefined) return undefined; let url; try { url = new URL(String(value)); } catch { problems.push( `${label} must be an absolute URL, got ${JSON.stringify(value)}` ); return undefined; } if ( url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHostname(url.hostname)) ) { problems.push( `${label} must use https (http is accepted only for localhost), got ${url.href}` ); return undefined; } if (url.username || url.password) { problems.push(`${label} must not contain credentials`); return undefined; } return url; } /** * Parse `requiredClaims`: an object, or its JSON, mapping a claim to the value * or values it must have. * * @param {unknown} value * @param {string} label * @param {string[]} problems * @returns {Array<[string, string[]]>} */ function toRequiredClaims(value, label, problems) { if (value === undefined) return []; let parsed = value; if (typeof value === 'string') { try { parsed = JSON.parse(value); } catch { problems.push( `${label} must be a JSON object, such as {"environment":"production"}` ); return []; } } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { problems.push( `${label} must be an object mapping claim names to a value or a list of values` ); return []; } /** @type {Array<[string, string[]]>} */ const out = []; for (const [claim, expected] of Object.entries(parsed)) { const values = (Array.isArray(expected) ? expected : [expected]).filter( (v) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ); if (!claim || values.length === 0) { problems.push( `${label}: claim ${JSON.stringify(claim)} needs a string, number or boolean value, or a list of them` ); continue; } out.push([claim, values.map(String)]); } return out; } /** Normalize a mount path: `/` or empty -> "" (root); otherwise strip trailing slash. */ function normalizeBasename(basename) { if (!basename || basename === '/') return ''; return basename.endsWith('/') ? basename.slice(0, -1) : basename; } /** * Validate and normalize the auth configuration. * * `options.auth` replaces the `WORKFLOW_WEB_AUTH*` variables when given; * `options.readOnly` falls back to `WORKFLOW_WEB_READ_ONLY`. * * @param {{ * auth?: import('./auth-options.js').WorkflowWebAuth | 'none' | false, * readOnly?: boolean, * basename?: string, * env?: Record, * }} input */ export function resolveAuthConfig({ auth, readOnly, basename = '', env = process.env, } = {}) { /** @type {string[]} */ const problems = []; const fromEnv = auth === undefined; /** @type {Record} */ const raw = auth === false || auth === 'none' ? { mode: 'none' } : auth === undefined ? (readAuthEnv(env) ?? {}) : { ...auth }; /** @param {string} key */ const label = (key) => (fromEnv ? AUTH_ENV[key] : `auth.${key}`); const base = normalizeBasename(basename); const access = { readOnly: toBoolean( readOnly ?? env[READ_ONLY_ENV], readOnly === undefined ? READ_ONLY_ENV : 'readOnly', problems ) ?? false, }; const mode = resolveMode(raw, label, problems); if (mode !== 'jwt' && mode !== 'oidc') { if (problems.length > 0) throw new WorkflowWebAuthConfigError(problems); return { mode, basename: base, ...access }; } const unused = (mode === 'jwt' ? OIDC_ONLY : JWT_ONLY).filter( (key) => raw[key] !== undefined ); if (unused.length > 0) { problems.push( `${unused.map(label).join(', ')} ${unused.length === 1 ? 'does' : 'do'} not apply to ${label('mode')}=${mode}` ); } const common = { mode, basename: base, ...access, ...resolveVerification(raw, label, problems), policy: resolvePolicy(raw, label, problems), authorize: typeof raw.authorize === 'function' ? raw.authorize : undefined, }; if (raw.authorize !== undefined && typeof raw.authorize !== 'function') { problems.push('auth.authorize must be a function'); } const settings = mode === 'jwt' ? resolveJwt(raw, label, problems) : resolveOidc(raw, label, problems, base, common.issuer); if (problems.length > 0) throw new WorkflowWebAuthConfigError(problems); return { ...common, ...settings }; } /** * `local` when unset, else `none`, `jwt` or `oidc`. Records a problem for an * unknown mode, and for settings that the mode would ignore. * * @param {Record} raw * @param {(key: string) => string} label * @param {string[]} problems * @returns {'local' | 'none' | 'jwt' | 'oidc'} */ function resolveMode(raw, label, problems) { const stray = Object.keys(raw).filter((key) => key !== 'mode'); const names = stray.map(label).join(', '); if (raw.mode === undefined) { if (stray.length > 0) { problems.push( `${names} ${stray.length === 1 ? 'is' : 'are'} set, but ${label('mode')} is not: set it to jwt or oidc to enable authentication, or to none to serve the UI without it` ); } return 'local'; } const mode = String(raw.mode).trim().toLowerCase(); if (!MODES.has(mode)) { problems.push( `${label('mode')} must be none, jwt or oidc, got ${JSON.stringify(raw.mode)}` ); return 'local'; } if (mode === 'none' && stray.length > 0) { problems.push( `${names} ${stray.length === 1 ? 'has' : 'have'} no effect with ${label('mode')}=none: remove ${stray.length === 1 ? 'it' : 'them'}, or pick jwt or oidc` ); } return /** @type {'none' | 'jwt' | 'oidc'} */ (mode); } /** * Issuer, algorithms and clock tolerance, which both token modes check. * * @param {Record} raw * @param {(key: string) => string} label * @param {string[]} problems */ function resolveVerification(raw, label, problems) { const issuer = raw.issuer === undefined ? undefined : String(raw.issuer).trim(); if (!issuer) { problems.push(`${label('issuer')} is required`); } else { toFetchUrl(issuer, label('issuer'), problems); } const clockTolerance = toInteger( raw.clockTolerance, label('clockTolerance'), { min: 0, max: MAX_CLOCK_TOLERANCE_SECONDS, fallback: DEFAULT_CLOCK_TOLERANCE_SECONDS, }, problems ); const algorithms = toList(raw.algorithms); for (const alg of algorithms) { if (!SUPPORTED_ALGORITHMS.includes(alg)) { problems.push( `${label('algorithms')}: ${JSON.stringify(alg)} is not supported; use asymmetric algorithms only (${SUPPORTED_ALGORITHMS.join(', ')})` ); } } return { issuer, clockTolerance, algorithms: algorithms.length > 0 ? algorithms : [...SUPPORTED_ALGORITHMS], }; } /** * The allowlists, required claims and write groups. * * @param {Record} raw * @param {(key: string) => string} label * @param {string[]} problems */ function resolvePolicy(raw, label, problems) { const groupsClaim = raw.groupsClaim === undefined ? DEFAULT_GROUPS_CLAIM : String(raw.groupsClaim).trim(); if (!groupsClaim) problems.push(`${label('groupsClaim')} must not be empty`); const policy = { subjects: toList(raw.allowedSubjects), emails: toList(raw.allowedEmails).map((e) => e.toLowerCase()), domains: toList(raw.allowedDomains).map((d) => d.toLowerCase().replace(/^@/, '') ), groups: toList(raw.allowedGroups), writeGroups: toList(raw.writeGroups), groupsClaim, requiredClaims: toRequiredClaims( raw.requiredClaims, label('requiredClaims'), problems ), }; for (const domain of policy.domains) { if (domain.includes('@') || !domain.includes('.')) { problems.push( `${label('allowedDomains')} must list email domains such as example.com, got ${JSON.stringify(domain)}` ); } } for (const email of policy.emails) { if (!/^[^@\s]+@[^@\s]+$/.test(email)) { problems.push( `${label('allowedEmails')} must list email addresses, got ${JSON.stringify(email)}` ); } } return policy; } const TOKEN_CHARS = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; /** * @param {Record} raw * @param {(key: string) => string} label * @param {string[]} problems */ function resolveJwt(raw, label, problems) { const audience = toList(raw.audience); if (audience.length === 0) problems.push(`${label('audience')} is required`); if (raw.jwksUrl === undefined) { problems.push(`${label('jwksUrl')} is required`); } const jwksUrl = toFetchUrl(raw.jwksUrl, label('jwksUrl'), problems); const tokenHeader = String(raw.tokenHeader ?? DEFAULT_TOKEN_HEADER) .trim() .toLowerCase(); if (!TOKEN_CHARS.test(tokenHeader)) { problems.push( `${label('tokenHeader')} must be an HTTP header name, got ${JSON.stringify(raw.tokenHeader)}` ); } const tokenCookie = raw.tokenCookie === undefined ? undefined : String(raw.tokenCookie).trim(); if (tokenCookie !== undefined && !TOKEN_CHARS.test(tokenCookie)) { problems.push( `${label('tokenCookie')} must be a cookie name, got ${JSON.stringify(raw.tokenCookie)}` ); } return { audience, jwksUrl, tokenHeader, tokenCookie }; } /** * The redirect URI: absolute, `https` (or `http` on localhost), and the * callback path under the basename. * * @param {Record} raw * @param {(key: string) => string} label * @param {string[]} problems * @param {string} base * @returns {URL | undefined} */ function resolveRedirectUri(raw, label, problems, base) { const callback = `${base}${AUTH_PATHS.callback}`; if (raw.redirectUri === undefined) { problems.push( `${label('redirectUri')} is required: the public URL of ${callback}, as registered with your identity provider` ); return undefined; } let url; try { url = new URL(String(raw.redirectUri)); } catch { problems.push( `${label('redirectUri')} must be an absolute URL, got ${JSON.stringify(raw.redirectUri)}` ); return undefined; } const loopbackHttp = url.protocol === 'http:' && isLoopbackHostname(url.hostname); if (url.protocol !== 'https:' && !loopbackHttp) { problems.push( `${label('redirectUri')} must use https (http is accepted only for localhost), got ${url.href}` ); } if (url.pathname !== callback) { problems.push( `${label('redirectUri')} must end in the UI's callback path ${callback}, got ${url.pathname}` ); } if (url.search || url.hash || url.username || url.password) { problems.push( `${label('redirectUri')} must not have a query, fragment or credentials` ); } return url; } /** * Session secrets, lifetime and cookie settings. * * @param {Record} raw * @param {(key: string) => string} label * @param {string[]} problems * @param {URL | undefined} redirectUri */ function resolveSession(raw, label, problems, redirectUri) { const sessionSecrets = toList(raw.sessionSecret); if (sessionSecrets.length === 0) { problems.push( `${label('sessionSecret')} is required: at least ${MIN_SESSION_SECRET_LENGTH} random characters, for example from \`openssl rand -base64 32\`` ); } else if (sessionSecrets.some((s) => s.length < MIN_SESSION_SECRET_LENGTH)) { problems.push( `${label('sessionSecret')}: every secret must be at least ${MIN_SESSION_SECRET_LENGTH} characters` ); } const sessionMaxAge = toInteger( raw.sessionMaxAge, label('sessionMaxAge'), { min: MIN_SESSION_MAX_AGE_SECONDS, max: MAX_SESSION_MAX_AGE_SECONDS, fallback: DEFAULT_SESSION_MAX_AGE_SECONDS, }, problems ); const cookieSecure = toBoolean(raw.cookieSecure, label('cookieSecure'), problems) ?? redirectUri?.protocol !== 'http:'; if (redirectUri?.protocol === 'https:' && !cookieSecure) { problems.push( `${label('cookieSecure')} cannot be false when ${label('redirectUri')} uses https` ); } let cookieName = raw.cookieName === undefined ? `${cookieSecure ? '__Host-' : ''}${DEFAULT_COOKIE_NAME}` : String(raw.cookieName).trim(); if (!TOKEN_CHARS.test(cookieName)) { problems.push( `${label('cookieName')} must be a cookie name, got ${JSON.stringify(raw.cookieName)}` ); cookieName = DEFAULT_COOKIE_NAME; } if (/^__(Host|Secure)-/.test(cookieName) && !cookieSecure) { problems.push( `${label('cookieName')}: a __Host- or __Secure- cookie needs ${label('cookieSecure')}` ); } return { sessionSecrets, sessionMaxAge, cookieName, cookieSecure }; } /** * @param {Record} raw * @param {(key: string) => string} label * @param {string[]} problems * @param {string} base * @param {string | undefined} issuer */ function resolveOidc(raw, label, problems, base, issuer) { if (toList(raw.audience).length > 0) { problems.push( `${label('audience')} does not apply to ${label('mode')}=oidc: ID tokens are checked against ${label('clientId')}` ); } const clientId = String(raw.clientId ?? '').trim(); if (!clientId) problems.push(`${label('clientId')} is required`); const discoveryUrl = raw.discoveryUrl !== undefined ? toFetchUrl(raw.discoveryUrl, label('discoveryUrl'), problems) : issuer && safeUrl( `${issuer.replace(/\/+$/, '')}/.well-known/openid-configuration` ); const redirectUri = resolveRedirectUri(raw, label, problems, base); const scopes = toList(raw.scopes ?? DEFAULT_SCOPES, /[\s,]+/); if (!scopes.includes('openid')) scopes.unshift('openid'); return { clientId, clientSecret: raw.clientSecret === undefined ? undefined : String(raw.clientSecret), discoveryUrl: discoveryUrl || undefined, redirectUri: redirectUri?.href, scopes, ...resolveSession(raw, label, problems, redirectUri), }; } function safeUrl(value) { try { return new URL(value); } catch { return undefined; } } // --- Authorization ----------------------------------------------------------- /** * @param {Record} claims * @param {string} claim * @returns {string[]} */ function claimValues(claims, claim) { const value = claims[claim]; if (Array.isArray(value)) return value.map(String); if (value === undefined || value === null) return []; if (typeof value === 'string') return value.split(/[\s,]+/).filter(Boolean); return [String(value)]; } /** * Decide whether verified claims may use the UI, and with which access. * Required claims must all match. When any allowlist is set, the claims must * match at least one entry of one of them. Emails count only with * `email_verified: true`. * * @param {Record} claims * @param {ReturnType} config * @returns {Promise<{ ok: true, access: 'read' | 'write' } | { ok: false, reason: string }>} */ export async function authorizeClaims(claims, config) { const { policy } = config; for (const [claim, expected] of policy.requiredClaims) { const actual = Array.isArray(claims[claim]) ? claims[claim].map(String) : claims[claim] === undefined || claims[claim] === null ? [] : [String(claims[claim])]; if (!actual.some((value) => expected.includes(value))) { return { ok: false, reason: `claim ${claim} does not have a required value`, }; } } const groups = claimValues(claims, policy.groupsClaim); const hasAllowlist = policy.subjects.length + policy.emails.length + policy.domains.length + policy.groups.length > 0; if (hasAllowlist) { const sub = typeof claims.sub === 'string' ? claims.sub : undefined; const email = typeof claims.email === 'string' && (claims.email_verified === true || claims.email_verified === 'true') ? claims.email.toLowerCase() : undefined; const domain = email?.slice(email.lastIndexOf('@') + 1); const allowed = (sub !== undefined && policy.subjects.includes(sub)) || (email !== undefined && policy.emails.includes(email)) || (domain !== undefined && policy.domains.includes(domain)) || groups.some((group) => policy.groups.includes(group)); if (!allowed) return { ok: false, reason: 'not in the allowlist' }; } /** @type {'read' | 'write'} */ let access = policy.writeGroups.length > 0 && !groups.some((group) => policy.writeGroups.includes(group)) ? 'read' : 'write'; if (config.authorize) { const decision = await config.authorize(claims, { access }); if (decision === false || decision === undefined || decision === null) { return { ok: false, reason: 'refused by auth.authorize' }; } if (decision === 'read' || decision === 'write') access = decision; else if (decision !== true) { return { ok: false, reason: 'auth.authorize returned an unknown value' }; } } if (config.readOnly) access = 'read'; return { ok: true, access }; } /** * The parts of the configuration a session's authorization depends on. A * session records it at login, so changing the policy signs everyone out. */ function policyFingerprint(config) { return createHash('sha256') .update( JSON.stringify([ config.issuer, config.clientId, config.policy, config.readOnly, config.authorize ? String(config.authorize) : null, ]) ) .digest('base64url') .slice(0, 22); } // --- Request helpers --------------------------------------------------------- /** @param {string | null} header */ export function parseCookies(header) { /** @type {Map} */ const cookies = new Map(); if (!header) return cookies; for (const part of header.split(';')) { const eq = part.indexOf('='); if (eq === -1) continue; const name = part.slice(0, eq).trim(); if (!name || cookies.has(name)) continue; let value = part.slice(eq + 1).trim(); if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1); cookies.set(name, value); } return cookies; } /** * @param {string} name * @param {string} value * @param {{ maxAge: number, secure: boolean }} options */ function serializeCookie(name, value, { maxAge, secure }) { return `${name}=${value}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${secure ? '; Secure' : ''}`; } /** `__Host-name` -> `__Host-name_login`, keeping the prefix's rules. */ function loginCookieName(name) { return `${name}_login`; } /** * The client's address, when the server exposes it: srvx's `ip`, which the * standalone server and srvx-based hosts set. It is the socket's address, * unless the host server configures srvx's `trustProxy`, in which case it is * the client a trusted proxy forwarded for. The UI never reads a forwarded * header itself. * * @param {Request} request * @returns {string | undefined} */ function clientAddress(request) { const ip = /** @type {any} */ (request).ip; return typeof ip === 'string' && ip !== '' ? ip : undefined; } function isHtmlNavigation(request, url, basename) { if (request.method !== 'GET' && request.method !== 'HEAD') return false; if (url.pathname.startsWith(`${basename}/api/`)) return false; if (url.pathname.endsWith('.data')) return false; const accept = request.headers.get('accept') ?? ''; return accept.includes('text/html'); } /** * Where a login may send the browser back to: a path under the basename on * this origin, never another origin and never an auth route. * * @param {string | null | undefined} raw * @param {string} basename */ export function sanitizeReturnTo(raw, basename) { const fallback = `${basename}/`; if (typeof raw !== 'string' || raw === '' || raw.length > 2048) return fallback; if (!raw.startsWith('/') || raw.startsWith('//') || raw.includes('\\')) return fallback; // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting them is the point if (/[\u0000-\u001f\u007f]/.test(raw)) return fallback; const sentinel = 'http://return-to.invalid'; let url; try { url = new URL(raw, sentinel); } catch { return fallback; } if (url.origin !== sentinel) return fallback; const path = url.pathname; // Dot segments normalize away (`/.//evil.example.com` becomes // `//evil.example.com`), so the normalized path is checked again: a // `Location` starting with `//` is another origin. if (path.startsWith('//')) return fallback; if (basename && path !== basename && !path.startsWith(`${basename}/`)) return fallback; if (path.startsWith(`${basename}/_auth/`)) return fallback; return path + url.search; } function escapeHtml(text) { return String(text).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); } const NO_STORE = { 'cache-control': 'no-store' }; function textResponse(status, message, headers = {}) { return new Response(`${message}\n`, { status, headers: { 'content-type': 'text/plain; charset=utf-8', ...NO_STORE, ...headers, }, }); } function htmlResponse(status, title, bodyHtml, headers) { const html = `${escapeHtml(title)}

${escapeHtml(title)}

${bodyHtml}`; const h = new Headers(headers); h.set('content-type', 'text/html; charset=utf-8'); h.set('cache-control', 'no-store'); h.set( 'content-security-policy', "default-src 'none'; style-src 'unsafe-inline'" ); h.set('referrer-policy', 'no-referrer'); return new Response(html, { status, headers: h }); } function redirect(location, status, headers) { const h = new Headers(headers); h.set('location', location); h.set('cache-control', 'no-store'); h.set('referrer-policy', 'no-referrer'); return new Response(null, { status, headers: h }); } /** * Credentials a browser attaches on its own (cookies) need a same-origin * check on writes, even when the host guard accepts any host name. * * @param {Request} request * @param {string[] | true} allowedHosts */ function isCrossSiteWrite(request, allowedHosts) { if (SAFE_METHODS.has(request.method)) return false; const site = request.headers.get('sec-fetch-site'); if (site && site !== 'same-origin' && site !== 'none') return true; const origin = request.headers.get('origin'); if (!origin) return true; let originHost; try { originHost = new URL(origin).host.toLowerCase(); } catch { return true; } if (originHost === request.headers.get('host')?.toLowerCase()) return false; return !( Array.isArray(allowedHosts) && matchesAllowList(parseHostHeader(originHost) ?? '', allowedHosts) ); } // --- Logging ----------------------------------------------------------------- const lastLogged = new Map(); const LOG_INTERVAL_MS = 60_000; /** One line per reason per minute, so a scanner cannot flood the log. */ function logRejection(reason) { const now = Date.now(); if ((lastLogged.get(reason) ?? 0) + LOG_INTERVAL_MS > now) return; lastLogged.set(reason, now); console.warn(`[workflow-web] request rejected: ${reason}`); } // --- Modes ------------------------------------------------------------------- /** * @typedef {{ mode: string, access: 'read' | 'write', subject?: string, email?: string, name?: string }} AuthContext * @typedef {{ response: Response } | { context: AuthContext }} AuthResult */ /** * Build the auth layer. Throws `WorkflowWebAuthConfigError` for an invalid * configuration, and, in `oidc` mode, when the provider's discovery document * cannot be read or does not match the issuer. * * @param {Parameters[0] & { fetch?: typeof fetch }} input */ export async function createAuth(input = {}) { const config = resolveAuthConfig(input); const fetchImpl = input.fetch ?? globalThis.fetch; const access = config.readOnly ? 'read' : 'write'; if (config.mode === 'local' || config.mode === 'none') { const mode = config.mode; return { config, describe: mode === 'none' ? `authentication disabled (WORKFLOW_WEB_AUTH=none): anyone who can reach this server can ${config.readOnly ? 'read' : 'read and change'} workflow runs` : 'no authentication configured: serving loopback clients only (set WORKFLOW_WEB_AUTH to jwt or oidc to serve other clients)', /** @param {Request} request @returns {Promise} */ async handle(request) { if (mode === 'local' && !isLocalRequest(request)) { logRejection( 'non-loopback client while no authentication is configured' ); return { response: textResponse( 403, 'Forbidden: the workflow web UI serves only loopback clients until authentication is configured. ' + 'Set WORKFLOW_WEB_AUTH to jwt or oidc, or to none to serve it without authentication.' ), }; } return { context: { mode, access } }; }, }; } if (config.mode === 'jwt') return createJwtAuth(config); return createOidcAuth(config, fetchImpl); } /** @param {Request} request */ function isLocalRequest(request) { const ip = clientAddress(request); if (ip !== undefined && !isLoopbackAddress(ip)) return false; const host = parseHostHeader(request.headers.get('host')); return host !== undefined && isLoopbackHostname(host); } function verifyOptions(config, audience) { return { issuer: config.issuer, audience, algorithms: config.algorithms, clockTolerance: config.clockTolerance, requiredClaims: ['exp'], }; } function toContext(mode, claims, access) { return { mode, access, subject: typeof claims.sub === 'string' ? claims.sub : undefined, email: typeof claims.email === 'string' ? claims.email : undefined, name: typeof claims.name === 'string' ? claims.name : undefined, }; } /** @param {ReturnType} config */ function createJwtAuth(config) { const jwks = createRemoteJWKSet(config.jwksUrl); const unauthorized = (error) => textResponse(401, 'Unauthorized', { 'www-authenticate': `Bearer realm="workflow-web"${error ? `, error="${error}"` : ''}`, }); /** @param {Request} request */ function readToken(request) { const header = request.headers.get(config.tokenHeader); if (header) { const match = /^Bearer\s+(.+)$/i.exec(header.trim()); if (match) return { token: match[1].trim(), via: 'header' }; // `Authorization` carries a scheme; a custom header may carry the bare token. if (config.tokenHeader !== 'authorization') return { token: header.trim(), via: 'header' }; return undefined; } if (config.tokenCookie) { const value = parseCookies(request.headers.get('cookie')).get( config.tokenCookie ); if (value) return { token: value, via: 'cookie' }; } return undefined; } return { config, describe: `JWT (issuer ${config.issuer}, audience ${config.audience.join(', ')}, keys ${config.jwksUrl.href}, token from the ${config.tokenHeader} header${config.tokenCookie ? ` or the ${config.tokenCookie} cookie` : ''})${config.readOnly ? ', read-only' : ''}`, /** * @param {Request} request * @param {{ allowedHosts?: string[] | true }} [options] * @returns {Promise} */ async handle(request, { allowedHosts = [] } = {}) { const found = readToken(request); if (!found) { logRejection('no token'); return { response: unauthorized() }; } if (found.token.length > MAX_TOKEN_LENGTH) { logRejection('token too long'); return { response: unauthorized('invalid_token') }; } let claims; try { ({ payload: claims } = await jwtVerify( found.token, jwks, verifyOptions(config, config.audience) )); } catch (error) { logRejection( `invalid token (${error?.code ?? error?.name ?? 'error'})` ); return { response: unauthorized('invalid_token') }; } const decision = await authorizeClaims(claims, config); if (!decision.ok) { logRejection(`token ${decision.reason}`); return { response: textResponse(403, 'Forbidden') }; } if (found.via === 'cookie' && isCrossSiteWrite(request, allowedHosts)) { logRejection('cross-site write with a cookie token'); return { response: textResponse(403, 'Forbidden: cross-origin request'), }; } return { context: toContext('jwt', claims, decision.access) }; }, }; } /** * Derive the cookie encryption key for each session secret. The first seals * new cookies; every one opens existing ones, for rotation. * * @param {string[]} secrets */ function sessionKeys(secrets) { return secrets.map( (secret) => new Uint8Array( hkdfSync('sha256', secret, 'workflow-web', 'session cookie A256GCM', 32) ) ); } function randomToken() { return randomBytes(32).toString('base64url'); } function sameString(a, b) { if (typeof a !== 'string' || typeof b !== 'string') return false; const left = Buffer.from(a); const right = Buffer.from(b); return left.length === right.length && timingSafeEqual(left, right); } async function fetchJson(fetchImpl, url, init, timeoutMs, what) { const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs), }); if (!response.ok) { throw new Error(`${what} returned HTTP ${response.status}`); } try { return await response.json(); } catch { throw new Error(`${what} did not return JSON`); } } /** * Read and check the provider's discovery document. * * @param {ReturnType} config * @param {typeof fetch} fetchImpl */ async function discover(config, fetchImpl) { let doc; try { doc = await fetchJson( fetchImpl, config.discoveryUrl, { headers: { accept: 'application/json' } }, DISCOVERY_TIMEOUT_MS, `OIDC discovery (${config.discoveryUrl.href})` ); } catch (error) { throw new WorkflowWebAuthConfigError([ `could not read the OIDC discovery document: ${error instanceof Error ? error.message : String(error)}`, ]); } /** @type {string[]} */ const problems = []; if (doc?.issuer !== config.issuer) { problems.push( `the discovery document's issuer ${JSON.stringify(doc?.issuer)} does not equal the configured issuer ${JSON.stringify(config.issuer)}` ); } const endpoints = {}; for (const key of ['authorization_endpoint', 'token_endpoint', 'jwks_uri']) { if (typeof doc?.[key] !== 'string') { problems.push(`the discovery document has no ${key}`); continue; } endpoints[key] = toFetchUrl(doc[key], `discovery ${key}`, problems); } const methods = doc?.code_challenge_methods_supported; if (Array.isArray(methods) && !methods.includes('S256')) { problems.push('the provider does not support PKCE with S256'); } const authMethods = Array.isArray(doc?.token_endpoint_auth_methods_supported) ? doc.token_endpoint_auth_methods_supported : ['client_secret_basic']; let tokenAuth = 'none'; if (config.clientSecret !== undefined) { if (authMethods.includes('client_secret_basic')) tokenAuth = 'client_secret_basic'; else if (authMethods.includes('client_secret_post')) tokenAuth = 'client_secret_post'; else problems.push( 'the provider supports neither client_secret_basic nor client_secret_post' ); } const signingAlgs = Array.isArray(doc?.id_token_signing_alg_values_supported) ? doc.id_token_signing_alg_values_supported : undefined; const algorithms = signingAlgs ? config.algorithms.filter((alg) => signingAlgs.includes(alg)) : config.algorithms; if (algorithms.length === 0) { problems.push( `none of the provider's ID token algorithms (${signingAlgs?.join(', ')}) is allowed` ); } if (problems.length > 0) throw new WorkflowWebAuthConfigError(problems); return { authorizationEndpoint: endpoints.authorization_endpoint, tokenEndpoint: endpoints.token_endpoint, jwksUri: endpoints.jwks_uri, tokenAuth, algorithms, issParamSupported: doc?.authorization_response_iss_parameter_supported === true, }; } /** * @param {ReturnType} config * @param {typeof fetch} fetchImpl */ async function createOidcAuth(config, fetchImpl) { const provider = await discover(config, fetchImpl); const jwks = createRemoteJWKSet(provider.jwksUri); const keys = sessionKeys(config.sessionSecrets); const fingerprint = policyFingerprint(config); const base = config.basename; const loginCookie = loginCookieName(config.cookieName); const paths = { login: `${base}${AUTH_PATHS.login}`, callback: `${base}${AUTH_PATHS.callback}`, logout: `${base}${AUTH_PATHS.logout}`, }; const cookie = (name, value, maxAge) => serializeCookie(name, value, { maxAge, secure: config.cookieSecure }); const clear = (name) => cookie(name, '', 0); async function seal(payload, audience, maxAge) { return new EncryptJWT(payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .setIssuedAt() .setExpirationTime(Math.floor(Date.now() / 1000) + maxAge) .setAudience(audience) .encrypt(keys[0]); } async function open(token, audience) { if (!token || token.length > MAX_TOKEN_LENGTH) return undefined; for (const key of keys) { try { const { payload } = await jwtDecrypt(token, key, { audience, keyManagementAlgorithms: ['dir'], contentEncryptionAlgorithms: ['A256GCM'], }); return payload; } catch { // Try the next key: rotation keeps old secrets after the first. } } return undefined; } function errorPage(status, title, message, headers) { return htmlResponse( status, title, `

${escapeHtml(message)}

Sign in again

`, headers ); } /** @param {URL} url */ async function login(url) { const state = randomToken(); const nonce = randomToken(); const verifier = randomToken(); const returnTo = sanitizeReturnTo(url.searchParams.get('returnTo'), base); const target = new URL(provider.authorizationEndpoint); target.searchParams.set('response_type', 'code'); target.searchParams.set('client_id', config.clientId); target.searchParams.set('redirect_uri', config.redirectUri); target.searchParams.set('scope', config.scopes.join(' ')); target.searchParams.set('state', state); target.searchParams.set('nonce', nonce); target.searchParams.set( 'code_challenge', createHash('sha256').update(verifier).digest('base64url') ); target.searchParams.set('code_challenge_method', 'S256'); const sealed = await seal( { state, nonce, verifier, returnTo }, LOGIN_AUDIENCE, LOGIN_TIMEOUT_SECONDS ); return redirect(target.href, 302, { 'set-cookie': cookie(loginCookie, sealed, LOGIN_TIMEOUT_SECONDS), }); } async function exchangeCode(code, verifier) { const body = new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: config.redirectUri, code_verifier: verifier, }); const headers = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json', }; if (provider.tokenAuth === 'client_secret_basic') { // RFC 6749 section 2.3.1: form-encode both parts before base64. const encode = (v) => encodeURIComponent(v).replace(/%20/g, '+'); headers.authorization = `Basic ${Buffer.from(`${encode(config.clientId)}:${encode(config.clientSecret)}`).toString('base64')}`; } else { body.set('client_id', config.clientId); if (provider.tokenAuth === 'client_secret_post') { body.set('client_secret', config.clientSecret); } } const tokens = await fetchJson( fetchImpl, provider.tokenEndpoint, { method: 'POST', headers, body, redirect: 'error' }, TOKEN_ENDPOINT_TIMEOUT_MS, 'the token endpoint' ); if (typeof tokens?.id_token !== 'string') { throw new Error('the token endpoint returned no id_token'); } return tokens.id_token; } /** @param {Request} request @param {URL} url */ async function callback(request, url) { const clearLogin = { 'set-cookie': clear(loginCookie) }; const pending = await open( parseCookies(request.headers.get('cookie')).get(loginCookie), LOGIN_AUDIENCE ); if (!pending) { logRejection('sign-in callback without a pending sign-in'); return errorPage( 400, 'Sign-in expired', 'This sign-in started too long ago, or in another browser. Start again.', clearLogin ); } if (!sameString(url.searchParams.get('state') ?? '', pending.state)) { logRejection('sign-in callback with a mismatched state'); return errorPage( 400, 'Sign-in failed', 'The sign-in response does not match this browser. Start again.', clearLogin ); } // RFC 9207: a provider that names itself must name the configured issuer, // and one advertising iss parameter support must include it. const iss = url.searchParams.get('iss'); if ( (iss !== null && iss !== config.issuer) || (provider.issParamSupported && iss === null) ) { logRejection('sign-in callback from another issuer'); return errorPage( 400, 'Sign-in failed', 'The sign-in response came from an unexpected identity provider.', clearLogin ); } const error = url.searchParams.get('error'); if (error) { const sanitizeLog = (value, max = 200) => String(value ?? '') // biome-ignore lint/suspicious/noControlCharactersInRegex: stripping control chars prevents log injection .replace(/[\u0000-\u001f\u007f]+/g, ' ') .slice(0, max); console.warn( `[workflow-web] identity provider returned an error: ${sanitizeLog(error, 100)}: ${sanitizeLog(url.searchParams.get('error_description'))}` ); return errorPage( 401, 'Sign-in failed', `The identity provider returned: ${error.slice(0, 100)}`, clearLogin ); } const code = url.searchParams.get('code'); if (!code) return errorPage( 400, 'Sign-in failed', 'The sign-in response has no authorization code.', clearLogin ); let claims; try { const idToken = await exchangeCode(code, pending.verifier); ({ payload: claims } = await jwtVerify(idToken, jwks, { ...verifyOptions( { ...config, algorithms: provider.algorithms }, config.clientId ), requiredClaims: ['exp', 'iat', 'sub'], })); if (!sameString(claims.nonce, pending.nonce)) throw new Error('nonce mismatch'); if ( Array.isArray(claims.aud) && claims.aud.length > 1 && claims.azp !== config.clientId ) throw new Error('azp required for multiple audiences'); if (claims.azp !== undefined && claims.azp !== config.clientId) throw new Error('azp mismatch'); } catch (err) { console.warn( `[workflow-web] sign-in failed: ${err instanceof Error ? err.message : String(err)}` ); return errorPage( 401, 'Sign-in failed', 'The identity provider’s response could not be verified.', clearLogin ); } const decision = await authorizeClaims(claims, config); if (!decision.ok) { console.warn( `[workflow-web] sign-in refused for ${claims.sub}: ${decision.reason}` ); return errorPage( 403, 'Access denied', 'Your account is not allowed to use this workflow dashboard.', clearLogin ); } const context = toContext('oidc', claims, decision.access); const session = await seal( { sub: context.subject, email: context.email, name: context.name, access: decision.access, cfg: fingerprint, }, SESSION_AUDIENCE, config.sessionMaxAge ); console.info( `[workflow-web] signed in ${context.subject} with ${decision.access} access` ); const headers = new Headers(); headers.append('set-cookie', clear(loginCookie)); headers.append( 'set-cookie', cookie(config.cookieName, session, config.sessionMaxAge) ); return redirect(pending.returnTo, 303, headers); } return { config, provider, describe: `OIDC (issuer ${config.issuer}, client ${config.clientId}, callback ${config.redirectUri})${config.readOnly ? ', read-only' : ''}`, /** * @param {Request} request * @param {{ allowedHosts?: string[] | true }} [options] * @returns {Promise} */ async handle(request, { allowedHosts = [] } = {}) { const url = new URL(request.url); if (url.pathname === paths.login || url.pathname === paths.callback) { if (request.method !== 'GET') { return { response: textResponse(405, 'Method Not Allowed', { allow: 'GET' }), }; } return { response: url.pathname === paths.login ? await login(url) : await callback(request, url), }; } if (url.pathname === paths.logout) { return { response: htmlResponse( 200, 'Signed out', `

Sign in again

`, { 'set-cookie': clear(config.cookieName), } ), }; } const session = await open( parseCookies(request.headers.get('cookie')).get(config.cookieName), SESSION_AUDIENCE ); if ( !session || session.cfg !== fingerprint || (session.access !== 'read' && session.access !== 'write') ) { if (isHtmlNavigation(request, url, base)) { const returnTo = sanitizeReturnTo(url.pathname + url.search, base); return { response: redirect( `${paths.login}?returnTo=${encodeURIComponent(returnTo)}`, 302 ), }; } return { response: textResponse(401, 'Unauthorized: sign in again') }; } if (isCrossSiteWrite(request, allowedHosts)) { logRejection('cross-site write with a session cookie'); return { response: textResponse(403, 'Forbidden: cross-origin request'), }; } return { context: { mode: 'oidc', access: config.readOnly ? 'read' : session.access, subject: typeof session.sub === 'string' ? session.sub : undefined, email: typeof session.email === 'string' ? session.email : undefined, name: typeof session.name === 'string' ? session.name : undefined, }, }; }, }; }