Release 1.3.0: adopt shared @simpleworkjs/* packages; fix LDAP filter injection
Rewire onto the shared @simpleworkjs/oidc-client, /ldap, and /app-stack
packages (deleting the byte-identical local forks of the same code), close the
LDAP filter-injection in User.get by routing the username through escapeFilter
(RFC 4515), align model-redis ^1.6.0 and ldapts ^8.1.8, and unify build_info to
{buildVersion, buildHash, buildYear}. package-lock regenerated from the npm
registry (no file:/link:), so npm ci is clean in docker builds.
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,136 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const Table = require('../models');
|
||||
const {User, AuthToken} = Table.models;
|
||||
const {ApiToken} = require('./api_token');
|
||||
|
||||
/**
|
||||
* Auth Model
|
||||
*
|
||||
* Handles authentication operations for the application.
|
||||
* Manages user login, token validation, and logout processes.
|
||||
*
|
||||
* Dependencies:
|
||||
* - User model: Validates user credentials
|
||||
* - AuthToken model: Creates and manages authentication tokens
|
||||
*
|
||||
* All methods throw standardized login errors on failure to avoid
|
||||
* leaking information about whether usernames exist or tokens are valid.
|
||||
*/
|
||||
class Auth{
|
||||
/**
|
||||
* Standardized error responses for authentication failures.
|
||||
* Returns generic "Invalid Credentials" message for security.
|
||||
*/
|
||||
static errors = {
|
||||
login: function(){
|
||||
let error = new Error('LoginFailed');
|
||||
error.name = 'LoginFailed';
|
||||
error.message = `Invalid Credentials, login failed.`;
|
||||
error.status = 401;
|
||||
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate user and create session token.
|
||||
*
|
||||
* @param {Object} data - Login credentials {username, password}
|
||||
* @returns {Object} {user, token} - User object and auth token
|
||||
* @throws {Error} Generic login error on any failure
|
||||
*
|
||||
* Flow:
|
||||
* 1. Validate credentials via User.login()
|
||||
* 2. Create new AuthToken for the user
|
||||
* 3. Return both user data and token
|
||||
*/
|
||||
static async login(data){
|
||||
try{
|
||||
let user = await User.login(data);
|
||||
// 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){
|
||||
console.log('login error', error);
|
||||
throw this.errors.login();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @param {string} token - Token string to validate
|
||||
* @returns {Object} Token object if valid
|
||||
* @throws {Error} Generic login error if token invalid or expired
|
||||
*
|
||||
* Checks:
|
||||
* 1. Token exists in database
|
||||
* 2. Token has not expired (via token.check())
|
||||
*/
|
||||
static async checkToken(token){
|
||||
try{
|
||||
token = await AuthToken.get(token);
|
||||
if(token && token.check()) return token;
|
||||
|
||||
throw this.errors.login();
|
||||
}catch(error){
|
||||
console.log('check error', error);
|
||||
throw this.errors.login();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an `Authorization: Bearer prx_<id>_<secret>` API token.
|
||||
*
|
||||
* Returns the authenticated ApiToken record (with created_by + the
|
||||
* mint-time groups snapshot); middleware/auth.js wraps it into the
|
||||
* req.token shape the authz layer expects. Every failure collapses to the
|
||||
* same generic login 401 — no leak of existence / wrong secret / expired.
|
||||
*/
|
||||
static async checkApiToken(raw){
|
||||
try{
|
||||
return await ApiToken.authenticate(raw);
|
||||
}catch(error){
|
||||
console.log('api-token check error', error);
|
||||
throw this.errors.login();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy an authentication token (logout).
|
||||
*
|
||||
* @param {string} data - Token string to destroy
|
||||
* @returns {void}
|
||||
*
|
||||
* Removes token from database, invalidating the session.
|
||||
*/
|
||||
static async logout(data){
|
||||
let token = await AuthToken.get(data);
|
||||
await token.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {Auth};
|
||||
+23
-4
@@ -1,18 +1,37 @@
|
||||
'use strict';
|
||||
const conf = require('@simpleworkjs/conf');
|
||||
const {setUpTable} = require('model-redis');
|
||||
const {createOidcClient, bootstrapLocalAdmin} = require('@simpleworkjs/oidc-client');
|
||||
|
||||
const Table = setUpTable(conf.redis);
|
||||
|
||||
module.exports = Table;
|
||||
|
||||
// App-local models. User + ApiToken register before the OIDC client factory
|
||||
// below: Auth binds User, and checkApiToken wraps ApiToken.authenticate.
|
||||
require('./user'); // User (redis-backed local + OIDC JIT)
|
||||
const {ApiToken} = require('./api_token'); // ApiToken (Bearer PATs)
|
||||
require('./dns_provider');
|
||||
require('./dynamic_record');
|
||||
require('./host');
|
||||
require('./token');
|
||||
require('./user');
|
||||
require('./local_group');
|
||||
require('./permission');
|
||||
require('./oidc_state');
|
||||
require('./sso_session');
|
||||
require('./api_token');
|
||||
|
||||
// Shared OIDC client (authorization-code + PKCE): session models (Token,
|
||||
// AuthToken, OidcState), the Auth service, and the /login /logout /oidc/start
|
||||
// /oidc/callback router — all created on this app's Table/redis. PAT validation
|
||||
// is wired in (proxy accepts Bearer prx_<id>_<secret>); the package collapses
|
||||
// every checkApiToken failure to a generic 401.
|
||||
const oidcClient = createOidcClient({
|
||||
Table,
|
||||
checkApiToken: (raw) => ApiToken.authenticate(raw),
|
||||
});
|
||||
module.exports.Token = oidcClient.Token;
|
||||
module.exports.AuthToken = oidcClient.AuthToken;
|
||||
module.exports.OidcState = oidcClient.OidcState;
|
||||
module.exports.Auth = oidcClient.Auth;
|
||||
module.exports.authRouter = oidcClient.router;
|
||||
|
||||
// Idempotent anti-lockout local admin (was the IIFE in user_redis.js).
|
||||
bootstrapLocalAdmin(Table.models.User, {defaultName: 'proxyadmin2'});
|
||||
@@ -1,31 +0,0 @@
|
||||
'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};
|
||||
@@ -1,64 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const Table = require('.');
|
||||
const UUID = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)};
|
||||
|
||||
|
||||
class Token extends Table{
|
||||
static _key = 'token';
|
||||
static _keyMap = {
|
||||
'created_by': {isRequired: true, type: 'string', min: 3, max: 500},
|
||||
'created_on': {default: function(){return (new Date).getTime()}},
|
||||
'updated_on': {default: function(){return (new Date).getTime()}, always: true},
|
||||
'token': {default: UUID, type: 'string', min: 36, max: 36, isPrivate: true},
|
||||
'is_valid': {default: true, type: 'boolean'},
|
||||
}
|
||||
|
||||
constructor(...args){
|
||||
super(...args);
|
||||
}
|
||||
|
||||
async check(){
|
||||
try{
|
||||
return this.is_valid;
|
||||
}catch(error){
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Token.register();
|
||||
|
||||
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();
|
||||
|
||||
module.exports = {Token, AuthToken};
|
||||
@@ -1,8 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
const { Client, Attribute, Change } = require('ldapts');
|
||||
const {Token} = require('./token');
|
||||
const conf = require('@simpleworkjs/conf').ldap;
|
||||
const { escapeFilter } = require('@simpleworkjs/ldap');
|
||||
|
||||
// tlsOptions is optional and forwarded to ldapts so the proxy can bind to
|
||||
// ldaps:// with a self-signed or internal-CA cert. Set via conf/secrets.js or
|
||||
@@ -107,7 +107,9 @@ User.get = async function(data){
|
||||
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
|
||||
let filter = `(&${conf.userFilter}(${conf.userNameAttribute}=${data.username}))`;
|
||||
// Escape the interpolated username (RFC 4515) — previously raw, which
|
||||
// let `*`/`(`/`)`/`\`/NUL in a username break or broaden the filter.
|
||||
let filter = `(&${conf.userFilter}(${conf.userNameAttribute}=${escapeFilter(data.username)}))`;
|
||||
|
||||
const res = await client.search(conf.searchBase, {
|
||||
scope: 'sub',
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
const linuxUser = require('linux-sys-user').promise();
|
||||
const objValidate = require('../utils/object_validate');
|
||||
const {Token} = require('./token');
|
||||
const {promisify} = require('util');
|
||||
const pam = require('authenticate-pam');
|
||||
const authenticate = promisify(pam.authenticate);
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
const Table = require('.');
|
||||
const bcrypt = require('bcrypt');
|
||||
const crypto = require('crypto');
|
||||
const conf = require('@simpleworkjs/conf');
|
||||
const saltRounds = 10;
|
||||
|
||||
class User extends Table{
|
||||
@@ -86,39 +85,6 @@ class User extends Table{
|
||||
|
||||
User.register();
|
||||
|
||||
(async function(){
|
||||
// Matches migrations/permission_bootstrap.js: the anti-lockout account is
|
||||
// the first entry in conf.auth.adminUsers (default 'proxyadmin2'), NOT a
|
||||
// hardcoded name -- otherwise an operator who customizes adminUsers ends
|
||||
// up with a bootstrap account that has no admin permissions.
|
||||
var defaultUser = (conf.auth && conf.auth.adminUsers && conf.auth.adminUsers[0]) || 'proxyadmin2';
|
||||
// Optional: an orchestrator (e.g. theta-env's setup.sh) can set
|
||||
// auth.localAdminPass in proxy-secrets.js to a generated password so this
|
||||
// bootstrap account isn't left at a well-known default. Only used on first
|
||||
// creation -- once the account exists this is never read again, so it's
|
||||
// safe to leave set. If unset, a random password is generated and printed
|
||||
// once; save it from the log or set auth.localAdminPass explicitly.
|
||||
var defaultPass = (conf.auth && conf.auth.localAdminPass);
|
||||
if (!defaultPass) {
|
||||
defaultPass = crypto.randomBytes(16).toString('hex');
|
||||
console.warn(`====================================================================`);
|
||||
console.warn(`Bootstrap admin "${defaultUser}" created with random password:`);
|
||||
console.warn(`${defaultPass}`);
|
||||
console.warn(`Set auth.localAdminPass in your secrets file to make this deterministic.`);
|
||||
console.warn(`====================================================================`);
|
||||
}
|
||||
try{
|
||||
let user = await User.get(defaultUser);
|
||||
}catch(error){
|
||||
try{
|
||||
let user = await User.create({
|
||||
username:defaultUser,
|
||||
password: defaultPass,
|
||||
created_by: defaultUser
|
||||
});
|
||||
console.log(defaultUser, 'created');
|
||||
}catch(error){
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
})();
|
||||
// Anti-lockout local-admin bootstrap moved to @simpleworkjs/oidc-client
|
||||
// (bootstrapLocalAdmin); invoked once from models/index.js after User is
|
||||
// registered. See the package lib/bootstrap.js for the original logic.
|
||||
|
||||
Reference in New Issue
Block a user