Add OIDC login and per-domain authorization

Authentication previously implied full authorization: any valid token
could manage every host, DNS provider, domain, and user. This adds SSO
login and a per-domain rights model.

OIDC login (authorization_code + PKCE):
- conf.oidc + conf.auth blocks; clientSecret in (gitignored) secrets.js.
- utils/oidc.js (state/PKCE, code exchange, userinfo) using global fetch.
- models/oidc_state.js: short-lived state store, auto-expiring via
  model-redis 1.5 per-key TTL.
- routes/auth.js: GET /auth/oidc/start + /auth/oidc/callback; JIT-provisions
  a local user, mints an AuthToken carrying the SSO groups, hands the token to
  the browser via a URL fragment. "Log in with SSO" button on the login page.

Authorization (groups + app overrides, per-domain, with ownership):
- models/grant.js + utils/roles.js (pure, unit-tested): effective rights from
  conf.auth (admin users/groups, group->role map), Grant records
  (user|group -> global|domain -> viewer|manager|admin), and ownership
  (created_by). Roles rank admin > manager(owner) > viewer.
- AuthToken stores session groups; middleware/auth.js exposes req.groups.
- middleware/authz.js: requireAdmin, requireDomainRole(minRole, resolveDomain),
  filterViewable. Applied across routes: host mutations need manager on the
  host's domain; reads are filtered to visible domains; DNS providers, user
  management, and grant management are global-admin-only; certs need viewer.
- routes/grant.js: admin CRUD for grants. Anti-lockout via conf.auth.adminUsers
  plus migrations/grant_bootstrap.js.

Frontend: /me returns effective rights; nav gates Users/Grants to admins;
grants management page; OIDC token-fragment handling in app-base.js.

