From ad2cacf0949f9d034919a6efac828c41a382a385 Mon Sep 17 00:00:00 2001 From: William Mantly Date: Wed, 15 Jul 2026 00:41:16 -0400 Subject: [PATCH] Make basic auth and SSO mutually exclusive per host; fix silently-broken validation errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Auth tab is now a single choice (Off / Basic auth / SSO) instead of two independent toggles that could both be on at once, which made it ambiguous which gate actually protected a request. Enforced both in the UI and server-side (POST/PUT), accounting for partial PUT updates against the existing record. - Add per-user basic-auth management (change password, delete) so an admin no longer has to blow away and retype the whole user list to remove or rotate one account. - Fix: `Model.errors.ObjectValidateError(...)` is a constructor and was being called without `new` everywhere in this codebase. Without `new`, `this` inside it was the module's shared `errors` object (mutated in place) and the call evaluated to `undefined` — so every `throw Model.errors.ObjectValidateError(...)` actually threw `undefined`, which Express's `next(undefined)` treats as "no error" and silently falls through to the catch-all 404 handler. Every host/user/group/ permission/dns-provider validation error (bad hostname, bad IP, etc.) was showing a confusing "Page not found" instead of the real message. Co-Authored-By: Claude Sonnet 5 --- nodejs/models/dns_provider.js | 2 +- nodejs/models/host.js | 2 +- nodejs/models/local_group.js | 4 +- nodejs/models/permission.js | 4 +- nodejs/routes/host.js | 61 ++++++++++- nodejs/routes/render.js | 10 +- nodejs/routes/user.js | 2 +- nodejs/views/hosts.ejs | 190 ++++++++++++++++++++++++---------- 8 files changed, 209 insertions(+), 66 deletions(-) diff --git a/nodejs/models/dns_provider.js b/nodejs/models/dns_provider.js index 172317e..636aab9 100644 --- a/nodejs/models/dns_provider.js +++ b/nodejs/models/dns_provider.js @@ -176,7 +176,7 @@ class DnsProvider extends Table{ for(let key in Provider._keyMap){ keys.push({'key': key, message: 'Invalid Key'}) } - throw this.errors.ObjectValidateError(keys, "API rejected key"); + throw new this.errors.ObjectValidateError(keys, "API rejected key"); } // Don't swallow other failures (e.g. a domain-sync validation error): // returning undefined here made the route crash on `item.id` with an diff --git a/nodejs/models/host.js b/nodejs/models/host.js index e6d7fb7..445bf06 100755 --- a/nodejs/models/host.js +++ b/nodejs/models/host.js @@ -189,7 +189,7 @@ class Host extends Table{ }catch(error){ console.log('validateWildcardCreate error', error) if(error.status === 404) error.message = "No matching DNS provider registered" - throw this.errors.ObjectValidateError([{key: 'host', message: error.message}]); + throw new this.errors.ObjectValidateError([{key: 'host', message: error.message}]); } } diff --git a/nodejs/models/local_group.js b/nodejs/models/local_group.js index f8a83f1..fa3c75f 100644 --- a/nodejs/models/local_group.js +++ b/nodejs/models/local_group.js @@ -30,7 +30,7 @@ class LocalGroup extends Table{ static async create(data){ data.name = this.slug(data.name); if(!data.name){ - throw this.errors.ObjectValidateError([{key: 'name', message: 'A group name is required.'}]); + throw new this.errors.ObjectValidateError([{key: 'name', message: 'A group name is required.'}]); } if(!Array.isArray(data.members)) data.members = []; return super.create(data); @@ -39,7 +39,7 @@ class LocalGroup extends Table{ async addMember(username){ username = String(username || '').trim(); if(!username){ - throw this.constructor.errors.ObjectValidateError([{key: 'username', message: 'A username is required.'}]); + throw new this.constructor.errors.ObjectValidateError([{key: 'username', message: 'A username is required.'}]); } let members = Array.isArray(this.members) ? this.members : []; if(members.includes(username)) return this; diff --git a/nodejs/models/permission.js b/nodejs/models/permission.js index 2287366..99b2c09 100644 --- a/nodejs/models/permission.js +++ b/nodejs/models/permission.js @@ -55,10 +55,10 @@ class Permission extends Table{ static async create(data){ if(!this.roles.includes(data.role)){ - throw this.errors.ObjectValidateError([{key: 'role', message: `role must be one of ${this.roles.join(', ')}`}]); + throw new this.errors.ObjectValidateError([{key: 'role', message: `role must be one of ${this.roles.join(', ')}`}]); } if(!['user', 'group'].includes(data.subjectType)){ - throw this.errors.ObjectValidateError([{key: 'subjectType', message: `subjectType must be 'user' or 'group'`}]); + throw new this.errors.ObjectValidateError([{key: 'subjectType', message: `subjectType must be 'user' or 'group'`}]); } if(data.scope === 'global') data.domain = '*'; data.id = this.mkId(data); diff --git a/nodejs/routes/host.js b/nodejs/routes/host.js index ccfe75d..c93e1f4 100755 --- a/nodejs/routes/host.js +++ b/nodejs/routes/host.js @@ -6,7 +6,7 @@ const {Host, Domain, User} = require('../models').models; const {LocalGroup} = require('../models/local_group'); const {Permission} = require('../models/permission'); const authz = require('../middleware/authz'); -const {normalizeHostFeatures} = require('../utils/host_features'); +const {normalizeHostFeatures, sanitizeBasicAuthObject} = require('../utils/host_features'); const {collectHostFieldErrors} = require('../utils/hostname_validate'); const {hashBasicAuthUsers} = require('../utils/basicauth'); @@ -16,7 +16,22 @@ const Model = Host; // ObjectValidateError (per-field keys) that the frontend surfaces inline. function validateHostFields(body){ let errors = collectHostFieldErrors(body); - if(errors.length) throw Model.errors.ObjectValidateError(errors); + if(errors.length) throw new Model.errors.ObjectValidateError(errors); +} + +// Basic auth and SSO are mutually exclusive per host (having both enabled +// invites confusion about which gate actually protected a request). `existing` +// is the current record (undefined on create), so a partial PUT that only +// touches one of the two fields is still checked against the other's current +// value. +function validateAuthExclusivity(body, existing){ + let basic = 'basicauth_enabled' in body ? body.basicauth_enabled : (existing ? existing.basicauth_enabled : false); + let sso = 'sso_enabled' in body ? body.sso_enabled : (existing ? existing.sso_enabled : false); + if(basic && sso){ + throw new Model.errors.ObjectValidateError([ + {key: 'sso_enabled', message: 'Basic auth and SSO cannot both be enabled for the same host — pick one.'}, + ]); + } } // After normalizeHostFeatures has parsed basic-auth creds to {user: plaintext}, @@ -73,6 +88,7 @@ router.post('/', authz.requireDomainRole('manager', authz.resolve.hostBody), asy req.body.created_by = authz.reqUsername(req); validateHostFields(req.body); normalizeHostFeatures(req.body); + validateAuthExclusivity(req.body); hashHostSecrets(req.body); let item = await Model.create(req.body); @@ -139,9 +155,10 @@ router.put('/:item', authz.requireDomainRole('manager', authz.resolve.hostParam) req.body.updated_by = authz.reqUsername(req); validateHostFields(req.body); normalizeHostFeatures(req.body); + let existing = await Model.get(req.params.item); + validateAuthExclusivity(req.body, existing); hashHostSecrets(req.body); - let item = await Model.get(req.params.item); - item = await item.update(req.body); + let item = await existing.update(req.body); return res.json({ message: `"${req.params.item}" updated.`, @@ -170,6 +187,42 @@ router.delete('/:item', authz.requireDomainRole('manager', authz.resolve.hostPar } }); +// Manage a single basic-auth user without replacing the whole list — the bulk +// PUT /:item endpoint always replaces basicauth_users wholesale (an empty +// textarea there means "leave existing users untouched", see +// normalizeHostFeatures), which makes deleting or rotating one user's +// password error-prone from that form. These two routes touch exactly one key. +router.put('/:item/basicauth-user/:username', authz.requireDomainRole('manager', authz.resolve.hostParam), async function(req, res, next){ + try{ + let item = await Model.get(req.params.item); + let sanitized = sanitizeBasicAuthObject({[req.params.username]: req.body.password}); + let username = Object.keys(sanitized)[0]; + if(!username){ + throw new Model.errors.ObjectValidateError([{key: 'password', message: 'Invalid username or empty password.'}]); + } + + let users = Object.assign({}, item.basicauth_users, hashBasicAuthUsers(sanitized)); + item = await item.update({basicauth_users: users, updated_by: authz.reqUsername(req)}); + + return res.json({message: `User "${username}" saved.`, ...item}); + }catch(error){ + next(error); + } +}); + +router.delete('/:item/basicauth-user/:username', authz.requireDomainRole('manager', authz.resolve.hostParam), async function(req, res, next){ + try{ + let item = await Model.get(req.params.item); + let users = Object.assign({}, item.basicauth_users); + delete users[req.params.username]; + item = await item.update({basicauth_users: users, updated_by: authz.reqUsername(req)}); + + return res.json({message: `User "${req.params.username}" removed.`, ...item}); + }catch(error){ + next(error); + } +}); + router.put('/:item/renew', authz.requireDomainRole('manager', authz.resolve.hostParam), async function(req, res, next){ try{ let item = await Model.get(req.params.item); diff --git a/nodejs/routes/render.js b/nodejs/routes/render.js index f3dea9c..17235ba 100644 --- a/nodejs/routes/render.js +++ b/nodejs/routes/render.js @@ -19,13 +19,17 @@ const frontEndModules = ['bootstrap', 'mustache', 'jquery', '@fortawesome', // Server front end modules // https://stackoverflow.com/a/55700773/3140931 +// Vendor libraries only change when package versions are bumped (a rebuild), +// so they're safe to cache aggressively; ETag/Last-Modified (on by default) +// still cover that rare case with a cheap 304 instead of a stale asset. frontEndModules.forEach(dep => { - router.use(`/static-modules/${dep}`, express.static(path.join(__dirname, `../node_modules/${dep}`))) + router.use(`/static-modules/${dep}`, express.static(path.join(__dirname, `../node_modules/${dep}`), {maxAge: '7d'})) }); // Have express server static content( images, CSS, browser JS) from the public -// local folder. -router.use('/static', express.static(path.join(__dirname, '../public'))) +// local folder. Shorter maxAge than /static-modules since this is the app's +// own JS/CSS, which changes on every deploy and isn't cache-busted/fingerprinted. +router.use('/static', express.static(path.join(__dirname, '../public'), {maxAge: '1h'})) router.get('/', (req, res) => { res.redirect(301, '/hosts'); diff --git a/nodejs/routes/user.js b/nodejs/routes/user.js index 434d41c..d89e4d1 100755 --- a/nodejs/routes/user.js +++ b/nodejs/routes/user.js @@ -9,7 +9,7 @@ const {passwordError} = require('../utils/password_policy'); // per-field key the frontend surfaces inline. function validatePassword(password){ let message = passwordError(password); - if(message) throw User.errors.ObjectValidateError([{key: 'password', message}]); + if(message) throw new User.errors.ObjectValidateError([{key: 'password', message}]); } // User management is global-admin-only, except the self-service routes below diff --git a/nodejs/views/hosts.ejs b/nodejs/views/hosts.ejs index 8add303..fefc6e7 100755 --- a/nodejs/views/hosts.ejs +++ b/nodejs/views/hosts.ejs @@ -110,6 +110,66 @@ input.focus(); } + // Host name of the record currently open in the edit modal, or null when + // adding a new host (basic-auth user management needs a saved host to + // attach users to). + let hostFormCurrentHost = null; + + // The auth_mode radios aren't real form fields (no [name]); this keeps the + // two hidden basicauth_enabled/sso_enabled inputs — the ones actually + // submitted — in sync so only one can ever be true, and shows/hides the + // matching field group. + function hostAuthModeChanged(mode){ + $('#basicauth_enabled-hidden').val(mode === 'basic' ? 'true' : 'false'); + $('#sso_enabled-hidden').val(mode === 'sso' ? 'true' : 'false'); + $('#hostTab-auth-basicFields').toggle(mode === 'basic'); + $('#hostTab-auth-ssoFields').toggle(mode === 'sso'); + $('#hostTab-auth-basicUsersMgmt').toggle(mode === 'basic' && !!hostFormCurrentHost); + } + + // Per-user basic-auth management (delete / change password) for the host + // currently open in the edit modal. Only shown once a host exists to attach + // users to (not on "Add host", before it's been saved). + function hostRenderBasicAuthUsers(host, users){ + let $rows = $('#basicAuthUserRows').empty(); + let usernames = Object.keys(users || {}); + if(!usernames.length){ + $rows.append('No basic-auth users yet.'); + return; + } + for(let username of usernames){ + let $tr = $(''); + $tr.append($('').text(username)); + let $pass = $(''); + $tr.append($('').append($pass)); + let $actions = $(''); + let $save = $(''); + $save.on('click', function(){ + let password = $pass.val(); + if(!password) return; + app.api.put('host/' + encodeURIComponent(host) + '/basicauth-user/' + encodeURIComponent(username), {password}, function(error, data){ + if(error) return app.util.actionMessage((data && data.message) || 'Failed to update password', $rows, 'danger'); + $pass.val(''); + app.util.actionMessage('Password updated for "' + username + '".', $rows, 'success'); + }); + }); + // No confirm step, matching this form's existing "Delete" button + // (host deletion itself is also a single click, no dialog — see the + // host row actions above). + let $del = $(''); + $del.on('click', function(){ + app.api.delete('host/' + encodeURIComponent(host) + '/basicauth-user/' + encodeURIComponent(username), function(error, data){ + if(error) return app.util.actionMessage((data && data.message) || 'Failed to delete user', $rows, 'danger'); + $tr.remove(); + $('.basicauth-current').text(Object.keys((data && data.basicauth_users) || {}).join(', ') || 'none'); + }); + }); + $actions.append($save).append($del); + $tr.append($actions); + $rows.append($tr); + } + } + // Fill the user/group datalists that back the allow-list autocomplete. function hostLoadAuthSuggestions(){ app.api.get('host/auth-suggestions', function(error, data){ @@ -135,6 +195,8 @@ .addClass('challengeType-container'); $('#challengeType-child-relatedHost').text(''); $('.basicauth-current').text('none'); + hostFormCurrentHost = null; + hostAuthModeChanged('none'); hostShowTab('hostTab-general-btn'); } @@ -175,6 +237,13 @@ $f.find("textarea[name='basicauth_users']").val(''); $('.basicauth-current').text(Object.keys(h.basicauth_users || {}).join(', ') || 'none'); + // Auth: one radio drives both mutually-exclusive booleans. + hostFormCurrentHost = host; + let authMode = h.sso_enabled ? 'sso' : (h.basicauth_enabled ? 'basic' : 'none'); + $f.find('#auth_mode-' + authMode).prop('checked', true); + hostAuthModeChanged(authMode); + hostRenderBasicAuthUsers(host, h.basicauth_users); + // The host name is the key; it can't change on edit. Wildcard hosts can // still toggle their matching mode. $f.find('[name=host]').prop('disabled', true); @@ -637,71 +706,88 @@

- Basic auth and SSO are OR'd — if either is enabled, a request - is allowed when it passes either one. Leave both off for a - public host. + Pick one authentication method for this host — basic auth and + SSO can't both be enabled, to avoid ambiguity about which one + actually protected a request. Choose "Off" for a public host.

-
Basic authentication
+
-
- - -
-
- - - - Current: none. - Passwords are stored hashed and never shown here. Leave blank to keep - the current users; entering any lines replaces the whole list. - + + + + + -
-
Single sign-on (SSO)
-
-
-
- Gates the site behind the same identity provider the admin app uses. Empty allow-lists below mean any authenticated user is allowed. + -
- -
- - + -
- -
- - -
-