Skip to content

Commit 8767d6a

Browse files
committed
fix(service-settings,plugin-auth): a write predicate sees only the request headers it names; the refusal says no entry matches
Contract review 6650936040: the route handed every predicate the whole header table. registerWritePredicate now takes requestHeaders, and the allow-list predicate names the forwarded-address headers alone. The refusal says no entry matches the address (an IPv6 CIDR entry matches nothing today), and the settings slot's predicate input is unknown. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6Ca3N2EsTAqg7jhabeL
1 parent 89ff3aa commit 8767d6a

8 files changed

Lines changed: 191 additions & 25 deletions

File tree

‎.changeset/30203-allowed-ip-ranges-live.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
fix(plugin-auth)!: clearing the allowed IP ranges applies at once, and a console save that leaves out the saving address is refused
77

8-
Clause-②: no (narrowing) — a settings console save (`PUT /api/settings/auth`) of an `allowed_ip_ranges` list that leaves out the saving request's own address is refused, where it was stored before; nothing is widened.
8+
Clause-②: yes (narrowing) — a settings console save (`PUT /api/settings/auth`) of an `allowed_ip_ranges` list none of whose entries matches the saving request's own address is refused, where it was stored before; and `@objectstack/service-settings` widens its published surface: three new exported types (`SettingsWriteOptions`, `SettingsRequestTransport`, `SettingsWritePredicateOptions`), `setMany`'s fourth parameter accepts `SettingsWriteOptions`, `registerWritePredicate` takes an optional fourth `options`, and `SettingsWritePredicateInput` gains an optional `transport`.
99
Metadata-protocol: none
1010
Skills-docs: none — `skills/**` teaches no `allowed_ip_ranges`; `content/docs/permissions/authentication.mdx` describes the setting and does not yet state the save refusal or the recovery, which ship here in the refusal text and this entry (the page is outside this change's surface and is named for a follow-up).
1111

@@ -14,7 +14,7 @@ Skills-docs: none — `skills/**` teaches no `allowed_ip_ranges`; `content/docs/
1414
**BREAKING** for an administrator who saves, through the settings console, an allowed-IP list (ADR-0069 D5) that does not include the address they are connected from.
1515

1616
- **Clearing applies at once.** The console sends an emptied field as `null`, which resolves with source `default`, and the settings binding used to skip a default-sourced `allowed_ip_ranges`: the last stored list kept refusing sign-in (`403 IP_NOT_ALLOWED`) until a restart while the field showed empty. A cleared or restored-default value now hands the gate back to the deployment's own declaration in the same pass: no list when it declared none, the `allowedIpRanges` the plugin options or an `auth:configure` handler declared otherwise.
17-
- **The save is refused.** A list that leaves out the saving request's address is refused with `400 SETTINGS_VALIDATION`, `invalid_value` at `allowed_ip_ranges`, the address in `constraint.clientAddress`, and a message in the caller's language that names it. The address is the one the gate judges at sign-in: the transport's peer address, or the forwarded one when the stack declares `server.trustProxy`. When the server cannot establish the address, every non-empty list is refused, because the gate would refuse that request too. Clearing the list is never refused, and an in-process write (boot, seed, migration) carries no request and is not judged.
17+
- **The save is refused.** A list no entry of which matches the saving request's address is refused with `400 SETTINGS_VALIDATION`, `invalid_value` at `allowed_ip_ranges`, the address in `constraint.clientAddress`, and a message in the caller's language that names it. The address is the one the gate judges at sign-in: the transport's peer address, or the forwarded one when the stack declares `server.trustProxy`. When the server cannot establish the address, every non-empty list is refused, because the gate would refuse that request too. Clearing the list is never refused, and an in-process write (boot, seed, migration) carries no request and is not judged.
1818
- **Recovery when already locked out.** Start the server with `OS_AUTH_ALLOWED_IP_RANGES` set to an empty value. The settings env override wins over the stored list and opens the gate; remove it once the list is fixed.
19-
- **`@objectstack/service-settings`.** `setMany`'s options (`SettingsWriteOptions`) and a write predicate's input gain an optional `transport` (`SettingsRequestTransport`: the request headers and the transport's peer address), which the settings routes set on a save so a write predicate can judge the change against the caller's own connection. It identifies and authorizes nothing and is never stored.
19+
- **`@objectstack/service-settings`.** `setMany`'s options (`SettingsWriteOptions`) and a write predicate's input gain an optional `transport` (`SettingsRequestTransport`: the transport's peer address and request headers), which the settings routes set on a save so a write predicate can judge the change against the caller's own connection. A predicate sees only the headers it names at registration (`registerWritePredicate(…, { requestHeaders })`, `SettingsWritePredicateOptions`), so a credential header never reaches one that did not ask for it. The transport identifies and authorizes nothing and is never stored.
2020
- **Who moves.** An administrator adds their own address or range to the list, or saves it from an address inside it.

‎packages/plugins/plugin-auth/src/allowed-ip-ranges.ts‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,8 @@ interface RefusalCopy {
8484
const COPY: Record<'en' | 'zh-CN' | 'ja-JP' | 'es-ES', RefusalCopy> = {
8585
en: {
8686
outside: (address) =>
87-
`This list does not include ${address}, the address you are connected from, so saving it would refuse your own `
88-
+ 'next sign-in. Add your address or its range to the list, or save the list from an address inside it.',
87+
`No entry in this list matches ${address}, the address you are connected from, so saving it would refuse your `
88+
+ 'own next sign-in. Add your address or its range to the list, or save the list from an address it matches.',
8989
undetermined:
9090
'The server cannot establish the address you are connected from, and while any list is set it refuses every '
9191
+ 'such request, your own next sign-in included. Save the list from a connection whose address the server can '
@@ -94,27 +94,27 @@ const COPY: Record<'en' | 'zh-CN' | 'ja-JP' | 'es-ES', RefusalCopy> = {
9494
},
9595
'zh-CN': {
9696
outside: (address) =>
97-
`这份列表不包含你当前连接所用的地址 ${address},保存后你自己下一次登录就会被拒绝。`
98-
+ '请把你的地址或所在网段加进列表,或在列表内的地址上保存。',
97+
`这份列表中没有任何一项与你当前连接所用的地址 ${address} 匹配,保存后你自己下一次登录就会被拒绝。`
98+
+ '请把你的地址或所在网段加进列表,或在列表能匹配的地址上保存。',
9999
undetermined:
100100
'服务器无法确定你当前连接所用的地址;只要设置了列表,这样的请求都会被拒绝,你自己下一次登录也不例外。'
101101
+ '请在服务器能确定地址的连接上保存。',
102102
recovery: `如果已被锁在外面,可将环境变量 ${ALLOWED_IP_RANGES_ENV} 设为空值后重启服务器。`,
103103
},
104104
'ja-JP': {
105105
outside: (address) =>
106-
`このリストには、現在接続しているアドレス ${address} が含まれていないため、保存するとご自身の次回のサインインが拒否されます。`
107-
+ 'ご自身のアドレスまたはその範囲をリストに追加するか、リスト内のアドレスから保存してください。',
106+
`このリストには、現在接続しているアドレス ${address} に一致する項目がないため、保存するとご自身の次回のサインインが拒否されます。`
107+
+ 'ご自身のアドレスまたはその範囲をリストに追加するか、リストに一致するアドレスから保存してください。',
108108
undetermined:
109109
'サーバーは現在の接続のアドレスを確定できません。リストが設定されている間はそのようなリクエストはすべて拒否され、'
110110
+ 'ご自身の次回のサインインも同様です。サーバーがアドレスを確定できる接続から保存してください。',
111111
recovery: `締め出された場合は、環境変数 ${ALLOWED_IP_RANGES_ENV} を空の値にしてサーバーを再起動してください。`,
112112
},
113113
'es-ES': {
114114
outside: (address) =>
115-
`Esta lista no incluye ${address}, la dirección desde la que está conectado, así que al guardarla se rechazaría `
116-
+ 'su propio próximo inicio de sesión. Añada su dirección o su rango a la lista, o guarde la lista desde una '
117-
+ 'dirección incluida en ella.',
115+
`Ninguna entrada de esta lista coincide con ${address}, la dirección desde la que está conectado, así que al `
116+
+ 'guardarla se rechazaría su propio próximo inicio de sesión. Añada su dirección o su rango a la lista, o guarde '
117+
+ 'la lista desde una dirección con la que coincida.',
118118
undetermined:
119119
'El servidor no puede determinar la dirección desde la que está conectado y, mientras haya una lista, rechaza '
120120
+ 'todas esas solicitudes, incluido su propio próximo inicio de sesión. Guarde la lista desde una conexión cuya '
@@ -136,8 +136,10 @@ function copyFor(locale: string | undefined): RefusalCopy {
136136
*/
137137
export function allowedIpRangesWritePredicate(
138138
manager: () => Pick<AuthManager, 'resolveClientAddress'> | null | undefined,
139-
): (input: AllowedIpRangesWriteInput) => AllowedIpRangesWriteRefusal | undefined {
140-
return ({ next, transport, locale }) => {
139+
): (input: unknown) => AllowedIpRangesWriteRefusal | undefined {
140+
return (input) => {
141+
// The settings write predicate's input (`SettingsWritePredicateInput`), read structurally.
142+
const { next, transport, locale } = (input ?? {}) as AllowedIpRangesWriteInput;
141143
if (!transport) return undefined;
142144
const ranges = parseAllowedIpRanges(next);
143145
if (ranges.length === 0) return undefined;

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ import {
121121
import { cloudManagedRefusal } from './cloud-managed.js';
122122
import { registerCopyInvitationLinkAction } from './invitation-link-action.js';
123123
import { allowedIpRangesWritePredicate, parseAllowedIpRanges } from './allowed-ip-ranges.js';
124+
import { FORWARDED_CLIENT_ADDRESS_HEADERS } from './client-address-forwarding.js';
124125
import {
125126
runAdminBanUser,
126127
runAdminUnbanUser,
@@ -179,7 +180,12 @@ interface SettingsReadSurface {
179180
* the write lands (`SettingsService.registerWritePredicate`). Optional, like
180181
* `subscribe`.
181182
*/
182-
registerWritePredicate?(namespace: string, key: string, predicate: (input: any) => unknown): void;
183+
registerWritePredicate?(
184+
namespace: string,
185+
key: string,
186+
predicate: (input: unknown) => unknown,
187+
options?: { requestHeaders?: readonly string[] },
188+
): void;
183189
}
184190

185191
/** [#23367] The auth setting that records when the API-key lifecycle policy took effect. */
@@ -2537,6 +2543,8 @@ export class AuthPlugin implements Plugin {
25372543
'auth',
25382544
'allowed_ip_ranges',
25392545
allowedIpRangesWritePredicate(() => this.authManager),
2546+
// Only the forwarded-address headers the address rule reads reach it.
2547+
{ requestHeaders: FORWARDED_CLIENT_ADDRESS_HEADERS },
25402548
);
25412549
} catch (err: any) {
25422550
ctx.logger.warn(

‎packages/services/service-settings/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ export {
6060
type SettingsWriteRefusal,
6161
type SettingsDisplayOptions,
6262
type SettingsWriteOptions,
63+
type SettingsWritePredicateOptions,
6364
SETTINGS_LIVE_STATUS_BANNER_ID,
6465
type SettingsAuditSink,
6566
type SettingsContext,

‎packages/services/service-settings/src/settings-routes.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,8 @@ export function registerSettingsRoutes(
357357
ctx,
358358
// The language a write predicate's refusal is written in, and [#30203]
359359
// the request's own connection, for a predicate that judges the change
360-
// against it (`SettingsWriteOptions.transport`).
360+
// against it (`SettingsWriteOptions.transport`). Each predicate sees
361+
// only the headers it named at registration (`narrowTransport`).
361362
{
362363
locale: requestLocaleOf(req),
363364
transport: {

‎packages/services/service-settings/src/settings-service.ts‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ import {
2323
type SettingsLiveStatus,
2424
type SettingsLiveStatusProvider,
2525
type SettingsWritePredicate,
26+
type SettingsWritePredicateOptions,
27+
type SettingsRequestTransport,
2628
type SettingsDisplayOptions,
2729
type SettingsWriteOptions,
2830
SETTINGS_LIVE_STATUS_BANNER_ID,
@@ -894,7 +896,10 @@ export class SettingsService {
894896
/** Live-status providers by namespace — see {@link registerLiveStatus}. */
895897
private readonly liveStatusProviders = new Map<string, SettingsLiveStatusProvider>();
896898
/** Write predicates by namespace, then key — see {@link registerWritePredicate}. */
897-
private readonly writePredicates = new Map<string, Map<string, SettingsWritePredicate>>();
899+
private readonly writePredicates = new Map<
900+
string,
901+
Map<string, { predicate: SettingsWritePredicate; requestHeaders: ReadonlySet<string> }>
902+
>();
898903
/** Change subscribers, optionally scoped to a namespace. */
899904
private readonly subscribers = new Set<{
900905
ns?: string;
@@ -1660,15 +1665,24 @@ export class SettingsService {
16601665
* Register (or replace) the write predicate of one manifest key — a rule
16611666
* over engine state that may refuse a CHANGE to the key. See
16621667
* {@link SettingsWritePredicate}. The last registration wins, the same
1663-
* override rule as {@link registerAction}.
1668+
* override rule as {@link registerAction}. `options.requestHeaders` names the
1669+
* request headers the predicate may read ({@link SettingsWritePredicateOptions}).
16641670
*/
1665-
registerWritePredicate(namespace: string, key: string, predicate: SettingsWritePredicate): void {
1671+
registerWritePredicate(
1672+
namespace: string,
1673+
key: string,
1674+
predicate: SettingsWritePredicate,
1675+
options: SettingsWritePredicateOptions = {},
1676+
): void {
16661677
const reg = this.registry.get(namespace);
16671678
if (!reg) throw new UnknownNamespaceError(namespace);
16681679
if (!reg.scopes.has(key)) throw new UnknownKeyError(namespace, key);
16691680
let byKey = this.writePredicates.get(namespace);
16701681
if (!byKey) this.writePredicates.set(namespace, (byKey = new Map()));
1671-
byKey.set(key, predicate);
1682+
byKey.set(key, {
1683+
predicate,
1684+
requestHeaders: new Set((options.requestHeaders ?? []).map((name) => name.toLowerCase())),
1685+
});
16721686
}
16731687

16741688
/**
@@ -2673,8 +2687,9 @@ export class SettingsService {
26732687
if (!byKey) return;
26742688
const refusals: FieldError[] = [];
26752689
for (const [key, submitted] of Object.entries(patch)) {
2676-
const predicate = byKey.get(key);
2677-
if (!predicate) continue;
2690+
const registered = byKey.get(key);
2691+
if (!registered) continue;
2692+
const { predicate } = registered;
26782693
const next = submitted ?? null;
26792694
const current = (await this.get(namespace, key, ctx)).value ?? null;
26802695
if (stableStringify(next) === stableStringify(current)) continue;
@@ -2688,7 +2703,7 @@ export class SettingsService {
26882703
organizationId,
26892704
ctx,
26902705
locale: display.locale,
2691-
...(display.transport ? { transport: display.transport } : {}),
2706+
...(display.transport ? { transport: narrowTransport(display.transport, registered.requestHeaders) } : {}),
26922707
});
26932708
if (!refusal) continue;
26942709
const spec = ((reg.manifest.specifiers ?? []) as Array<Record<string, unknown>>)
@@ -3807,6 +3822,24 @@ function stableStringify(input: unknown): string {
38073822
}
38083823

38093824
/** Re-typed env coercer (the canonical one lives in settings-service.types). */
3825+
/**
3826+
* [#30203] The request as one write predicate sees it: the peer address, and
3827+
* only the headers it named at registration.
3828+
*/
3829+
function narrowTransport(
3830+
transport: SettingsRequestTransport,
3831+
names: ReadonlySet<string>,
3832+
): SettingsRequestTransport {
3833+
const headers: Record<string, string | string[] | undefined> = {};
3834+
for (const [name, value] of Object.entries(transport.headers ?? {})) {
3835+
if (names.has(name.toLowerCase())) headers[name] = value;
3836+
}
3837+
return {
3838+
headers,
3839+
...(transport.remoteAddress ? { remoteAddress: transport.remoteAddress } : {}),
3840+
};
3841+
}
3842+
38103843
function coerceEnvValue(raw: string, hint: unknown): unknown {
38113844
if (typeof hint === 'boolean') return raw === 'true' || raw === '1' || raw === 'yes';
38123845
if (typeof hint === 'number') {

‎packages/services/service-settings/src/settings-service.types.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -380,12 +380,25 @@ export interface SettingsWritePredicateInput {
380380
/** The language the refusal is written in — {@link SettingsDisplayOptions.locale}. */
381381
locale?: string;
382382
/**
383-
* [#30203] The request the write arrived on ({@link SettingsWriteOptions.transport});
384-
* absent on an in-process write.
383+
* [#30203] The request the write arrived on ({@link SettingsWriteOptions.transport}),
384+
* narrowed to the headers this predicate declared at registration
385+
* ({@link SettingsWritePredicateOptions.requestHeaders}); absent on an
386+
* in-process write.
385387
*/
386388
transport?: SettingsRequestTransport;
387389
}
388390

391+
/** [#30203] How a {@link SettingsWritePredicate} is registered. */
392+
export interface SettingsWritePredicateOptions {
393+
/**
394+
* The request headers the predicate reads, lower-case. Only these reach its
395+
* `transport.headers`, so a credential header (`cookie`, `authorization`, an
396+
* API key) never reaches a predicate that did not name it. None named: the
397+
* predicate sees the peer address and no header.
398+
*/
399+
requestHeaders?: readonly string[];
400+
}
401+
389402
/**
390403
* A predicate's refusal. `message` is the sentence the caller reads under the
391404
* field, written in the input's `locale`; `constraint` carries its discrete values

0 commit comments

Comments
 (0)