Skip to content

Commit b5765be

Browse files
fix(plugin-auth)!: clearing an authentication setting, or resetting the namespace, takes effect at once (#30312) (#30447)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgA9Z648v7EcnvTMWpmnkjL3)_ domain:server#2 · os-bill · session_01Utp6Cbvcmv8YWFhFJwzjKL ## 维护者速读 - 改了什么:Setup → 认证里清空一个设置(或"恢复默认"整组重置)后,运行值当场回到部署自己声明的值(插件选项 / `auth:configure`,没声明就回内置默认),不再要重启。覆盖全部 33 个认证设置:锁定阈值、每人最大会话、密码策略、会话时长、强制 MFA、API 密钥期限、限流、Google、受众策略等;IP 白名单(#30203)并入同一机制。 - 为什么改:清空后界面显示默认值,但运行时一直沿用上次存的值,直到重启(实测:锁定阈值 3、最大会话 2 清空后仍生效)。管理员以为已经恢复默认,其实没有。 - 风险与回滚:收窄一处(Clause-② `yes (narrowing)`):部署声明"邮箱密码登录关"、在 Setup 里打开、再关掉了 Google,此时清空"邮箱密码登录"会被拒存(400 `SETTINGS_VALIDATION`),因为清空现在真的会把它关掉、导致无人能登录。其余清空只是开始生效。环境变量锁定的设置不受影响。回滚即撤本 PR。 - 先看:`packages/plugins/plugin-auth/src/auth-settings-declared.ts`(回落表,每个键走哪一片);`auth-plugin.ts` 的 `applySettings` 新增回落段与受众回落;`sign-in-method-floor.ts` 清空按声明值判的一行。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/auth-settings-clear.pin.test.ts`,预期 17/17 通过,其中第一组断言锁定阈值清空后当场回到声明的 7。 - 需要你做的:无,席位落地。 Fixes #30312 Clause-②: yes (narrowing) — one save an administrator could make before is now refused at the auth settings save door with the existing `SETTINGS_VALIDATION` / `invalid_value` field error at `email_password_enabled`: clearing that toggle on a deployment that itself declared email and password off, when nothing else signs anyone in after the save. Before, that clear was saved and changed nothing at runtime; now a clear applies, and that one would lock everyone out. No error code, settings key or export is added or removed. Metadata-protocol: none Skills-docs: none — no file under `skills/**` teaches the auth settings namespace, its clear or the sign-in floor. ## Why `PUT /api/settings/auth` with a key set to `null` (the console's clear), or the namespace reset, answers saved, and the key resolves `source: 'default'`. Every `if (isExplicit(key))` branch in `applySettings` skipped such a key, so the running value kept the last stored one until a restart. Re-measured first on `dbf53efe`, real `AuthPlugin` + `SettingsService`: `lockout_threshold` 3 and `max_concurrent_sessions_per_user` 2 stayed 3 / 2 after `setMany(…, null)`; a reset left `lockout_threshold` 4. Only `allowed_ip_ranges` had a reset arm (#30203, PR #30309). ## What changes - **One mechanism, not thirty `else` arms.** `auth-settings-declared.ts` holds two pieces of data. `captureDeclaredAuthOptions` takes, once in `init()` after `auth:configure` and before the manager is built, the deployment's own value of every option an `auth.*` key drives. `AUTH_SETTING_RESTORE` names, for each of the 33 keys of the shipped auth manifest, the piece its declared value goes back through. - **The restore arm in `applySettings`.** The pass keeps the set of keys the running config last took from the store. A key in that set that now resolves `source: 'default'` is restored in the same pass, through the same piece a save of it rides, so the manager judges a restore as it judges a save: - plain options (membership policy, password complexity / classes / history / expiry, MFA grace, the four API-key keys, session idle / absolute / concurrent, lockout pair, `allowed_ip_ranges`) ride the plain patch; - `emailAndPassword` fields (`email_password_enabled`, `signup_enabled`, `require_email_verification`, `password_min_length`, `password_max_length`) are each their own refusable piece; the verification flag restores as the deployment's declaration (#20389), as at boot; - `password_reject_breached` is its own `plugins` piece; - `mfa_required` restores as a save of the declared value would apply: a declared on is one piece with `plugins.twoFactor`, a declared off clears the requirement and leaves the enrollment path standing, exactly as an explicit off does; - `session_expiry_days` / `session_refresh_days` merge over the declared `session` block (a stored field overrides its declared twin; before, a stored field replaced the whole block); - the rate-limit pair and the Google trio restore whole once none of their keys is stored; the audience restores whole once `audience_posture` is not stored, through the same merged-result validation (a sibling still stored without a posture is IGNORED, as before). - A key whose restore the manager refuses stays owed and is retried on the next pass. A key the store never gave a value is never touched (boot restores nothing). Env overrides resolve `source: 'env'` and are unaffected. - **`allowed_ip_ranges`** moves onto the same table; `declaredAllowedIpRanges` / `allowedIpRangesFromSettings` are gone. Its #30203 pins pass unchanged (an undeclared list restores to `undefined`, which the gate reads as open, as `[]` was). - **The sign-in floor (`sign-in-method-floor.ts`, file surface widened by the seat).** The floor read a cleared `email_password_enabled` as on (the manifest default). With clears now applying, a deployment that declared email and password off could clear the toggle into a lockout. Measured before the floor change: declared off + Google, Setup sets email/password on, then Google off, then clears the toggle → 200, and the running config ends `emailPassword.enabled: false` with no provider. The floor now takes an optional `declaredEmailPasswordEnabled()` reader (from `bindAuthSettings`) and judges a cleared toggle at the declaration; the same clear is refused 400 and nothing changes. With another way in standing, the clear saves and applies. ## Tests `packages/plugins/plugin-auth/src/auth-settings-clear.pin.test.ts`, 17 cases, on #30203's composition (real `AuthPlugin`, real `SettingsService` with the shipped auth manifest, real settings routes for the save-door cases): 1. The restore table names exactly the shipped manifest's keys. 2. Plain options: the measured case (declared `lockoutThreshold: 7` back to 7; undeclared max sessions back to `undefined`); password classes + API-key max expiry; a pass about one stored key applies only that key's option (`applyConfigPatch` spy). 3. Refusable pieces: `emailAndPassword` fields; breached-password flag; `mfa_required` to a declared off (enrollment stays) and to a declared on (with `twoFactor`); the floor refuses the clear with no other way in (code, field, `invalid_value`, runtime unchanged) and lets it through with Google standing. 4. Groups: session merge; rate-limit pair; Google; audience (all three cleared; posture alone cleared with siblings stored). 5. Namespace reset across families; an env-pinned `OS_AUTH_LOCKOUT_THRESHOLD` survives a reset. Ablations, each through `scripts/ablation-replace.mjs` (anchor 1 → 0, restored to the HEAD blob, `git diff HEAD` empty; tests import `src/`, no dist in the path): | Ablated | Red | | --- | --- | | A1 plain-patch arm | 7 (incl. all three #30203 clear pins) | | A2 `emailAndPassword` arm | 3 | | A3 `plugins` arm | 1 | | A4 session arm | 1 | | A5 `mfa_required` declared-off arm | 1 | | A6 `mfa_required` declared-on arm | 1 | | A7 rate-limit group | 2 | | A8 Google group | 1 | | A9 audience restore | 2 | | A10 floor reads a clear at the declaration | 1 | | A11 store tracking (restore every unstored key) | 1 (the spy pin) | ## Acceptance notes - With one rate-limit key cleared and the other stored, the explicit branch keeps building the limit with its built-in fallbacks (10 / 60) for the cleared half, not the declared `rateLimit`; unchanged from before. - A deployment that declared `mfaRequired: true` while `OS_AUTH_TWO_FACTOR=false` restores to its own contradictory boot state on a clear; the gate's once-per-process warning (#30201) names it. Not filed: boot already lands there. ## Verification Readings under `scripts/pm/os-verify-lock.sh`, shared box. **Landing head `c22645eb`**: `8b9f159f` plus a merge of `origin/main` at `f506b79d` (29 commits, among them PR #30449 for #30300). One hand resolution, in `auth-plugin.ts`: #30449's one-line `registerSignInMethodFloor(…, this.signInMethodFloorDeps(…), …)` taken, and this PR's `declaredEmailPasswordEnabled` reader moved into that shared constructor (read only by the save floor's batch fallback; the SSO-provider delete floor and the boot report judge the running config). Delta contract review PASS, comment 6659465418. On `c22645eb`, one run under the verify lock (`VERDICT command-exit 0`, every step exit 0): closure build of `dogfood^...` and `service-settings^...`; full dogfood Test Files 419 passed, 3 skipped (422), Tests 3492 passed, 36 skipped (3528); `@objectstack/plugin-auth` test 225/225 files, 3991 passed, 10 skipped (4001); plugin-auth typecheck exit 0 (`check:test-typecheck` OK); `@objectstack/service-settings` test 68/68 files, 1156/1156; service-settings typecheck exit 0. Earlier readings, kept for the record: code head `f58be8f5`; `8b9f159f` was that plus a merge of `origin/main` (23 commits, none touching `auth-plugin.ts`, `sign-in-method-floor.ts` or `service-settings`). <details><summary>Suites and typecheck</summary> - On `8b9f159f`: `pnpm --filter '@objectstack/plugin-auth^...' build && pnpm --filter @objectstack/plugin-auth test && pnpm --filter @objectstack/plugin-auth run typecheck`: `VERDICT command-exit 0`; Test Files 225 passed (225), Tests 3971 passed, 10 skipped (3981); `check:test-typecheck: OK`. (A first run after the merge, before rebuilding the closure, read a stale `@objectstack/spec` dist and failed `public-feature-registry.test.ts` on main's new `emailDelivery` flag; the rebuilt run above is green.) - On `f58be8f5`: the same suite 225/225 files, 3966 passed; `pnpm lint`: exit 0. - The new file alone: 17/17. Ablations as in the table above. </details> <details><summary>Full dogfood battery (owed by the narrowing arm)</summary> On `f58be8f5`: `pnpm --filter '@objectstack/dogfood^...' build && pnpm --filter @objectstack/dogfood test` (no shard, no path): `VERDICT command-exit 0`, held the lock 40m35s; Test Files 419 passed, 3 skipped (422); Tests 3492 passed, 36 skipped (3528); no failure. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 64 commands on `f58be8f5`; each run with its exit code recorded before any pipe. `--ran`: 64 derived, 63 run, 1 NOT-MEASURED, 0 UNRUN. NOT MEASURED: `pnpm check:dual-build-cjs-loads` (exit 3, PREREQUISITE NOT MET: it needs a whole-workspace build; CI runs it). `check-plugin-teardown-shape --self-test` first exited 3 (shallow clone, pinned fixture commit), then 0 after fetching that commit. Every other command exited 0. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZPLJKSBMtARXMHc4W)_ <!-- signed: domain:server#2 · os-bill · session_01Utp6Cbvcmv8YWFhFJwzjKL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent fb1ab89 commit b5765be

5 files changed

Lines changed: 670 additions & 29 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth)!: clearing an authentication setting, or restoring the namespace's defaults, takes effect at once (#30312)
6+
7+
Clause-②: yes (narrowing) — one save an administrator could make before is now refused at the settings save door with the existing `SETTINGS_VALIDATION` / `invalid_value` field error: clearing `auth.email_password_enabled` on a deployment that itself declared email and password off, when nothing else signs anyone in after the save. Before, that clear was saved and changed nothing at runtime; now a clear applies, and that one would lock everyone out. No new error code, settings key or export.
8+
Metadata-protocol: none
9+
Skills-docs: none — no file under `skills/**` teaches the auth settings namespace, its clear or the sign-in floor.
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped: every auth key keeps its declaration. A clear now applies the deployment's own declared value, which is what a clear always documented; the save door refuses only the one clear that would leave no way to sign in. Nothing at rest is rewritten, so there is nothing for a migration to do. -->
12+
13+
**BREAKING** accept-set narrowing at the auth settings save door (`PUT /api/settings/auth`, `SettingsService.setMany('auth', …)`): one clear that was saved before is refused.
14+
15+
- **The fix.** A cleared `auth.*` key (the console sends `null`) or a namespace reset resolves `source: 'default'`. Every key except `allowed_ip_ranges` (#30203) then kept its last stored value in force until a restart: lockout threshold, max sessions per user, password policy, session lifetime, MFA, API-key lifetime, rate limits, Google, audience. Now the running value returns in the same pass to what the deployment declared (plugin options, `auth:configure`), or to the built-in default where it declared nothing. A value in a block the auth manager judges (`emailAndPassword`, `plugins`, `audience`) is restored through that same block, so it is judged as a save of it would be. Environment overrides keep ruling.
16+
- **The refused clear.** With email and password declared off by the deployment and turned on in Setup, and no other way in (Google switched off in Setup, no other provider, no SSO, no phone sign-in, no host handoff), clearing "Enable email/password login" now answers `400 SETTINGS_VALIDATION` at `email_password_enabled` (`constraint.lastSignInMethod: email_password`), and nothing is written. Set up another sign-in method first, or save the toggle on explicitly instead of clearing it.
17+
- **Session lifetime.** A stored `session_expiry_days` / `session_refresh_days` now overrides its field of the deployment's declared `session` block instead of replacing the whole block.

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 140 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,13 @@ import {
131131
import { cloudManagedRefusal } from './cloud-managed.js';
132132
import { registerCopyInvitationLinkAction } from './invitation-link-action.js';
133133
import { allowedIpRangesWritePredicate, parseAllowedIpRanges } from './allowed-ip-ranges.js';
134+
import {
135+
AUTH_SETTING_RESTORE,
136+
captureDeclaredAuthOptions,
137+
copyDeclared,
138+
restoreGroupKeys,
139+
type DeclaredAuthOptions,
140+
} from './auth-settings-declared.js';
134141
import { FORWARDED_CLIENT_ADDRESS_HEADERS } from './client-address-forwarding.js';
135142
import {
136143
runAdminBanUser,
@@ -554,14 +561,19 @@ export class AuthPlugin implements Plugin {
554561
private allowListUndeterminedWarned = false;
555562
private allowListUntrustedHeaderWarned = false;
556563
/**
557-
* [#30203] The allow-list the deployment itself declared (plugin options or
558-
* an `auth:configure` handler), taken before any setting is applied: what
559-
* the running list returns to when the stored `allowed_ip_ranges` is cleared
560-
* or restored to its default.
564+
* [#30203, #30312] What the deployment itself declared (plugin options and
565+
* `auth:configure` handlers) for every option an `auth.*` setting can drive,
566+
* taken before any setting is applied: what the running value returns to when
567+
* the stored key is cleared or restored to its default.
568+
*/
569+
private declaredAuthOptions: DeclaredAuthOptions = {};
570+
/**
571+
* [#30203, #30312] The `auth.*` keys whose stored value the running config
572+
* was last given (or whose restore the manager refused): a key leaving this
573+
* set by resolving `source: 'default'` hands its value back to the
574+
* declaration. Boot never restores, so an unset key costs nothing.
561575
*/
562-
private declaredAllowedIpRanges: string[] | undefined;
563-
/** [#30203] Whether the running allow-list is the one a stored setting gave it. */
564-
private allowedIpRangesFromSettings = false;
576+
private authSettingsFromStore = new Set<string>();
565577
private configuredSocialProviders: SocialProviderConfig | undefined;
566578
/** Whether each provider declared at boot holds a credential pair (the sign-in floor's count). */
567579
private bootProviderCredentials: ReadonlyMap<string, boolean> = new Map();
@@ -801,7 +813,7 @@ export class AuthPlugin implements Plugin {
801813
logger: ctx.logger,
802814
});
803815

804-
this.declaredAllowedIpRanges = authConfig.allowedIpRanges ? [...authConfig.allowedIpRanges] : undefined;
816+
this.declaredAuthOptions = captureDeclaredAuthOptions(authConfig);
805817
// Initialize auth manager with data engine
806818
this.authManager = new AuthManager(authConfig);
807819
// ADR-0092 D6 — remember the storage better-auth will actually use so the
@@ -2070,6 +2082,8 @@ export class AuthPlugin implements Plugin {
20702082
// Read when judged: the index is set in init, after `auth:configure`.
20712083
providerHasCredentials: (provider) => providerCredentialsFrom(this.bootProviderCredentials)(provider),
20722084
env: () => ((globalThis as any)?.process?.env ?? {}) as Record<string, string | undefined>,
2085+
// [#30312] A cleared toggle returns to the declaration: judge it there.
2086+
declaredEmailPasswordEnabled: () => this.declaredAuthOptions.emailAndPassword?.enabled !== false,
20732087
};
20742088
}
20752089

@@ -2161,6 +2175,18 @@ export class AuthPlugin implements Plugin {
21612175
}
21622176

21632177
const isExplicit = (key: string) => (sources[key] ?? 'default') !== 'default';
2178+
// [#30312] A key the running config took from the store that now
2179+
// resolves `source: 'default'` (cleared, or the namespace restored to
2180+
// its defaults) hands its value back to the deployment's declaration in
2181+
// this same pass, through the piece a save of it travels. Without this,
2182+
// every branch below skipped it and the last stored value ruled until a
2183+
// restart while the console showed the default. See auth-settings-declared.ts.
2184+
const declared = this.declaredAuthOptions;
2185+
const restoring = (key: string) => !isExplicit(key) && this.authSettingsFromStore.has(key);
2186+
const groupRestoring = (group: 'rateLimit' | 'google'): string[] => {
2187+
const keys = restoreGroupKeys(group);
2188+
return keys.some(isExplicit) ? [] : keys.filter(restoring);
2189+
};
21642190
const asBoolean = (value: unknown, fallback: boolean): boolean => {
21652191
if (typeof value === 'boolean') return value;
21662192
if (typeof value === 'string') return value.toLowerCase() !== 'false';
@@ -2369,9 +2395,6 @@ export class AuthPlugin implements Plugin {
23692395
const d = asPositiveInt(values.session_refresh_days);
23702396
if (d !== undefined) session.updateAge = d * 86_400;
23712397
}
2372-
if (Object.keys(session).length > 0) {
2373-
patch.session = session as AuthManagerOptions['session'];
2374-
}
23752398

23762399
// Session controls (ADR-0069 D4) — idle / absolute / concurrent. 0 = off;
23772400
// non-negative reader so an explicit 0 disables.
@@ -2393,16 +2416,10 @@ export class AuthPlugin implements Plugin {
23932416
}
23942417

23952418
// Network gating (ADR-0069 D5) — parse the CIDR/IP textarea into a list.
2396-
// [#30203] A cleared or restored-default value resolves with source
2397-
// `default`. It hands the gate back to the deployment's own declaration
2398-
// at once, rather than leaving the last stored list in force until a
2399-
// restart while the console shows the field empty.
2419+
// [#30203] A cleared value hands the gate back to the deployment's own
2420+
// declaration at once (the restore arms below).
24002421
if (isExplicit('allowed_ip_ranges')) {
24012422
patch.allowedIpRanges = parseAllowedIpRanges(values.allowed_ip_ranges);
2402-
this.allowedIpRangesFromSettings = true;
2403-
} else if (this.allowedIpRangesFromSettings) {
2404-
patch.allowedIpRanges = this.declaredAllowedIpRanges ? [...this.declaredAllowedIpRanges] : [];
2405-
this.allowedIpRangesFromSettings = false;
24062423
}
24072424

24082425
// Anti-abuse (ADR-0069 D2) — account lockout (custom, per-identity)
@@ -2477,11 +2494,80 @@ export class AuthPlugin implements Plugin {
24772494
: undefined;
24782495
}
24792496

2480-
const audienceKeys = [
2481-
'audience_posture',
2482-
'audience_allowed_email_domains',
2483-
'audience_self_registration_permission_set',
2484-
];
2497+
// [#30312] The restore arms: each key that left the store goes back to
2498+
// its declared value through the same piece a save of it rides, so a
2499+
// refusable block is judged on a restore exactly as on a save.
2500+
const restoredInPatch: string[] = [];
2501+
let sessionRestoring = false;
2502+
for (const [key, arm] of Object.entries(AUTH_SETTING_RESTORE)) {
2503+
if (!restoring(key)) continue;
2504+
switch (arm.via) {
2505+
case 'patch':
2506+
(patch as Record<string, unknown>)[arm.field] = copyDeclared(declared[arm.field]);
2507+
restoredInPatch.push(key);
2508+
break;
2509+
case 'emailAndPassword':
2510+
// The declared verification flag is the deployment's own
2511+
// declaration, as it was at boot (#20389).
2512+
emailAndPasswordField(
2513+
key,
2514+
{ [arm.field]: declared.emailAndPassword?.[arm.field] },
2515+
arm.field === 'requireEmailVerification' ? { requireEmailVerificationFrom: 'deployment' } : undefined,
2516+
);
2517+
break;
2518+
case 'plugins':
2519+
refusable.push({
2520+
key,
2521+
patch: {
2522+
plugins: {
2523+
[arm.field]: (declared.plugins as Record<string, unknown> | undefined)?.[arm.field],
2524+
} as AuthManagerOptions['plugins'],
2525+
},
2526+
});
2527+
break;
2528+
case 'session':
2529+
sessionRestoring = true;
2530+
restoredInPatch.push(key);
2531+
break;
2532+
case 'mfaRequired':
2533+
// As a save of the declared value: on is one piece with its
2534+
// enrollment path; off leaves enrolled factors verifiable.
2535+
if (declared.mfaRequired === true) {
2536+
refusable.push({
2537+
key,
2538+
patch: { mfaRequired: true, plugins: { twoFactor: true } as AuthManagerOptions['plugins'] },
2539+
});
2540+
} else {
2541+
patch.mfaRequired = declared.mfaRequired;
2542+
restoredInPatch.push(key);
2543+
}
2544+
break;
2545+
case 'group':
2546+
break;
2547+
}
2548+
}
2549+
// Session lifetime rides one `session` block, merged over the declared
2550+
// one: a stored field overrides its declared twin, the rest stand.
2551+
if (Object.keys(session).length > 0 || sessionRestoring) {
2552+
const merged = { ...(declared.session ?? {}), ...session };
2553+
patch.session = (Object.keys(merged).length > 0 ? merged : copyDeclared(declared.session)) as
2554+
AuthManagerOptions['session'];
2555+
}
2556+
const rateLimitRestoring = groupRestoring('rateLimit');
2557+
if (rateLimitRestoring.length > 0) {
2558+
patch.rateLimit = copyDeclared(declared.rateLimit);
2559+
restoredInPatch.push(...rateLimitRestoring);
2560+
}
2561+
const googleRestoring = groupRestoring('google');
2562+
if (googleRestoring.length > 0) {
2563+
const configured = this.configuredSocialProviders ? { ...this.configuredSocialProviders } : undefined;
2564+
patch.socialProviders = configured && Object.keys(configured).length > 0 ? configured : undefined;
2565+
restoredInPatch.push(...googleRestoring);
2566+
}
2567+
// Keys whose restore the manager refused: still owed on the next pass.
2568+
const owed: string[] = [];
2569+
2570+
const audienceKeys = restoreGroupKeys('audience');
24852571

24862572
// [#20412] Each piece is applied in its own `try`, so a refusal is
24872573
// contained to the piece it names. `error`, not `warn` (AGENTS.md,
@@ -2497,6 +2583,7 @@ export class AuthPlugin implements Plugin {
24972583
try {
24982584
authManager.applyConfigPatch(piece, options);
24992585
} catch (refusal: any) {
2586+
owed.push(...keys.filter(restoring));
25002587
const named = keys.map((key) => `auth.${key}`).join(', ');
25012588
ctx.logger.error(
25022589
`[auth] auth settings REFUSED (${named}) — the standing runtime value keeps ruling while the settings ` +
@@ -2508,9 +2595,12 @@ export class AuthPlugin implements Plugin {
25082595
if (Object.keys(patch).length > 0) {
25092596
const pieceKeys = new Set(refusable.map((piece) => piece.key));
25102597
applyPiece(
2511-
Object.keys(values).filter(
2512-
(key) => isExplicit(key) && !pieceKeys.has(key) && !audienceKeys.includes(key),
2513-
),
2598+
[
2599+
...Object.keys(values).filter(
2600+
(key) => isExplicit(key) && !pieceKeys.has(key) && !audienceKeys.includes(key),
2601+
),
2602+
...restoredInPatch,
2603+
],
25142604
patch,
25152605
);
25162606
}
@@ -2548,6 +2638,24 @@ export class AuthPlugin implements Plugin {
25482638
// Missing required siblings are NOT guessed: the patch goes out
25492639
// without them and `applyConfigPatch` refuses the merged result
25502640
// (standing config keeps ruling — refusing to OPEN fails closed).
2641+
// [#30312] No posture stored any more (cleared, or the namespace
2642+
// restored) while an audience key had been: the declared audience comes
2643+
// back whole, judged by the same merged-result validation. A sibling
2644+
// still stored without a posture is then IGNORED as below.
2645+
if (!isExplicit('audience_posture')) {
2646+
const audienceRestoring = audienceKeys.filter(restoring);
2647+
if (audienceRestoring.length > 0) {
2648+
try {
2649+
authManager.applyConfigPatch({ audience: copyDeclared(declared.audience) });
2650+
} catch (audienceErr: any) {
2651+
owed.push(...audienceRestoring);
2652+
ctx.logger.error(
2653+
`[auth] audience settings REFUSED — the standing posture ('${authManager.getAudience().posture}') keeps ruling. ` +
2654+
String(audienceErr?.message ?? audienceErr),
2655+
);
2656+
}
2657+
}
2658+
}
25512659
if (audienceKeys.some((key) => isExplicit(key))) {
25522660
const rawPosture = values.audience_posture;
25532661
if (!isExplicit('audience_posture')) {
@@ -2601,6 +2709,11 @@ export class AuthPlugin implements Plugin {
26012709
}
26022710
}
26032711
}
2712+
2713+
this.authSettingsFromStore = new Set([
2714+
...Object.keys(AUTH_SETTING_RESTORE).filter(isExplicit),
2715+
...owed,
2716+
]);
26042717
} catch (err: any) {
26052718
// [#20412] A refusal no longer reaches here — each piece above
26062719
// contains its own. What does is a pass that failed as a whole, the

0 commit comments

Comments
 (0)