Make basic auth and SSO mutually exclusive per host; fix silently-broken validation errors

- 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 <noreply@anthropic.com>
This commit is contained in:
2026-07-15 00:41:16 -04:00
parent 71f1b12a74
commit ad2cacf094
8 changed files with 209 additions and 66 deletions
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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}]);
}
}
+2 -2
View File
@@ -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;
+2 -2
View File
@@ -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);
+57 -4
View File
@@ -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);
+7 -3
View File
@@ -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');
+1 -1
View File
@@ -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
+138 -52
View File
@@ -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('<tr><td colspan="3" class="text-muted">No basic-auth users yet.</td></tr>');
return;
}
for(let username of usernames){
let $tr = $('<tr>');
$tr.append($('<td>').text(username));
let $pass = $('<input type="text" class="form-control form-control-sm" placeholder="new password">');
$tr.append($('<td>').append($pass));
let $actions = $('<td>');
let $save = $('<button type="button" class="btn btn-sm btn-outline-secondary me-1"><i class="fa-solid fa-key"></i></button>');
$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 = $('<button type="button" class="btn btn-sm btn-outline-danger"><i class="fa-solid fa-trash"></i></button>');
$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 @@
<!-- Authentication -->
<div class="tab-pane fade" id="hostTab-auth" role="tabpanel">
<p class="field-help text-muted">
Basic auth and SSO are OR'd &mdash; if either is enabled, a request
is allowed when it passes <b>either</b> one. Leave both off for a
public host.
Pick one authentication method for this host &mdash; 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.
</p>
<h6 class="text-muted">Basic authentication</h6>
<div class="form-group">
<div class="radio"><label>
<input type="radio" name="basicauth_enabled" id="basicauth_enabled-false" value="false" checked>
Off
<input type="radio" id="auth_mode-none" value="none" checked onchange="hostAuthModeChanged('none')">
Off (public)
</label></div>
<div class="radio"><label>
<input type="radio" name="basicauth_enabled" id="basicauth_enabled-true" value="true">
Require username / password
<input type="radio" id="auth_mode-basic" value="basic" onchange="hostAuthModeChanged('basic')">
Basic authentication
</label></div>
<div class="radio"><label>
<input type="radio" id="auth_mode-sso" value="sso" onchange="hostAuthModeChanged('sso')">
Single sign-on (SSO)
</label></div>
</div>
<div class="form-group">
<label for="basicauth_realm" class="form-label">Realm</label>
<input type="text" name="basicauth_realm" class="form-control" value="Restricted" placeholder="Restricted" />
</div>
<div class="form-group">
<label for="basicauth_users" class="form-label">Users</label>
<textarea name="basicauth_users" class="form-control" rows="2" placeholder="username:password, one per line"></textarea>
<small class="field-help text-muted d-block">
Current: <span class="basicauth-current">none</span>.
Passwords are stored hashed and never shown here. Leave blank to keep
the current users; entering any lines replaces the whole list.
</small>
<!-- Actually-submitted fields; kept in sync with the radios above by
hostAuthModeChanged() so only one can be true at a time. -->
<input type="hidden" name="basicauth_enabled" id="basicauth_enabled-hidden" value="false">
<input type="hidden" name="sso_enabled" id="sso_enabled-hidden" value="false">
<div id="hostTab-auth-basicFields" style="display:none">
<hr>
<h6 class="text-muted">Basic authentication</h6>
<div class="form-group">
<label for="basicauth_realm" class="form-label">Realm</label>
<input type="text" name="basicauth_realm" class="form-control" value="Restricted" placeholder="Restricted" />
</div>
<div class="form-group">
<label for="basicauth_users" class="form-label">Users</label>
<textarea name="basicauth_users" class="form-control" rows="2" placeholder="username:password, one per line"></textarea>
<small class="field-help text-muted d-block">
Current: <span class="basicauth-current">none</span>.
Passwords are stored hashed and never shown here. Leave blank to keep
the current users; entering any lines replaces the whole list. To
manage individual users (delete / change password), use the table
below once the host has been saved.
</small>
</div>
</div>
<hr>
<h6 class="text-muted">Single sign-on (SSO)</h6>
<div class="form-group">
<div class="radio"><label>
<input type="radio" name="sso_enabled" id="sso_enabled-false" value="false" checked>
Off
</label></div>
<div class="radio"><label>
<input type="radio" name="sso_enabled" id="sso_enabled-true" value="true">
Require login via the configured OIDC provider
</label></div>
<small class="field-help text-muted d-block">Gates the site behind the same identity provider the admin app uses. Empty allow-lists below mean any authenticated user is allowed.</small>
<div id="hostTab-auth-ssoFields" style="display:none">
<hr>
<h6 class="text-muted">Single sign-on (SSO)</h6>
<p class="field-help text-muted">Gates the site behind the same identity provider the admin app uses. Empty allow-lists below mean any authenticated user is allowed.</p>
<div class="form-group">
<label for="sso_allow_users" class="form-label">Allowed users</label>
<div class="input-group mb-1">
<input type="text" class="form-control" list="hostSsoUsers" placeholder="type to search users…"
onkeydown="if(event.key==='Enter'){event.preventDefault();allowListAdd(this,'sso_allow_users');}">
<button type="button" class="btn btn-outline-secondary" onclick="allowListAdd(this.previousElementSibling,'sso_allow_users')">
<i class="fa-solid fa-plus"></i> Add
</button>
</div>
<textarea name="sso_allow_users" class="form-control" rows="2" placeholder="one email/username per line; blank = any authenticated user"></textarea>
</div>
<div class="form-group">
<label for="sso_allow_groups" class="form-label">Allowed groups</label>
<div class="input-group mb-1">
<input type="text" class="form-control" list="hostSsoGroups" placeholder="type to search groups…"
onkeydown="if(event.key==='Enter'){event.preventDefault();allowListAdd(this,'sso_allow_groups');}">
<button type="button" class="btn btn-outline-secondary" onclick="allowListAdd(this.previousElementSibling,'sso_allow_groups')">
<i class="fa-solid fa-plus"></i> Add
</button>
</div>
<textarea name="sso_allow_groups" class="form-control" rows="2" placeholder="one group per line; blank = any authenticated user"></textarea>
</div>
</div>
<div class="form-group">
<label for="sso_allow_users" class="form-label">Allowed users</label>
<div class="input-group mb-1">
<input type="text" class="form-control" list="hostSsoUsers" placeholder="type to search users…"
onkeydown="if(event.key==='Enter'){event.preventDefault();allowListAdd(this,'sso_allow_users');}">
<button type="button" class="btn btn-outline-secondary" onclick="allowListAdd(this.previousElementSibling,'sso_allow_users')">
<i class="fa-solid fa-plus"></i> Add
</button>
<div id="hostTab-auth-basicUsersMgmt" style="display:none">
<hr>
<h6 class="text-muted">Manage basic-auth users</h6>
<div class="table-responsive">
<table class="table table-sm">
<thead><tr><th>Username</th><th>New password</th><th></th></tr></thead>
<tbody id="basicAuthUserRows"></tbody>
</table>
</div>
<textarea name="sso_allow_users" class="form-control" rows="2" placeholder="one email/username per line; blank = any authenticated user"></textarea>
</div>
<div class="form-group">
<label for="sso_allow_groups" class="form-label">Allowed groups</label>
<div class="input-group mb-1">
<input type="text" class="form-control" list="hostSsoGroups" placeholder="type to search groups…"
onkeydown="if(event.key==='Enter'){event.preventDefault();allowListAdd(this,'sso_allow_groups');}">
<button type="button" class="btn btn-outline-secondary" onclick="allowListAdd(this.previousElementSibling,'sso_allow_groups')">
<i class="fa-solid fa-plus"></i> Add
</button>
</div>
<textarea name="sso_allow_groups" class="form-control" rows="2" placeholder="one group per line; blank = any authenticated user"></textarea>
</div>
</div>