Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/auth-declared-defaults-every-key.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@objectstack/plugin-auth': patch
---

fix(plugin-auth)!: Setup → Authentication shows what the deployment runs for every auth setting it declares, and says when sign-up is forced off over a value saved on

Clause-②: yes (narrowing) — narrowed: with nothing stored, `SettingsService.get('auth', …)` and `GET /api/settings/auth` answer 24 more `auth` keys with the deployment's declaration (still `source: 'default'`) where they answered the manifest default: `password_min_length`, `password_max_length`, `membership_policy`, `password_reject_breached`, `password_require_complexity`, `password_min_classes`, `password_history_count`, `password_expiry_days`, `mfa_required`, `mfa_grace_period_days`, `api_key_default_expiry_days`, `api_key_max_expiry_days`, `api_key_inactivity_days`, `session_expiry_days`, `session_refresh_days`, `session_idle_timeout_minutes`, `session_absolute_max_hours`, `max_concurrent_sessions_per_user`, `allowed_ip_ranges`, `lockout_threshold`, `lockout_duration_minutes`, `audience_posture`, `audience_allowed_email_domains`, `audience_self_registration_permission_set`; so a published response's value changes for an existing reader on any deployment whose own configuration differs from the manifest default for one of them. Four keys gate another key's visibility, so with nothing stored a declaration now shows a key that was hidden, and a save that touches it or its gate is judged for its options and bounds where it was not: `lockout_duration_minutes` under a declared `lockoutThreshold` above 0 (for example `lockout_duration_minutes: 5000` is now refused `400 SETTINGS_VALIDATION` where it was stored), `mfa_grace_period_days` under a declared `mfaRequirement` other than `off`, `password_min_classes` under a declared `passwordRequireComplexity: true`, and `audience_allowed_email_domains` / `audience_self_registration_permission_set` under a declared `audience.posture` of `email_domain` or `open`. A save that sets one of these keys to its manifest default where the declaration differs now asks the key's write predicates. Widened: a save that sets one of these keys to the declaration with nothing stored is no change and asks no predicate. The Setup → Authentication live-status banner adds a `warning` for `signup_enabled` stored on where the deployment forces sign-up off (SSO-only, cloud-managed, `OS_DISABLE_SIGNUP`), in all 11 languages; where both that and the cloud-managed email-and-password hold apply, one banner carries both statements.
Metadata-protocol: none
Skills-docs: none — no skill under `skills/**` teaches the auth settings page, these keys or the settings cascade's bottom rung.

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed, renamed or re-shaped: these are settings values, runtime state, not authorable metadata, and the settings manifest is unchanged. What moves is the value a key with nothing stored resolves to, which keys that value shows, and the save of it that a write predicate is now asked about; no stored row is read differently, so there is nothing for `objectstack migrate meta` to rewrite and no tombstone. -->

**BREAKING** for a reader of `GET /api/settings/auth` or `SettingsService.get('auth', …)` on a deployment whose own configuration differs from the manifest default for one of these keys, with nothing saved: the value answered is now what runs (for example `lockout_threshold: { value: 5, source: 'default' }` where the deployment declares `lockoutThreshold: 5`), not the manifest default. A saved value and an `OS_AUTH_*` override still win, and a clear returns to the declaration. A deployment that declares none of these reads exactly as before.

Each answer takes the key's own shape: session lifetimes in days (the declared seconds divided by 86 400), allowed IP ranges and email domains one per line, and a select's value only when it is one of its options (an off-vocabulary `membershipPolicy` or `mfaRequirement` leaves the manifest default). Not stated, by design: `rate_limit_max` and `rate_limit_window_seconds` (the auth library's per-path rules run with nothing stored, which no one number states), `api_key_policy_started_at` (recorded into the store at first boot), and the Google keys (the toggle's runtime default is the manifest default, and a declared credential outranks a saved one).