Tests: utils/roles and utils/oidc unit-tested (no redis); wired into the test
scripts. Full suite 89 pass. Also verified end-to-end against redis (grant
resolution, middleware allow/deny/403, list filtering) and the OIDC pure flow.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-10 12:17:05 -04:00
parent 9f175f5bf6
commit 10abd36340
28 changed files with 1317 additions and 50 deletions
+23 -1
View File
@@ -47,7 +47,10 @@ class Auth{
static async login(data){
try{
let user = await User.login(data);
let token = await AuthToken.create({username: user.username});
// Backends may attach group membership to the user (LDAP); default
// to none for local/redis users.
let groups = Array.isArray(user.groups) ? user.groups : [];
let token = await AuthToken.create({username: user.username, groups});
return {user, token}
}catch(error){
@@ -56,6 +59,25 @@ class Auth{
}
}
/**
* Establish a session for an OIDC-authenticated identity: JIT-provision the
* local user (redis-backed) and mint an AuthToken carrying the SSO groups.
*
* @param {Object} identity - {username, groups} from utils/oidc claims
* @returns {Object} {user, token}
*/
static async oidcSession(identity){
let user = typeof User.upsertOidc === 'function'
? await User.upsertOidc(identity)
: await User.get(identity.username);
let token = await AuthToken.create({
username: user.username,
groups: identity.groups || [],
});
return {user, token};
}
/**
* Validate an authentication token.
*
+112
View File
@@ -0,0 +1,112 @@
'use strict';
const Table = require('.');
const conf = require('@simpleworkjs/conf');
const roles = require('../utils/roles');
/**
* Grant
*
* Assigns a role to a subject (a user or a group), either globally or for a
* single domain. Per-user overrides and group defaults both live here; group
* defaults can also be seeded from conf.auth.groupRoleMap.
*
* subjectType : 'user' | 'group'
* subject : username or group name
* scope : 'global' | 'domain'
* domain : domain name when scope==='domain' (else '*')
* role : 'admin' | 'manager' | 'viewer'
*
* See Grant.effectiveFor() for how these, plus ownership (created_by) and
* conf.auth, collapse into a request's effective rights.
*/
class Grant extends Table{
static _key = 'id';
static _keyMap = {
'created_by': {isRequired: true, type: 'string', min: 3, max: 500},
'created_on': {default: function(){return (new Date).getTime()}},
'id': {isRequired: true, type: 'string', min: 3, max: 1100},
'subjectType': {isRequired: true, type: 'string'},
'subject': {isRequired: true, type: 'string', min: 1, max: 500},
'scope': {default: 'domain', isRequired: true, type: 'string'},
'domain': {default: '*', isRequired: false, type: 'string'},
'role': {isRequired: true, type: 'string'},
}
static roles = ['viewer', 'manager', 'admin'];
// Re-export the pure helpers so existing callers (middleware/authz) can use
// them off the model.
static rank = roles.rank;
static maxRole = roles.maxRole;
static roleForDomain = roles.roleForDomain;
static allows = roles.allows;
static visibleDomains = roles.visibleDomains;
// Deterministic id so the same (subject, scope, domain) grant is a single
// record — re-granting updates rather than duplicating.
static mkId({subjectType, subject, scope, domain}){
return `${subjectType}:${subject}:${scope || 'domain'}:${scope === 'global' ? '*' : (domain || '*')}`;
}
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(', ')}`}]);
}
if(!['user', 'group'].includes(data.subjectType)){
throw this.errors.ObjectValidateError([{key: 'subjectType', message: `subjectType must be 'user' or 'group'`}]);
}
if(data.scope === 'global') data.domain = '*';
data.id = this.mkId(data);
// Upsert: replace an existing identical-scoped grant instead of 409ing.
try{
let existing = await this.get(data.id);
if(existing) await existing.remove();
}catch(error){ /* not found is fine */ }
return super.create(data);
}
/**
* Collapse conf.auth, grant records, and resource ownership into the
* effective rights for a session identity.
*
* @param {Object} identity - {username, groups: string[]}
* @returns {Object} { isAdmin, global: role|null, domains: {domain: role} }
* - isAdmin: full access to everything.
* - global: a non-admin global role (manager/viewer) applied to every
* domain the user can see.
* - domains: explicit per-domain roles (includes owned domains).
*/
static async effectiveFor(identity){
let username = identity && identity.username;
// Fetch the redis-backed inputs, then hand off to the pure resolver.
let grants = [];
try{
grants = await this.listDetail();
}catch(error){ grants = []; }
// Ownership: a user has manager rights over every domain they (or the
// DNS provider they created) own. Domain.created_by already carries the
// provider creator, so a single Domain scan covers both.
let ownedDomains = [];
if(username){
try{
let Domain = require('.').models.Domain;
ownedDomains = (await Domain.listDetail())
.filter(d => d.created_by === username)
.map(d => d.domain);
}catch(error){ /* domains unavailable, skip ownership */ }
}
return roles.resolveEffective(identity, {
grants,
ownedDomains,
authConf: conf.auth || {},
});
}
}
Grant.register();
module.exports = {Grant};
+2
View File
@@ -10,3 +10,5 @@ require('./dns_provider');
require('./host');
require('./token');
require('./user');
require('./grant');
require('./oidc_state');
+31
View File
@@ -0,0 +1,31 @@
'use strict';
const Table = require('.');
/**
* OidcState
*
* Short-lived store for an in-flight OpenID Connect authorization request.
* Keyed by the random `state` value; holds the PKCE `code_verifier` and the
* post-login redirect target until the SSO calls us back.
*
* The record auto-expires via model-redis per-key TTL (static _ttl), so an
* abandoned login attempt leaves nothing behind and there is no cleanup job.
*/
class OidcState extends Table{
static _key = 'state';
// Auth round-trips are quick; 5 minutes is plenty and bounds replay.
static _ttl = 300;
static _keyMap = {
'created_on': {default: function(){return (new Date).getTime()}},
'state': {isRequired: true, type: 'string', min: 8, max: 500},
'codeVerifier': {isRequired: true, type: 'string', min: 8, max: 500},
'redirect': {default: '/', isRequired: false, type: 'string'},
}
}
OidcState.register();
module.exports = {OidcState};
+18
View File
@@ -33,13 +33,31 @@ class AuthToken extends Token{
static _keyMap = {
...super._keyMap,
user: {model: 'User', rel: 'one', localKey: 'created_by'},
// Group memberships captured at login (OIDC `groups` claim or LDAP
// group membership), stored as a JSON string. Drives authorization for
// the life of the session without re-querying the IdP on every request.
groups: {default: '[]', isRequired: false, type: 'string'},
}
static async create(data){
data.created_by = data.username;
if(Array.isArray(data.groups)){
data.groups = JSON.stringify(data.groups);
}
return super.create(data)
}
// Parse the stored groups JSON back into an array, tolerating bad/missing
// data so authorization never crashes on a malformed token.
groupsArray(){
try{
let parsed = JSON.parse(this.groups);
return Array.isArray(parsed) ? parsed : [];
}catch(error){
return [];
}
}
}
AuthToken.register();
+15
View File
@@ -9,6 +9,19 @@ const client = new Client({
});
// Best-effort group extraction from a directory entry's `memberOf` values.
// Turns `cn=dns-team,ou=groups,dc=...` into `dns-team`. Directories that don't
// return memberOf simply yield no groups (see conf note); explicit group-search
// can be added later if needed.
const parse_groups = function(memberOf){
if(!memberOf) return [];
let values = Array.isArray(memberOf) ? memberOf : [memberOf];
return values.map(function(dn){
let match = /^cn=([^,]+)/i.exec(String(dn));
return match ? match[1] : String(dn);
});
}
const user_parse = function(data){
if(data[conf.userNameAttribute]){
data.username = data[conf.userNameAttribute]
@@ -20,6 +33,8 @@ const user_parse = function(data){
delete data.uidNumber;
}
data.groups = parse_groups(data.memberOf);
return data;
}
+23
View File
@@ -2,6 +2,7 @@
const Table = require('.');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const saltRounds = 10;
class User extends Table{
@@ -40,6 +41,28 @@ class User extends Table{
}
}
/**
* Just-in-time provisioning for an OIDC-authenticated user. Creates the
* local user on first login so relations (tokens, created_by, grants) have
* something to point at. OIDC users get a random, unusable password — they
* authenticate through the SSO, never the local password form.
*
* @param {Object} data - {username, ...} from the OIDC userinfo claims
* @returns {User} the existing or newly created user
*/
static async upsertOidc(data){
try{
return await User.get(data.username);
}catch(error){
return await User.create({
username: data.username,
password: crypto.randomBytes(24).toString('hex'),
created_by: data.username,
backing: 'oidc',
});
}
}
static async login(data){
try{
let user = await User.get(data);