What to do: nothing to migrate. A client that read `source: 'default'` as "the manifest default" should read it as "nothing is saved; this is the deployment's default".
42 changes: 30 additions & 12 deletions packages/plugins/plugin-auth/src/auth-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,12 @@ import {
ssoProviderDeleteRefusal,
type SignInMethodFloorDeps,
} from './sign-in-method-floor.js';
import { describeEmailPasswordLiveStatus, type AuthLiveStatus } from './auth-settings-live-status.js';
import {
combineAuthLiveStatus,
describeEmailPasswordLiveStatus,
describeSignUpLiveStatus,
type AuthLiveStatus,
} from './auth-settings-live-status.js';
import { registerAuthDeclaredDefaults } from './auth-settings-declared-defaults.js';
import { judgePlatformAdmin, judgeHeldSession, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js';
import {
Expand Down Expand Up @@ -3192,28 +3197,41 @@ export class AuthPlugin implements Plugin {
let pass: Promise<void> = Promise.resolve();
const runPass = (): Promise<void> => (pass = applySettings());

// Setup → Authentication states what runs when the switch says otherwise:
// a value stored on that a cloud-managed runtime does not apply, or any
// other disagreement. See auth-settings-live-status.ts.
// Setup → Authentication states what runs when a switch says otherwise:
// email and password stored on that a cloud-managed runtime does not
// apply, or any other disagreement; sign-up stored on where the
// deployment forces it off. See auth-settings-live-status.ts.
if (typeof settings.registerLiveStatus === 'function') {
const floorDeps = this.signInMethodFloorDeps(ctx, this.authManager);
try {
settings.registerLiveStatus('auth', async ({ ctx: pageCtx, locale }) => {
await pass;
const manager = this.authManager;
if (!manager) return undefined;
return describeEmailPasswordLiveStatus({
running: manager.getPublicConfig().emailPassword.enabled,
shown: await settings.get('auth', 'email_password_enabled', pageCtx),
heldOffByHost: emailPasswordHeldOffByHost(floorDeps),
locale,
});
const running = manager.getPublicConfig().emailPassword;
const emailPasswordShown = await settings.get('auth', 'email_password_enabled', pageCtx);
return combineAuthLiveStatus([
describeEmailPasswordLiveStatus({
running: running.enabled,
shown: emailPasswordShown,
heldOffByHost: emailPasswordHeldOffByHost(floorDeps),
locale,
}),
describeSignUpLiveStatus({
running: !running.disableSignUp,
shown: await settings.get('auth', 'signup_enabled', pageCtx),
forcedOff: manager.resolveDisableSignUp(false),
emailPasswordShown,
locale,
}),
]);
});
} catch (err: any) {
ctx.logger.warn(
'[auth] Setup → Authentication: the live status was NOT registered '
+ `(${String(err?.message ?? err)}), so where a saved email and password value is not what runs `
+ '(a cloud-managed environment holding it off), the page shows the switch on with nothing saying it is off.',
+ `(${String(err?.message ?? err)}), so where a saved email and password or sign-up value is not what `
+ 'runs (a cloud-managed or single-sign-on-only environment holding it off), the page shows the switch on '
+ 'with nothing saying it is off.',
);
}
}
Expand Down
118 changes: 111 additions & 7 deletions packages/plugins/plugin-auth/src/auth-settings-declared-defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
* service answers it at the bottom of the cascade, still `source: 'default'`
* (nothing is stored), and a stored value or an `OS_*` override still wins.
*
* Only the keys whose declaration can differ from their manifest default
* through a value the deployment itself states, each computed through the
* formula the running config answers with, so the two cannot disagree:
* Every key whose running value is taken from a value the deployment itself
* states, each computed through the formula the running config answers with,
* so the two cannot disagree. Measured key by key on a real `AuthPlugin`:
* with nothing declared each formula answers the manifest default (or nothing,
* for a key with no manifest default), so a deployment that declares nothing
* reads as before; with a declaration, the switch reads it.
*
* - `email_password_enabled` (manifest `true`): `emailAndPassword.enabled`,
* on unless declared `false` (`getPublicConfig().emailPassword.enabled`).
Expand All @@ -30,14 +33,48 @@
* `emailAndPassword.requireEmailVerification` under the audience posture in
* force (`resolveEmailVerificationRequirement`) — on under `email_domain`,
* on under `open` unless declared `false`.
* - The password, MFA, API-key, session, network and lockout keys, the
* membership policy and the audience trio: the declared option the manager
* reads, through the manager's own default and clamp where it has one
* ({@link AUTH_DECLARED_DEFAULTS} names the reader each mirrors).
*
* Each answer is in the shape the key's specifier takes: days for a session
* lifetime the manager holds in seconds, one entry per line for a list the
* console edits as a textarea, and a select's value only when it is one of
* the select's options (an off-vocabulary declaration answers nothing, so the
* manifest default stands, rather than serving a value the page cannot offer).
*
* Not declared here, by design:
*
* - `rate_limit_max` / `rate_limit_window_seconds`: with nothing stored the
* sign-in, sign-up and password-reset endpoints run on the auth library's
* own per-path rules (and its production-only switch), or a declared
* `rateLimit` that is not the per-endpoint cap the setting writes, so no
* one number states what runs.
* - `api_key_policy_started_at`: recorded into the store by the first boot
* that runs the policy, so it is not left unstored.
* - `google_enabled`: an intent toggle whose runtime default is the manifest
* default (on); a Google button needs it and both credentials.
* - `google_client_id` / `google_client_secret`: a credential declared in the
* server configuration outranks a saved one, so it is not the value a
* clear returns to, and a secret is never served as a default.
*
* Asked by the settings service on each read, never recorded here, so a
* posture change or a host flag is followed at once.
*/

import {
API_KEY_DEFAULT_EXPIRY_DAYS,
API_KEY_INACTIVITY_DAYS,
API_KEY_MAX_EXPIRY_DAYS,
} from '@objectstack/core';
import type { AudiencePosture } from '@objectstack/spec/system';
import { resolveEmailVerificationRequirement } from './audience-posture.js';
import { resolveAudience, resolveEmailVerificationRequirement } from './audience-posture.js';
import { readBooleanEnv } from './auth-manager.js';
import { resolveMfaGracePeriodDays } from './auth-manager-password-session-policy.js';
import type { DeclaredAuthOptions } from './auth-settings-declared.js';
import { isMfaRequirementLevel } from './organization-access-policy.js';
import { isMembershipPolicy } from './reconcile-membership.js';

/** What a declared default is computed from, all read when asked. */
export interface AuthDeclaredDefaultFacts {
Expand All @@ -49,17 +86,84 @@ export interface AuthDeclaredDefaultFacts {
audiencePosture(): AudiencePosture;
}

/** Each key's declared default, by key. */
export const AUTH_DECLARED_DEFAULTS: Readonly<Record<string, (facts: AuthDeclaredDefaultFacts) => boolean>> = {
/** A non-empty list as the console's textarea holds it (one entry per line), else nothing declared. */
function asLines(list: readonly string[] | undefined): string | undefined {
return Array.isArray(list) && list.length > 0 ? list.join('\n') : undefined;
}

/** `AuthManager#resolveApiKeyLifecyclePolicy`'s reading of one window. */
function apiKeyDays(value: unknown, fallback: number, min: number): number {
const n = Math.floor(Number(value));
return Number.isFinite(n) && n >= min ? n : fallback;
}

/**
* Each key's declared default, by key: what the running config takes for it
* while nothing is stored. `undefined` means the deployment declared nothing
* the specifier can show, and the manifest default stands.
*/
export const AUTH_DECLARED_DEFAULTS: Readonly<Record<string, (facts: AuthDeclaredDefaultFacts) => unknown>> = {
email_password_enabled: (facts) => facts.declared().emailAndPassword?.enabled !== false,
signup_enabled: (facts) => !facts.resolveDisableSignUp(facts.declared().emailAndPassword?.disableSignUp),
require_email_verification: (facts) =>
resolveEmailVerificationRequirement(
facts.audiencePosture(),
facts.declared().emailAndPassword?.requireEmailVerification,
),
// The auth library's own bounds (8 / 128) are the manifest defaults: only a declared bound is stated.
password_min_length: (facts) => numberOrUndefined(facts.declared().emailAndPassword?.minPasswordLength),
password_max_length: (facts) => numberOrUndefined(facts.declared().emailAndPassword?.maxPasswordLength),
// `AuthManager#getMembershipPolicy`.
membership_policy: (facts) => {
const declared = facts.declared().membershipPolicy ?? 'auto';
return isMembershipPolicy(declared) ? declared : undefined;
},
// `buildPluginList`: the deployment env, else the declared flag, else off.
password_reject_breached: (facts) =>
readBooleanEnv('OS_AUTH_PASSWORD_REJECT_BREACHED') ?? facts.declared().plugins?.passwordRejectBreached ?? false,
// `assertPasswordComplexity`.
password_require_complexity: (facts) => Boolean(facts.declared().passwordRequireComplexity),
password_min_classes: (facts) =>
Math.min(4, Math.max(1, Math.floor(Number(facts.declared().passwordMinClasses) || 3))),
// The password history and expiry policy bodies.
password_history_count: (facts) => Math.floor(Number(facts.declared().passwordHistoryCount) || 0),
password_expiry_days: (facts) => Math.floor(Number(facts.declared().passwordExpiryDays) || 0),
// `AuthManager#getDeploymentAccessFloor`.
mfa_required: (facts) => {
const declared = facts.declared().mfaRequirement ?? 'off';
return isMfaRequirementLevel(declared) ? declared : undefined;
},
mfa_grace_period_days: (facts) => resolveMfaGracePeriodDays(facts.declared()),
// `AuthManager#resolveApiKeyLifecyclePolicy` (the ceiling rules the default too).
api_key_default_expiry_days: (facts) => {
const declared = facts.declared();
const max = apiKeyDays(declared.apiKeyMaxExpiryDays, API_KEY_MAX_EXPIRY_DAYS, 1);
return Math.min(max, apiKeyDays(declared.apiKeyDefaultExpiryDays, API_KEY_DEFAULT_EXPIRY_DAYS, 1));
},
api_key_max_expiry_days: (facts) => apiKeyDays(facts.declared().apiKeyMaxExpiryDays, API_KEY_MAX_EXPIRY_DAYS, 1),
api_key_inactivity_days: (facts) => apiKeyDays(facts.declared().apiKeyInactivityDays, API_KEY_INACTIVITY_DAYS, 0),
// The auth instance's `session` block, seconds as days.
session_expiry_days: (facts) => (facts.declared().session?.expiresIn || 60 * 60 * 24 * 7) / 86_400,
session_refresh_days: (facts) => (facts.declared().session?.updateAge || 60 * 60 * 24) / 86_400,
// `AuthManager#getDeploymentAccessFloor`.
session_idle_timeout_minutes: (facts) => facts.declared().sessionIdleTimeoutMinutes ?? 0,
session_absolute_max_hours: (facts) => facts.declared().sessionAbsoluteMaxHours ?? 0,
max_concurrent_sessions_per_user: (facts) => facts.declared().maxConcurrentSessions ?? 0,
allowed_ip_ranges: (facts) => asLines(facts.declared().allowedIpRanges),
// The sign-in lockout bodies.
lockout_threshold: (facts) => Number(facts.declared().lockoutThreshold) || 0,
lockout_duration_minutes: (facts) => Number(facts.declared().lockoutDurationMinutes) || 15,
// `AuthManager#getAudience` (`resolveAudience`): undeclared or off-vocabulary is `invite_only`.
audience_posture: (facts) => resolveAudience(facts.declared().audience).posture,
audience_allowed_email_domains: (facts) => asLines(resolveAudience(facts.declared().audience).allowedEmailDomains),
audience_self_registration_permission_set: (facts) =>
resolveAudience(facts.declared().audience).selfRegistrationPermissionSet,
};

function numberOrUndefined(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}

/** The slice of the settings service this needs (structural: no package dependency). */
export interface DeclaredDefaultHost {
registerDeclaredDefault?(namespace: string, key: string, provider: () => unknown): void;
Expand All @@ -85,7 +189,7 @@ export function registerAuthDeclaredDefaults(
} catch (err: any) {
logger.warn(
`[auth] Setup → Authentication: the declared default of auth.${key} was NOT registered `
+ `(${String(err?.message ?? err)}), so with nothing saved that switch shows the console default rather `
+ `(${String(err?.message ?? err)}), so with nothing saved that setting shows the console default rather `
+ 'than what this deployment runs.',
);
}
Expand Down
Loading
Loading