diff --git a/.changeset/30924-ip-allow-list-refusal-audit-rows.md b/.changeset/30924-ip-allow-list-refusal-audit-rows.md new file mode 100644 index 00000000000..1db83ff917b --- /dev/null +++ b/.changeset/30924-ip-allow-list-refusal-audit-rows.md @@ -0,0 +1,18 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/plugin-audit': patch +--- + +feat(plugin-auth, plugin-audit): a sign-in the IP allow-list refuses leaves one `login_failed` row in the audit log, bounded per client address + +Clause-②: yes (widening) +Metadata-protocol: none + +A sign-in refused by the ADR-0069 D5 IP allow-list used to leave nothing in `sys_audit_log`: the deployment's list answered `403 IP_NOT_ALLOWED` with only a once-per-process operator line, and an organization's own list refused the session silently. Both now write a `login_failed` row with `metadata.reason: "IP_NOT_ALLOWED"`, `metadata.rule: "ip_allow_list"`, `metadata.endpoint` and `metadata.attempts`, and the client address and user agent in `ip_address` / `user_agent`: + +- **The deployment's list** refuses before any account is resolved. Its row names the account when the request's `email` resolves to one (the password sign-in's own account lookup), and is written with no account otherwise. Only `/sign-in/*` endpoints are recorded; a refused session read or sign-out is not a sign-in. The row is written off the response path, so the refusal's status, body and timing do not depend on whether the address names an account. +- **An organization's own list** refuses when the session is created. Its row names the account and the organization (`tenant_id`). A refused switch of the active organization is not a sign-in and writes no row. + +The rows are bounded so a scanner cannot flood the table: per client address, in a 10-minute window from its first refusal, only the 1st, 10th and 100th refusal write a row (`attempts` 1, 10, 100); across all addresses, at most 1000 rows per 10-minute window, with one operator `warn` line in a window once the cap drops a row. The bound is held in each server process, so N replicas write up to N times as many rows. No row carries the submitted identifier or the password. + +`@objectstack/plugin-audit`'s `AuthSessionAuditEvent.userId` and `@objectstack/plugin-auth`'s `AuthEventAuditSurface` event `userId` are now optional: a `login_failed` with no `userId` is written with `user_id` and `record_id` null (a row about no record, read under the ledger's own grant, platform administrators only when it names no organization). Any other event without a `userId` still writes nothing. `AuthManager.resolveRefusedSignInAccountId(email)` is new: the account a refused sign-in names, used only for that row. A sink registered on the `audit` service slot now receives `login_failed` events with no `userId`, so a custom sink must accept one. The exported `signInFailureEventFor` now answers `null` for `reason: 'IP_NOT_ALLOWED'`, because the door that refused the sign-in writes that row itself. diff --git a/content/docs/kernel/runtime-services/audit-service.mdx b/content/docs/kernel/runtime-services/audit-service.mdx index 91bd3f8eb96..f8480f654ec 100644 --- a/content/docs/kernel/runtime-services/audit-service.mdx +++ b/content/docs/kernel/runtime-services/audit-service.mdx @@ -29,7 +29,7 @@ The slot's entire surface is one method: ```ts services.audit.recordAuthEvent(event: { action: 'login' | 'logout' | 'login_failed' | 'account_locked'; - userId: string; + userId?: string; sessionId?: string; organizationId?: string; ipAddress?: string; @@ -46,11 +46,17 @@ services.audit.recordAuthEvent(event: { hands over an **event** (what happened) rather than a row (what to store). - `login` / `logout` are **session events**: a sign-in that minted a session, and a sign-out. - - `login_failed` / `account_locked` are **account events**: a refused password sign-in - that named an existing account, and the refused sign-in that stamped the account + - `login_failed` / `account_locked` are **account events**: a refused sign-in — a + password sign-in that named an existing account, or any `/sign-in/*` request the IP + allow-list refused (ADR-0069 D5) — and the refused sign-in that stamped the account lockout (`lockoutThreshold`, ADR-0069 D2). They exist without any session. -- **`userId`** is required and must be a real `sys_user` id — it lands on the strict - `user_id` lookup. On an account event it is the account the sign-in named. +- **`userId`** must be a real `sys_user` id when given — it lands on the strict `user_id` + lookup. On an account event it is the account the sign-in named. Every event names one + except a `login_failed` refused before any account could be resolved: the deployment's + IP allow-list refuses ahead of better-auth, and the identifier the request carried may + name no account. That row is written with `user_id` and `record_id` null — a row about + no record, read under the ledger's own grant — and still carries the client address and + the rule. Any other event without a `userId` writes nothing. - **`sessionId`** lands on `record_id`, with `object_name` set to `sys_session`, so the ledger row is navigable to the session it describes. An account event names its account instead — `object_name` `sys_user` and `record_id` the account's id — and does not read @@ -67,9 +73,23 @@ services.audit.recordAuthEvent(event: { because a refused attempt authenticated nobody. - **`context`** is free-form and is serialized into `metadata`, e.g. the endpoint that produced the event (`/sign-in/email`, `/sign-out`). On an account event it is the - endpoint, the refusal's machine code (`reason`, e.g. `INVALID_EMAIL_OR_PASSWORD` or - `ACCOUNT_LOCKED`) and, for `account_locked`, the lock's `locked_until` and `threshold`. - It never carries the attempted credential. + endpoint, the refusal's machine code (`reason`, e.g. `INVALID_EMAIL_OR_PASSWORD`, + `ACCOUNT_LOCKED` or `IP_NOT_ALLOWED`) and, for `account_locked`, the lock's `locked_until` + and `threshold`. It never carries the attempted credential. + - A sign-in an authentication **policy** holds or refuses also names the policy, in + `rule`. A sign-in held by enforced MFA (ADR-0069 D3) is not refused — the session is + minted — so its own `login` row carries `reason: 'MFA_REQUIRED'` and + `rule: 'mfa_required'`. A sign-in the IP allow-list refuses (ADR-0069 D5), by the + deployment's list or by the organization's own list when the session is created, is a + `login_failed` with `reason: 'IP_NOT_ALLOWED'`, `rule: 'ip_allow_list'` and + `attempts`, below; the organization's refusal also names the organization. A refused + switch of the active organization is not a sign-in and writes no row. + - IP allow-list rows are **bounded** so a scanner cannot flood the ledger: per client + address, in a 10-minute window from its first refusal, only the 1st, 10th and 100th + refusal write a row, carrying that count as `attempts`; across all addresses, at most + 1000 rows per 10-minute window, with one operator `warn` line in a window once the cap + drops a row. The bound is held in each server process, so N replicas write up to N + times as many rows. ## Notes @@ -80,8 +100,9 @@ services.audit.recordAuthEvent(event: { reference from the moment the plugin initializes. - `@objectstack/plugin-auth` is the only in-repo consumer. It resolves the slot lazily through a locally-declared structural surface and calls it from the session lifecycle - and from the password sign-in outcome, so neither package depends on the other. A - sign-in identifier that resolves to no account produces no call. + and from the sign-in outcomes, so neither package depends on the other. A password + sign-in whose identifier resolves to no account produces no call; an IP allow-list + refusal produces one with no `userId`. ## Typical Errors @@ -98,8 +119,9 @@ caller's side: `error` line, once. The sign-in was answered exactly as it would have been without the ledger, so the shipped `auth_events` list view and the system-overview widgets keep showing an empty, healthy-looking screen. -- The call **silently no-ops** when no data engine resolves, or when `userId` is absent. - A caller that passes an event without a subject records nothing and is told nothing. +- The call **silently no-ops** when no data engine resolves, or when `userId` is absent on + any event but `login_failed`. A caller that passes such an event records nothing and is + told nothing. - The most common cause of a failing insert is a datasource split rather than a broken write: `sys_audit_log` carries an ADR-0057 `audit` lifecycle class, which routes it to a dedicated `telemetry` datasource whenever one is registered — `os dev` provisions one by diff --git a/packages/plugins/plugin-audit/src/auth-event-audit.test.ts b/packages/plugins/plugin-audit/src/auth-event-audit.test.ts index dc9ffe4d38a..a2b298a3a4c 100644 --- a/packages/plugins/plugin-audit/src/auth-event-audit.test.ts +++ b/packages/plugins/plugin-audit/src/auth-event-audit.test.ts @@ -620,3 +620,54 @@ describe('auth-event audit — reported once per CAUSE, not once per process (#1 expect(warns[1].message).toMatch(/ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED/); }); }); + +/** + * [#30924] A sign-in the IP allow-list refuses is refused before any account + * is resolved, and the identifier it carried may name no account at all. Its + * `login_failed` row is still worth writing — the address and the rule are + * the record an enforcement report reads — so a `login_failed` is the one + * event that may name no subject. Every other event still needs one. + */ +describe('[#30924] a login_failed with no resolvable account is still a row', () => { + it('a subject-less login_failed lands about no record, credits nobody, and keeps the address and the rule', async () => { + const { engine } = await boot(); + const sink = createAuthEventAuditSink({ getEngine: () => engine as any }); + + await sink.recordAuthEvent({ + action: 'login_failed', + ipAddress: '198.51.100.9', + userAgent: 'scanner/1.0', + context: { endpoint: '/sign-in/email', reason: 'IP_NOT_ALLOWED', rule: 'ip_allow_list', attempts: 1 }, + }); + + const rows = await ledgerRows(engine, { action: 'login_failed' }); + expect(rows).toHaveLength(1); + const [row] = rows; + expect(row.user_id ?? null).toBeNull(); + expect(row.object_name).toBe('sys_user'); + expect(row.record_id ?? null).toBeNull(); + expect(row.actor ?? null).toBeNull(); + expect(row.tenant_id ?? null).toBeNull(); + expect(row.ip_address).toBe('198.51.100.9'); + expect(row.user_agent).toBe('scanner/1.0'); + expect(JSON.parse(String(row.metadata))).toEqual({ + endpoint: '/sign-in/email', + reason: 'IP_NOT_ALLOWED', + rule: 'ip_allow_list', + attempts: 1, + }); + }); + + it('every other event still needs its subject: no row', async () => { + const { engine } = await boot(); + const sink = createAuthEventAuditSink({ getEngine: () => engine as any }); + + await sink.recordAuthEvent({ action: 'login', sessionId: 'ses_1' }); + await sink.recordAuthEvent({ action: 'logout', sessionId: 'ses_1' }); + await sink.recordAuthEvent({ action: 'account_locked', context: { threshold: 3 } }); + await sink.recordAuthEvent({ action: 'login_failed', userId: '' }); + + expect(await ledgerRows(engine)).toHaveLength(1); + expect((await ledgerRows(engine, { action: 'login_failed' }))[0].user_id ?? null).toBeNull(); + }); +}); diff --git a/packages/plugins/plugin-audit/src/auth-event-audit.ts b/packages/plugins/plugin-audit/src/auth-event-audit.ts index df456a06ed8..4914c04ac14 100644 --- a/packages/plugins/plugin-audit/src/auth-event-audit.ts +++ b/packages/plugins/plugin-audit/src/auth-event-audit.ts @@ -75,6 +75,11 @@ * credited with it, and recording the account holder there would claim * they made the attempt. * + * A `login_failed` whose sign-in was refused before any account resolved + * (the IP allow-list, #30924) names no account: `user_id` and `record_id` are + * null, so it is a row about no record, read under the ledger's own grant, and + * still carries the client address and the refusing rule. + * * ⛔ An account event never carries the attempted credential, in any form. * Its `context` is the endpoint, the refusal's machine code and, for a * lockout, the lock's expiry and threshold — nothing the caller typed. @@ -130,8 +135,14 @@ export interface AuthSessionAuditEvent { * The event's subject — a real `sys_user` id (the `user_id` lookup): the * session's owner for a session event, the account the sign-in named for an * account event. + * + * [#30924] Optional for one event only: a `login_failed` whose sign-in was + * refused before any account could be resolved (the IP allow-list refuses + * ahead of better-auth, and the identifier may name no account) is still + * written, about no record and attributed to nobody. Every other event + * without a subject writes no row. */ - userId: string; + userId?: string; /** * The `sys_session` row a SESSION event is about, when known. An account * event names its account instead (module note), so this is not read for @@ -206,6 +217,15 @@ export interface AuthEventAuditSinkOptions { logger?: AuthEventAuditLogger; } +/** + * [#30924] Whether an event of `action` is written with no subject: only a + * refused sign-in (`login_failed`), whose refusal may come before any account + * is resolved. A session needs its owner and a lockout its account. + */ +function mayNameNoSubject(action: unknown): boolean { + return action === 'login_failed'; +} + /** The object a session event's row names as its target. */ const SESSION_OBJECT = 'sys_session'; @@ -354,7 +374,9 @@ export function createAuthEventAuditSink(opts: AuthEventAuditSinkOptions): AuthE return { async recordAuthEvent(event: AuthSessionAuditEvent): Promise { const engine = getEngine(); - if (!engine || !event?.userId) return; + if (!engine || !event) return; + const subject = typeof event.userId === 'string' && event.userId.length > 0 ? event.userId : undefined; + if (!subject && !mayNameNoSubject(event.action)) return; if (probe === undefined || probedEngine !== engine) { probe = createFieldPresenceProbe(engine); probedEngine = engine; @@ -367,13 +389,14 @@ export function createAuthEventAuditSink(opts: AuthEventAuditSinkOptions): AuthE action: event.action, // The whole point of the card: the event names its actor. `user_id` is // a strict `sys_user` lookup, and a session always has a real subject. - // On an account event it is the account the sign-in named. - user_id: event.userId, + // On an account event it is the account the sign-in named, and null + // for a refused sign-in that named none (#30924). + user_id: subject ?? null, // The record this event is about, so the row is navigable from the // ledger to it (and back) rather than being a bare verb: the session // for a session event, the account for an account event. object_name: targetObjectFor(event.action), - record_id: accountEvent ? event.userId : (event.sessionId ?? null), + record_id: accountEvent ? (subject ?? null) : (event.sessionId ?? null), // No before/after state: an auth event is not a field diff. Recording // `{}` here would be a claim about a record that never changed. old_value: null, @@ -393,7 +416,7 @@ export function createAuthEventAuditSink(opts: AuthEventAuditSinkOptions): AuthE // is, and recording the impersonated user as the sole principal there // would be a WRONG record rather than a vague one. An account event // authenticated nobody, so it credits no principal (module note). - row.actor = event.actor ?? (accountEvent ? null : event.userId); + row.actor = event.actor ?? (accountEvent ? null : subject); } try { diff --git a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts index d50159e7295..c08b724e927 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts @@ -54,7 +54,8 @@ import { recordUnlinkTombstone, } from './implicit-account-linking.js'; import { withSystemReadContext } from './objectql-adapter.js'; -import { emitAuthSessionAuditEvent, loginEventFor, logoutEventFor } from './auth-session-audit.js'; +import { emitAuthSessionAuditEvent, loginEventFor, logoutEventFor, signInClientFingerprint } from './auth-session-audit.js'; +import { ipAllowListRefusalEventFor, ipRefusalAuditBoundFor } from './ip-allow-list-refusal-audit.js'; import { sessionPolicyHoldFor, withSessionPolicyHold } from './session-policy-hold.js'; import { holdPrincipalSessionExpiry } from './principal-session-mint.js'; import { canonicalClientAddress } from './client-address-canonical.js'; @@ -314,11 +315,32 @@ export function composeDatabaseHooks( // established address is in the request state, exactly the address the // deployment's list judged at that door. A programmatic `auth.api.*` call // carries no request and is not judged, as the door never judged it. - const refuseUnadmittedScoping = async (userId: unknown, organizationId: unknown, ctx: any) => { + // + // [#30924] A refused CREATION is a refused sign-in, and leaves its + // `login_failed` row (`ip-allow-list-refusal-audit.ts`), counted by the same + // per-address bound as the deployment gate's rows. A refused SWITCH is not a + // sign-in and writes none: only the creation hands `creating` in. + const refuseUnadmittedScoping = async (userId: unknown, organizationId: unknown, ctx: any, creating?: any) => { if (!ctx?.request || typeof userId !== 'string' || !userId) return; if (typeof organizationId !== 'string' || !organizationId) return; - const verdict = await this.judgeSessionScoping(userId, organizationId, await readRequestClientAddress()); + const address = await readRequestClientAddress(); + const verdict = await this.judgeSessionScoping(userId, organizationId, address); if (verdict === 'admitted') return; + const sink = creating ? this.config.getAuditSink?.() : undefined; + if (sink) { + const fingerprint = signInClientFingerprint(ctx, address); + const attempts = ipRefusalAuditBoundFor(sink).admit(fingerprint.ipAddress, (line) => this.config.logger?.warn?.(line)); + if (attempts !== undefined) { + await emitAuthSessionAuditEvent(sink, ipAllowListRefusalEventFor({ + path: typeof ctx?.path === 'string' ? ctx.path : '', + attempts, + userId, + organizationId, + impersonatedBy: typeof creating?.impersonatedBy === 'string' ? creating.impersonatedBy : undefined, + fingerprint, + })); + } + } const { APIError } = await import('better-auth/api'); throw new APIError('FORBIDDEN', { code: SESSION_SCOPING_REFUSAL.code, message: SESSION_SCOPING_REFUSAL.message }); }; @@ -329,7 +351,7 @@ export function composeDatabaseHooks( const final = result && typeof result === 'object' && 'data' in result ? { ...captured, ...(result as any).data } : captured; - await refuseUnadmittedScoping(final?.userId, final?.activeOrganizationId, ctx); + await refuseUnadmittedScoping(final?.userId, final?.activeOrganizationId, ctx, final); if (result && typeof result === 'object' && 'data' in result) return { data: final }; return captured === session ? result : { data: captured }; }; diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index bf980c9b29d..836340518e4 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -6153,6 +6153,22 @@ export class AuthManager { return resolveSignInAccountId.call(host, email); } + /** + * [#30924] The id of the account a sign-in refused by the ADR-0069 D5 IP + * allow-list names, for its `login_failed` row only + * (`ip-allow-list-refusal-audit.ts`), or `undefined` — the password + * sign-in's own account question ({@link findSignInAccount}). The gate + * refuses before better-auth resolves any account, so this is the only way + * that row can name one. It decides nothing: the refusal is already + * answered. Throws what the engine throws; the caller writes the row with no + * subject then. + */ + public async resolveRefusedSignInAccountId(email: string): Promise { + const engine = this.getDataEngine(); + if (!engine) return undefined; + return (await this.findSignInAccount(engine, email, []))?.id; + } + /** * ADR-0069 D2 — the ONE answer to "which account does this password sign-in * name", read by the lock gate ({@link assertAccountNotLocked}), the counter diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 04b0eadf668..c40d559313f 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -53,7 +53,8 @@ import { ensureDefaultOrganizationExists } from './default-organization-invarian import { recoverInternalFieldsForSystemRead } from './internal-field-readback.js'; import { runAttributedToUser } from './auth-actor-attribution.js'; import { withSystemContext } from './objectql-adapter.js'; -import type { AuthEventAuditSurface } from './auth-session-audit.js'; +import { signInClientFingerprint, type AuthEventAuditSurface } from './auth-session-audit.js'; +import { ipRefusalAuditBoundFor, isSignInEndpoint, recordDeploymentListRefusal } from './ip-allow-list-refusal-audit.js'; import { createTenancyService, type TenancyService } from './tenancy-service.js'; import { isMembershipPolicy, @@ -3413,6 +3414,42 @@ export class AuthPlugin implements Plugin { ); } + /** + * [#30924] ADR-0069 D5 — the `login_failed` row of a sign-in the + * deployment's allow-list refused (`ip-allow-list-refusal-audit.ts`): a + * `/sign-in/*` endpoint only, counted by the per-address bound, and written + * detached from the refusal, so the answer, and the time it takes, do not + * depend on whether the identifier names an account. No `audit` service ⇒ + * nothing is counted or read. + */ + private auditAllowListRefusal( + ctx: PluginContext, + mgr: AuthManager, + c: any, + endpoint: string, + ip: string | undefined, + ): void { + if (!isSignInEndpoint(endpoint)) return; + let sink: AuthEventAuditSurface | undefined; + try { + sink = ctx.getService('audit'); + } catch { + return; + } + if (!sink || typeof sink.recordAuthEvent !== 'function') return; + const attempts = ipRefusalAuditBoundFor(sink).admit(ip, (line) => ctx.logger.warn(line)); + if (attempts === undefined) return; + const request: Request = c.req.raw; + void recordDeploymentListRefusal(sink, { + request, + endpoint, + attempts, + fingerprint: signInClientFingerprint({ headers: request.headers }, ip), + resolveAccount: (email) => mgr.resolveRefusedSignInAccountId(email), + debug: (line, meta) => ctx.logger.debug(line, meta), + }); + } + /** * Register authentication routes with HTTP server * @@ -3499,6 +3536,7 @@ export class AuthPlugin implements Plugin { const ip = mgr.resolveClientAddress({ headers, ...transportOf(c) }); if (!mgr.isClientIpAllowed(ip)) { this.explainAllowListRefusal(ctx, mgr, ip, headers); + this.auditAllowListRefusal(ctx, mgr, c, path.startsWith(basePath) ? path.slice(basePath.length) : path, ip); return c.json( { success: false, error: { code: 'IP_NOT_ALLOWED', message: 'Sign-in is not allowed from your network.' } }, 403, diff --git a/packages/plugins/plugin-auth/src/auth-session-audit.ts b/packages/plugins/plugin-auth/src/auth-session-audit.ts index 04b4f2241a0..c3aafebf91d 100644 --- a/packages/plugins/plugin-auth/src/auth-session-audit.ts +++ b/packages/plugins/plugin-auth/src/auth-session-audit.ts @@ -103,6 +103,18 @@ * (`AuthManager.resolveUserAuthGates`), so the row records a posture the * session is really held by, and fails open exactly where the gate does: no * posture read, no hold recorded. + * + * ## A sign-in the IP allow-list refuses (#30924) + * + * The ADR-0069 D5 allow-list refuses a sign-in at two doors — the deployment's + * list, before any account is resolved, and an organization's own list, when + * the session is created — and each refusal is a `login_failed` row with + * `context.reason: 'IP_NOT_ALLOWED'` and `context.rule: 'ip_allow_list'`, + * bounded per client address (`ip-allow-list-refusal-audit.ts`). It is the one + * account event that may name no subject: refused before better-auth runs, the + * identifier the request carried may name no account, and the address and the + * rule are still the record an enforcement report reads. The identifier is + * still never recorded, and the password never read. */ import { getIP } from '@better-auth/core/utils/ip'; @@ -125,7 +137,12 @@ import { canonicalClientAddress } from './client-address-canonical.js'; export interface AuthEventAuditSurface { recordAuthEvent(event: { action: 'login' | 'logout' | 'login_failed' | 'account_locked'; - userId: string; + /** + * The event's subject. Every event names one, except a `login_failed` for + * a sign-in refused before any account could be resolved (the IP + * allow-list, #30924), which may name none. + */ + userId?: string; sessionId?: string; organizationId?: string; ipAddress?: string; @@ -279,9 +296,20 @@ export function refusalCodeOf(returned: unknown): string | undefined { return code && REFUSAL_CODE.test(code) ? code : undefined; } +/** + * [#30924] The refusals whose refusing door writes the sign-in's + * `login_failed` row itself: an organization's IP list refuses the session at + * its creation (`IP_NOT_ALLOWED`, `auth-manager-database-hooks.ts`) and records + * the account, the organization, the rule and the per-address count there, + * which the password sign-in's outcome cannot see. The outcome writes no + * second row for one. + */ +const REFUSALS_RECORDED_AT_THEIR_DOOR: ReadonlySet = new Set(['IP_NOT_ALLOWED']); + /** * The `login_failed` event for a refused password sign-in, or `null` when no - * account was resolved (no subject ⇒ no row; see the module note). + * account was resolved (no subject ⇒ no row; see the module note) or the + * refusing door wrote the row itself ({@link REFUSALS_RECORDED_AT_THEIR_DOOR}). */ export function signInFailureEventFor( userId: string | null | undefined, @@ -289,6 +317,7 @@ export function signInFailureEventFor( ): AuthSessionAuditEventInput | null { const subject = str(userId); if (!subject) return null; + if (outcome.reason && REFUSALS_RECORDED_AT_THEIR_DOOR.has(outcome.reason)) return null; const context: Record = { endpoint: outcome.path }; if (outcome.reason) context.reason = outcome.reason; return { diff --git a/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit-bound.test.ts b/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit-bound.test.ts new file mode 100644 index 00000000000..b2b3a5b6029 --- /dev/null +++ b/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit-bound.test.ts @@ -0,0 +1,83 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// ADR-0069 D5 — the bound on IP allow-list refusal rows and the row itself +// (`ip-allow-list-refusal-audit.ts`), on an injected clock. The two refusing +// doors that use them are driven for real in +// `ip-allow-list-refusal-audit.test.ts`. + +import { describe, it, expect, vi } from 'vitest'; +import { + IP_ALLOW_LIST_RULE, + IP_REFUSAL_AUDIT_MARKS, + IP_REFUSAL_AUDIT_ROW_CAP, + IP_REFUSAL_AUDIT_WINDOW_MS, + IpRefusalAuditBound, + ipAllowListRefusalEventFor, +} from './ip-allow-list-refusal-audit'; + +const OUTSIDE = '198.51.100.9'; + +// ─────────────────────────────────────────────────────────────────────────── +// The bound, on its own clock +// ─────────────────────────────────────────────────────────────────────────── + +describe('[#30924] the IP refusal row bound', () => { + it('declares the ruled rule: a 10-minute window, rows at the 1st / 10th / 100th refusal, 1000 rows per window', () => { + expect(IP_REFUSAL_AUDIT_WINDOW_MS).toBe(10 * 60_000); + expect([...IP_REFUSAL_AUDIT_MARKS]).toEqual([1, 10, 100]); + expect(IP_REFUSAL_AUDIT_ROW_CAP).toBe(1000); + expect(IP_ALLOW_LIST_RULE).toBe('ip_allow_list'); + }); + + it('per address, the count restarts when its window has passed', () => { + let now = 0; + const bound = new IpRefusalAuditBound({ now: () => now }); + const admitted: Array = []; + for (let i = 0; i < 10; i += 1) admitted.push(bound.admit(OUTSIDE)); + expect(admitted).toEqual([1, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 10]); + now += IP_REFUSAL_AUDIT_WINDOW_MS - 1; + expect(bound.admit(OUTSIDE)).toBeUndefined(); + now += 1; + expect(bound.admit(OUTSIDE)).toBe(1); + }); + + it('an address the server could not establish is counted as one address', () => { + const bound = new IpRefusalAuditBound({ now: () => 0 }); + expect(bound.admit(undefined)).toBe(1); + expect(bound.admit(undefined)).toBeUndefined(); + }); + + it('the global cap holds across addresses, with one operator line per window once dropping', () => { + let now = 0; + const warn = vi.fn(); + const bound = new IpRefusalAuditBound({ now: () => now, rowCap: 3 }); + const answers = ['10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4', '10.0.0.5'].map((a) => bound.admit(a, warn)); + expect(answers).toEqual([1, 1, 1, undefined, undefined]); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toContain('sys_audit_log'); + + // The next window writes again, and may warn again. + now += IP_REFUSAL_AUDIT_WINDOW_MS; + expect(bound.admit('10.0.0.6', warn)).toBe(1); + expect(['10.0.0.7', '10.0.0.8', '10.0.0.9'].map((a) => bound.admit(a, warn))).toEqual([1, 1, undefined]); + expect(warn).toHaveBeenCalledTimes(2); + }); + + it('the addresses it tracks are bounded too', () => { + const bound = new IpRefusalAuditBound({ now: () => 0, rowCap: 1_000_000, trackedAddressCap: 4 }); + for (let i = 0; i < 50; i += 1) bound.admit(`10.0.1.${i}`); + expect(bound.trackedAddresses).toBeLessThanOrEqual(4); + }); +}); + +describe('[#30924] the IP refusal event', () => { + it('names the rule and the machine code, and only the fields it is given', () => { + expect( + ipAllowListRefusalEventFor({ path: '/sign-in/email', attempts: 10, fingerprint: { ipAddress: OUTSIDE } }), + ).toEqual({ + action: 'login_failed', + ipAddress: OUTSIDE, + context: { endpoint: '/sign-in/email', reason: 'IP_NOT_ALLOWED', rule: 'ip_allow_list', attempts: 10 }, + }); + }); +}); diff --git a/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit.test.ts b/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit.test.ts new file mode 100644 index 00000000000..bd46686cf63 --- /dev/null +++ b/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit.test.ts @@ -0,0 +1,368 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// ADR-0069 D5 — a sign-in the IP allow-list refuses leaves one `login_failed` +// row in the compliance ledger (`ip-allow-list-refusal-audit.ts`), bounded so a +// scanner hammering the gate cannot flood the table. +// +// Two doors refuse a sign-in by address, and both are driven for real here: +// +// - the DEPLOYMENT list, judged by the auth-route middleware AuthPlugin mounts +// in front of better-auth (`registerAuthRoutes`), before any account is +// resolved. The fixture mounts it on a real Hono app in front of a real +// AuthManager, as `client-ip-allow-list-trust-rule.test.ts` does; +// - an ORGANIZATION's own list, judged when better-auth creates the session +// (`auth-manager-database-hooks.ts`, `SESSION_SCOPING_REFUSAL`), driven +// through `AuthManager.handleRequest` with the transport peer. +// +// ADR-0112 is `code` AND `status`; every refusal assertion carries both. + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { Hono } from 'hono'; +import type { PluginContext } from '@objectstack/core'; +import { AuthManager } from './auth-manager'; +import { AuthPlugin } from './auth-plugin'; +import { createMemoryEngine } from './impersonation-bearer-rotation.test'; +import { inviteForAudienceGate } from './audience-gate-test-support'; +import type { AuthSessionAuditEventInput } from './auth-session-audit'; + +const SECRET = 'test-secret-at-least-32-chars-long!!'; +const PASSWORD = 'S3cure!Passw0rd-30924'; +const ORIGIN = 'http://localhost:3000'; +const BASE = '/api/v1/auth'; +const EMAIL = 'member.30924@example.com'; + +/** Documentation ranges (RFC 5737): one allowed, two not. */ +const RANGE = '203.0.113.0/24'; +const INSIDE = '203.0.113.7'; +const OUTSIDE = '198.51.100.9'; +const OUTSIDE_2 = '198.51.100.10'; + +/** A recording audit sink, in the shape plugin-audit registers under `audit`. */ +function recordingSink() { + const events: AuthSessionAuditEventInput[] = []; + return { + events, + recordAuthEvent: vi.fn(async (event: AuthSessionAuditEventInput) => { + events.push(event); + }), + }; +} + +/** Let detached work (the gate's row is written off the response path) run. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 25)); + +/** Status + the error code the body carries (ADR-0112 nests it under `error`). */ +async function verdict(res: Response): Promise<{ status: number; code?: string }> { + const text = await res.text(); + let code: string | undefined; + try { + const parsed = JSON.parse(text); + code = parsed?.error?.code ?? parsed?.code; + } catch { + /* non-JSON body → no code */ + } + return { status: res.status, code }; +} + +const REFUSED = { status: 403, code: 'IP_NOT_ALLOWED' }; + +/** One deployment with an allow-list, served through the REAL mount chain. */ +async function deployment(options: { sink?: ReturnType } = {}) { + const engine = createMemoryEngine(); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: engine, + allowedIpRanges: [RANGE], + } as any); + const sink = options.sink; + const ctx = { + registerService: vi.fn(), + getService: vi.fn((name: string) => { + if (name === 'manifest') return { register: vi.fn() }; + if (name === 'audit') return sink; + return undefined; + }), + getServices: vi.fn(() => new Map()), + hook: vi.fn(), + trigger: vi.fn(), + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(), + } as unknown as PluginContext & { logger: { warn: ReturnType } }; + const plugin = new AuthPlugin({ secret: SECRET }); + await plugin.init(ctx); + (plugin as any).authManager = manager; + const app = new Hono(); + (plugin as any).registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx); + + const send = (path: string, init: RequestInit, peer: string) => + app.request(`${ORIGIN}${BASE}${path}`, init, { incoming: { socket: { remoteAddress: peer } } }); + + /** Create the fixture user directly (no mount), so only the sign-in crosses the gate. */ + const signUp = async () => { + await inviteForAudienceGate(manager, EMAIL); + const res = await manager.handleRequest( + new Request(`${ORIGIN}${BASE}/sign-up/email`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN }, + body: JSON.stringify({ email: EMAIL, password: PASSWORD, name: 'Allow-list Member' }), + }), + ); + expect(res.status, `sign-up: ${await res.clone().text()}`).toBe(200); + const user = ((engine.tables.get('sys_user') ?? []) as any[]).find((r) => r.email === EMAIL); + return String(user.id); + }; + + const signIn = (peer: string, email = EMAIL, path = '/sign-in/email') => + send( + path, + { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN, 'user-agent': 'probe/30924' }, + body: JSON.stringify({ email, password: PASSWORD }), + }, + peer, + ); + + return { ctx, manager, engine, signUp, signIn, send }; +} + +beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('[#30924] the deployment allow-list writes one login_failed row per refused sign-in', () => { + it('an out-of-range sign-in of an existing account: one row naming the account, the address, the rule', async () => { + const sink = recordingSink(); + const d = await deployment({ sink }); + const userId = await d.signUp(); + sink.events.length = 0; + + expect(await verdict(await d.signIn(OUTSIDE))).toEqual(REFUSED); + await vi.waitFor(() => expect(sink.events).toHaveLength(1)); + await settle(); + + expect(sink.events).toEqual([ + { + action: 'login_failed', + userId, + ipAddress: OUTSIDE, + userAgent: 'probe/30924', + context: { endpoint: '/sign-in/email', reason: 'IP_NOT_ALLOWED', rule: 'ip_allow_list', attempts: 1 }, + }, + ]); + // ⛔ Nothing the caller typed reaches the row: no password, no identifier. + const written = JSON.stringify(sink.events); + expect(written).not.toContain(PASSWORD); + expect(written).not.toContain(EMAIL); + }); + + it('an identifier that names no account still writes the row, with no subject', async () => { + const sink = recordingSink(); + const d = await deployment({ sink }); + + expect(await verdict(await d.signIn(OUTSIDE, 'nobody.30924@example.com'))).toEqual(REFUSED); + await vi.waitFor(() => expect(sink.events).toHaveLength(1)); + + const [event] = sink.events; + expect(event.action).toBe('login_failed'); + expect(event.userId).toBeUndefined(); + expect(event.ipAddress).toBe(OUTSIDE); + expect(event.context).toEqual({ + endpoint: '/sign-in/email', + reason: 'IP_NOT_ALLOWED', + rule: 'ip_allow_list', + attempts: 1, + }); + expect(JSON.stringify(event)).not.toContain('nobody.30924'); + }); + + it('every /sign-in/* endpoint is recorded; a refused session read or sign-out is not', async () => { + const sink = recordingSink(); + const d = await deployment({ sink }); + + expect(await verdict(await d.send('/get-session', { method: 'GET' }, OUTSIDE))).toEqual(REFUSED); + expect(await verdict(await d.send('/sign-out', { method: 'POST' }, OUTSIDE))).toEqual(REFUSED); + await settle(); + expect(sink.events).toEqual([]); + + expect(await verdict(await d.signIn(OUTSIDE_2, EMAIL, '/sign-in/magic-link'))).toEqual(REFUSED); + await vi.waitFor(() => expect(sink.events).toHaveLength(1)); + expect(sink.events[0].context).toMatchObject({ endpoint: '/sign-in/magic-link', rule: 'ip_allow_list' }); + }); + + it('an admitted sign-in writes no refusal row', async () => { + const sink = recordingSink(); + const d = await deployment({ sink }); + await d.signUp(); + sink.events.length = 0; + + const res = await d.signIn(INSIDE); + expect(res.status, await res.clone().text()).toBe(200); + await settle(); + expect(sink.events.filter((e) => e.action === 'login_failed')).toEqual([]); + }); + + it('a flood from one address is bounded: rows at the 1st, 10th and 100th refusal only', async () => { + const sink = recordingSink(); + const d = await deployment({ sink }); + + for (let i = 0; i < 120; i += 1) { + expect((await d.signIn(OUTSIDE, 'nobody.30924@example.com')).status).toBe(403); + } + await vi.waitFor(() => expect(sink.events).toHaveLength(3)); + await settle(); + expect(sink.events.map((e) => e.context?.attempts)).toEqual([1, 10, 100]); + + // Another address has its own count. + expect((await d.signIn(OUTSIDE_2, 'nobody.30924@example.com')).status).toBe(403); + await vi.waitFor(() => expect(sink.events).toHaveLength(4)); + expect(sink.events[3]).toMatchObject({ ipAddress: OUTSIDE_2, context: { attempts: 1 } }); + }); + + it('the row does not change the answer: same status, code and body, and the response never waits on the account lookup', async () => { + const without = await deployment(); + const plain = await without.signIn(OUTSIDE); + const plainBody = await plain.text(); + + const sink = recordingSink(); + const d = await deployment({ sink }); + await d.signUp(); + // The account lookup is slow: the answer must arrive before it settles. + let settled = false; + const lookup = vi.spyOn(d.manager, 'resolveRefusedSignInAccountId').mockImplementation( + () => new Promise((resolve) => setTimeout(() => { settled = true; resolve(undefined); }, 150)), + ); + const audited = await d.signIn(OUTSIDE); + expect(settled, 'the refusal waited on the account lookup').toBe(false); + expect(audited.status).toBe(plain.status); + expect(await audited.text()).toBe(plainBody); + expect(JSON.parse(plainBody)).toEqual({ + success: false, + error: { code: 'IP_NOT_ALLOWED', message: 'Sign-in is not allowed from your network.' }, + }); + await vi.waitFor(() => expect(lookup).toHaveBeenCalledTimes(1)); + expect(lookup).toHaveBeenCalledWith(EMAIL); + }); + + it('no audit plugin: the refusal is answered as before and nothing is read', async () => { + const d = await deployment(); + const lookup = vi.spyOn(d.manager, 'resolveRefusedSignInAccountId'); + expect(await verdict(await d.signIn(OUTSIDE))).toEqual(REFUSED); + await settle(); + expect(lookup).not.toHaveBeenCalled(); + }); +}); + +// ─────────────────────────────────────────────────────────────────────────── +// An organization's own list, judged when the session is created +// ─────────────────────────────────────────────────────────────────────────── + +const ORG_A = 'org_alpha'; +const ORG_B = 'org_beta'; +const IN_A = '10.1.0.7'; +const IN_B = '10.2.0.7'; + +const post = (manager: AuthManager, path: string, body: unknown, remoteAddress: string, cookie?: string) => + manager.handleRequest( + new Request(`${ORIGIN}${BASE}${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'user-agent': 'probe/30924', ...(cookie ? { cookie } : {}) }, + body: JSON.stringify(body), + }), + { remoteAddress }, + ); + +const cookieFrom = (response: Response): string => + (response.headers.getSetCookie?.() ?? [response.headers.get('set-cookie') ?? '']) + .map((c) => c.split(';')[0]) + .filter(Boolean) + .join('; '); + +/** Alpha admits only 10.1.0.0/16, Beta only 10.2.0.0/16; Alice is a member of both, Alpha first. */ +async function organizations() { + const sink = recordingSink(); + const engine = createMemoryEngine(); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: engine, + audience: { posture: 'open', selfRegistrationPermissionSet: 'member_default' }, + emailAndPassword: { enabled: true, requireEmailVerification: false }, + getAuditSink: () => sink, + } as any); + vi.spyOn(manager as any, 'selfRegistrationSetResolvable').mockResolvedValue(true); + const policies: Record> = { + [ORG_A]: { allowed_ip_ranges: '10.1.0.0/16' }, + [ORG_B]: { allowed_ip_ranges: '10.2.0.0/16' }, + }; + manager.setOrganizationAccessPolicySource({ + read: async (id) => policies[id] ?? {}, + anyOrganizationRequiresMfa: async () => false, + }); + const email = 'alice@alpha.test'; + const res = await post(manager, '/sign-up/email', { email, password: PASSWORD, name: email }, '127.0.0.1'); + expect(res.status, await res.clone().text()).toBe(200); + const user = (engine.tables.get('sys_user') ?? []).find((u: any) => u.email === email); + await engine.insert('sys_organization', { id: ORG_A, name: 'Alpha', slug: 'alpha' }); + await engine.insert('sys_organization', { id: ORG_B, name: 'Beta', slug: 'beta' }); + engine.tables.set('sys_member', (engine.tables.get('sys_member') ?? []).filter((m: any) => m.user_id !== user.id)); + await engine.insert('sys_member', { user_id: user.id, organization_id: ORG_A, role: 'member', created_at: new Date(Date.now() - 60_000) }); + await engine.insert('sys_member', { user_id: user.id, organization_id: ORG_B, role: 'member', created_at: new Date() }); + sink.events.length = 0; + const signIn = (remoteAddress: string) => post(manager, '/sign-in/email', { email, password: PASSWORD }, remoteAddress); + return { sink, engine, manager, userId: String(user.id), signIn }; +} + +describe('[#30924] an organization\'s own list writes one login_failed row per refused sign-in', () => { + it('a sign-in scoped to an organization from outside its list: one row naming the account, the organization, the address, the rule', async () => { + // One row, not two: the password sign-in's own refusal row + // (`signInFailureEventFor`) yields to the row the refusing door wrote. + const { sink, userId, signIn } = await organizations(); + + const res = await signIn(IN_B); + expect(res.status).toBe(403); + expect(((await res.json()) as any).code).toBe('IP_NOT_ALLOWED'); + + expect(sink.events).toEqual([ + { + action: 'login_failed', + userId, + organizationId: ORG_A, + ipAddress: IN_B, + userAgent: 'probe/30924', + context: { endpoint: '/sign-in/email', reason: 'IP_NOT_ALLOWED', rule: 'ip_allow_list', attempts: 1 }, + }, + ]); + expect(JSON.stringify(sink.events)).not.toContain(PASSWORD); + }); + + it('control: an admitted sign-in writes its login row and no refusal row', async () => { + const { sink, signIn } = await organizations(); + expect((await signIn(IN_A)).status).toBe(200); + expect(sink.events.map((e) => e.action)).toEqual(['login']); + }); + + it('a refused switch of the active organization is not a sign-in: no row', async () => { + const { sink, manager, signIn } = await organizations(); + const signedIn = await signIn(IN_A); + expect(signedIn.status).toBe(200); + const cookie = cookieFrom(signedIn); + sink.events.length = 0; + + const res = await post(manager, '/organization/set-active', { organizationId: ORG_B }, IN_A, cookie); + expect(res.status).toBe(403); + expect(((await res.json()) as any).code).toBe('IP_NOT_ALLOWED'); + expect(sink.events).toEqual([]); + }); + + it('repeated refusals from one address share the deployment gate\'s bound', async () => { + const { sink, signIn } = await organizations(); + for (let i = 0; i < 12; i += 1) expect((await signIn(IN_B)).status).toBe(403); + expect(sink.events.map((e) => e.context?.attempts)).toEqual([1, 10]); + }); +}); diff --git a/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit.ts b/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit.ts new file mode 100644 index 00000000000..3b857bc93c4 --- /dev/null +++ b/packages/plugins/plugin-auth/src/ip-allow-list-refusal-audit.ts @@ -0,0 +1,315 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#30924] A sign-in the ADR-0069 D5 IP allow-list refuses leaves one + * `login_failed` row in the compliance ledger, bounded per client address. + * + * ## Which refusals, which row + * + * Two doors refuse a sign-in by its client address, and both record it here: + * + * - **The deployment's list**, judged by the auth-route middleware + * `AuthPlugin.registerAuthRoutes` mounts in front of better-auth. It refuses + * before better-auth resolves an account, so the row names the account only + * where the request's `email` resolves to one + * (`AuthManager.resolveRefusedSignInAccountId`, the password sign-in's own + * account question), and is written with no subject otherwise. Only a + * `/sign-in/*` endpoint is recorded: the same gate refuses a session read or + * a sign-out from the same address, and neither is a sign-in. + * - **An organization's own list**, judged when better-auth creates the + * session (`SESSION_SCOPING_REFUSAL`, `auth-manager-database-hooks.ts`). + * The credential check has passed there, so the row names the account and + * the organization. A refused switch of the active organization is not a + * sign-in and writes no row. + * + * The row follows the incumbent shape of a refused sign-in + * (`signInFailureEventFor`, `auth-session-audit.ts`): `action: 'login_failed'` + * with `context.endpoint` and `context.reason`, the refusal's machine code + * (`IP_NOT_ALLOWED`). It adds `context.rule` — the policy that refused it, + * `ip_allow_list`, as an MFA-held `login` row names `mfa_required` — and + * `context.attempts`, below. The client address and user agent are read by the + * rule every `login` row's are (`signInClientFingerprint`). + * + * ⛔ No row carries anything the caller typed: the submitted identifier is + * used only to find the account and is never recorded, and the password is + * never read. + * + * ## The bound + * + * A scanner hammering the gate must not be able to flood the table, so the + * rows are bounded ({@link IpRefusalAuditBound}): + * + * - per client address, a 10-minute window from that address's first + * refusal: a row at its 1st, 10th and 100th refusal, each carrying + * `context.attempts` (1, 10, 100) — so a steady flood from one address is + * three rows per window, and the third says it reached a hundred; + * - across all addresses, at most 1000 rows per 10-minute window, and once + * that cap drops a row, one operator `warn` line for the window; + * - the addresses it tracks are bounded too, so rotating addresses cannot + * grow its memory without limit. + * + * The bound is held in process memory, one per audit sink (in a running + * process that is the one `audit` service). It holds per process: N replicas + * of the server write up to N times as many rows. No shared store is used. + */ + +import { + emitAuthSessionAuditEvent, + type AuthEventAuditSurface, + type AuthSessionAuditEventInput, + type SignInClientFingerprint, +} from './auth-session-audit.js'; +import { canonicalClientAddress } from './client-address-canonical.js'; + +/** The policy a refused sign-in names in `context.rule`. */ +export const IP_ALLOW_LIST_RULE = 'ip_allow_list'; + +/** The machine code both doors answer, recorded as `context.reason`. */ +export const IP_NOT_ALLOWED_REASON = 'IP_NOT_ALLOWED'; + +/** The window a client address's refusals are counted in. */ +export const IP_REFUSAL_AUDIT_WINDOW_MS = 10 * 60_000; + +/** The refusals of one address, within its window, that write a row. */ +export const IP_REFUSAL_AUDIT_MARKS: readonly number[] = Object.freeze([1, 10, 100]); + +/** The rows written per window across every address. */ +export const IP_REFUSAL_AUDIT_ROW_CAP = 1000; + +/** The client addresses tracked at once; past it the stalest is forgotten. */ +const TRACKED_ADDRESS_CAP = 10_000; + +/** The key of a refusal whose client address could not be established. */ +const UNDETERMINED = ''; + +export interface IpRefusalAuditBoundOptions { + windowMs?: number; + marks?: readonly number[]; + rowCap?: number; + trackedAddressCap?: number; + now?: () => number; +} + +/** The module note's bound, on one clock. */ +export class IpRefusalAuditBound { + private readonly windowMs: number; + private readonly marks: ReadonlySet; + private readonly rowCap: number; + private readonly trackedAddressCap: number; + private readonly now: () => number; + private readonly perAddress = new Map(); + private windowStart: number | undefined; + private rowsInWindow = 0; + private warnedInWindow = false; + + constructor(options: IpRefusalAuditBoundOptions = {}) { + this.windowMs = options.windowMs ?? IP_REFUSAL_AUDIT_WINDOW_MS; + this.marks = new Set(options.marks ?? IP_REFUSAL_AUDIT_MARKS); + this.rowCap = options.rowCap ?? IP_REFUSAL_AUDIT_ROW_CAP; + this.trackedAddressCap = options.trackedAddressCap ?? TRACKED_ADDRESS_CAP; + this.now = options.now ?? Date.now; + } + + /** How many client addresses are tracked now. */ + get trackedAddresses(): number { + return this.perAddress.size; + } + + /** + * Count one refusal from `address`. Answers the `attempts` number its row + * carries when this refusal writes one, or `undefined` when it does not: + * not one of the marks, or the window's cap is spent (then `warn` is called + * once for the window). + */ + admit(address: string | undefined, warn?: (line: string) => void): number | undefined { + const now = this.now(); + const key = address ? canonicalClientAddress(address) : UNDETERMINED; + let entry = this.perAddress.get(key); + if (!entry || now - entry.start >= this.windowMs) { + if (entry) this.perAddress.delete(key); + else this.makeRoom(now); + entry = { start: now, count: 0 }; + this.perAddress.set(key, entry); + } + entry.count += 1; + if (!this.marks.has(entry.count)) return undefined; + + if (this.windowStart === undefined || now - this.windowStart >= this.windowMs) { + this.windowStart = now; + this.rowsInWindow = 0; + this.warnedInWindow = false; + } + if (this.rowsInWindow >= this.rowCap) { + if (!this.warnedInWindow) { + this.warnedInWindow = true; + warn?.( + `[auth] IP allow-list refusals (ADR-0069 D5): ${this.rowCap} login_failed rows were written to ` + + `sys_audit_log in this ${Math.round(this.windowMs / 60_000)}-minute window, the most one window ` + + 'takes, so further refused sign-ins are answered exactly as before but no longer recorded until ' + + `${new Date(this.windowStart + this.windowMs).toISOString()}. A refusal flood of this size is ` + + 'usually a scanner; the rows already written name the addresses it came from.', + ); + } + return undefined; + } + this.rowsInWindow += 1; + return entry.count; + } + + /** Keep the tracked addresses under their cap: drop the expired, then the stalest. */ + private makeRoom(now: number): void { + if (this.perAddress.size < this.trackedAddressCap) return; + for (const [key, entry] of this.perAddress) { + if (now - entry.start >= this.windowMs) this.perAddress.delete(key); + } + while (this.perAddress.size >= this.trackedAddressCap) { + const stalest = this.perAddress.keys().next(); + if (stalest.done) break; + this.perAddress.delete(stalest.value); + } + } +} + +/** One bound per audit sink, held weakly: per process, and never shared between test doubles. */ +const bounds = new WeakMap(); + +/** The bound the rows written to `sink` are counted by. */ +export function ipRefusalAuditBoundFor(sink: AuthEventAuditSurface): IpRefusalAuditBound { + let bound = bounds.get(sink); + if (!bound) { + bound = new IpRefusalAuditBound(); + bounds.set(sink, bound); + } + return bound; +} + +/** A non-empty string, or undefined. */ +function str(v: unknown): string | undefined { + return typeof v === 'string' && v.length > 0 ? v : undefined; +} + +/** + * The `login_failed` event for a sign-in the IP allow-list refused. `userId` + * and `organizationId` are recorded where the refusing door knows them, and + * the row is written without them otherwise (module note). + */ +export function ipAllowListRefusalEventFor(input: { + path: string; + attempts: number; + userId?: string; + organizationId?: string; + impersonatedBy?: string; + fingerprint?: SignInClientFingerprint; +}): AuthSessionAuditEventInput { + const userId = str(input.userId); + const organizationId = str(input.organizationId); + const impersonatedBy = str(input.impersonatedBy); + return { + action: 'login_failed', + ...(userId ? { userId } : {}), + ...(organizationId ? { organizationId } : {}), + ...(input.fingerprint ?? {}), + context: { + endpoint: input.path, + reason: IP_NOT_ALLOWED_REASON, + rule: IP_ALLOW_LIST_RULE, + attempts: input.attempts, + ...(impersonatedBy ? { impersonated_by: impersonatedBy } : {}), + }, + }; +} + +/** Whether a better-auth endpoint path is a sign-in (module note: only those are recorded). */ +export function isSignInEndpoint(path: string): boolean { + return path.startsWith('/sign-in/'); +} + +/** The most of a refused sign-in's body read to find its `email`. */ +const IDENTIFIER_BODY_LIMIT = 16 * 1024; + +/** The longest `email` looked up (RFC 5321 caps a path at 256 octets). */ +const IDENTIFIER_LIMIT = 320; + +/** + * The `email` a refused sign-in's JSON body carries, read only to find the + * account its row names, or `undefined`: no body, one past + * {@link IDENTIFIER_BODY_LIMIT}, one that does not parse, or no `email` text. + * Never throws. + */ +export async function refusedSignInEmailOf(request: Request): Promise { + const declared = Number(request.headers.get('content-length')); + if (Number.isFinite(declared) && declared > IDENTIFIER_BODY_LIMIT) return undefined; + const stream = request.body; + if (!stream) return undefined; + const chunks: Uint8Array[] = []; + let size = 0; + try { + const reader = stream.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > IDENTIFIER_BODY_LIMIT) { + await reader.cancel().catch(() => {}); + return undefined; + } + chunks.push(value); + } + const bytes = new Uint8Array(size); + let at = 0; + for (const chunk of chunks) { + bytes.set(chunk, at); + at += chunk.byteLength; + } + const email = (JSON.parse(new TextDecoder().decode(bytes)) as { email?: unknown } | null)?.email; + return typeof email === 'string' && email.length > 0 && email.length <= IDENTIFIER_LIMIT ? email : undefined; + } catch { + return undefined; + } +} + +/** + * Write the row of one sign-in the DEPLOYMENT's list refused (module note), + * after the bound admitted it. Called detached from the refusal: the answer + * never waits on the body read or the account lookup, so it is the same + * answer, in the same time, whether the identifier names an account or not. + * Never throws; an account lookup that fails writes the row with no subject. + */ +export async function recordDeploymentListRefusal( + sink: AuthEventAuditSurface, + refusal: { + request: Request; + endpoint: string; + attempts: number; + fingerprint: SignInClientFingerprint; + resolveAccount: (email: string) => Promise; + /** Told when the account lookup failed and the row is written with no subject. */ + debug?: (line: string, meta?: Record) => void; + }, +): Promise { + try { + const email = await refusedSignInEmailOf(refusal.request); + let userId: string | undefined; + if (email) { + try { + userId = await refusal.resolveAccount(email); + } catch (err) { + userId = undefined; + refusal.debug?.('[auth] an IP allow-list refusal row is written with no subject: the account lookup failed', { + err: String((err as { message?: unknown } | null)?.message ?? err), + }); + } + } + await emitAuthSessionAuditEvent( + sink, + ipAllowListRefusalEventFor({ + path: refusal.endpoint, + attempts: refusal.attempts, + userId, + fingerprint: refusal.fingerprint, + }), + ); + } catch { + /* the refusal is already answered; the sink reports its own lost rows */ + } +} diff --git a/packages/qa/dogfood/test/auth-session-audit-trail.dogfood.test.ts b/packages/qa/dogfood/test/auth-session-audit-trail.dogfood.test.ts index e158a50b46f..98138879e42 100644 --- a/packages/qa/dogfood/test/auth-session-audit-trail.dogfood.test.ts +++ b/packages/qa/dogfood/test/auth-session-audit-trail.dogfood.test.ts @@ -319,3 +319,75 @@ describe('#30924: a sign-in that enforced MFA holds records the hold on its own expect(JSON.stringify(mine)).not.toContain(HELD_PASSWORD); }, 120_000); }); + +describe('#30924: a sign-in the IP allow-list refuses writes one login_failed row', () => { + // ADR-0069 D5 on a real boot: the deployment's `auth.allowed_ip_ranges` + // set through the settings service to a range no request here comes from + // (the harness injects requests with no socket, so the server establishes + // no client address, which the gate refuses like one outside the ranges). + // Read back through the engine under a system context: with the list set, + // every auth route refuses the harness too. + const MEMBER = 'refused.30924@example.com'; + const MEMBER_PASS = 'Refused!Pass30924'; + let stack: VerifyStack; + let ql: any; + let memberId: string; + + const signInRaw = (email: string) => + stack.api('/auth/sign-in/email', { + method: 'POST', + headers: { 'content-type': 'application/json', origin: 'http://localhost:3000', 'user-agent': 'dogfood/30924' }, + body: JSON.stringify({ email, password: MEMBER_PASS }), + }); + + beforeAll(async () => { + stack = await bootShowcase({ extraPlugins: [new AuditPlugin()], orgContext: true }); + ql = await stack.kernel.getServiceAsync('objectql'); + await stack.signIn(); + await stack.signUp(MEMBER, MEMBER_PASS, 'Refused 30924'); + const [member] = await findRows(ql, 'sys_user', { email: MEMBER }, 1); + memberId = String(member.id); + const settings = await stack.kernel.getServiceAsync('settings'); + await settings.setMany('auth', { allowed_ip_ranges: '203.0.113.0/24' }); + }, 180_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + it('one row naming the account, the rule and the reason; a flood is bounded; no credential is written', async () => { + // The saved list reaches the gate through the settings apply, which is not + // synchronous with `setMany`: wait for the first refusal, which is the + // 1st counted, then send eleven more. + let first: Response | undefined; + for (let i = 0; i < 40 && first?.status !== 403; i += 1) { + if (i > 0) await new Promise((r) => setTimeout(r, 250)); + first = await signInRaw(MEMBER); + } + expect(first?.status, 'the saved allow-list never refused a sign-in').toBe(403); + expect(((await first!.json()) as any)?.error?.code).toBe('IP_NOT_ALLOWED'); + for (let i = 0; i < 11; i += 1) { + const res = await signInRaw(MEMBER); + expect(res.status).toBe(403); + expect(((await res.json()) as any)?.error?.code).toBe('IP_NOT_ALLOWED'); + } + + const rows = await waitForRows( + () => findRows(ql, 'sys_audit_log', { action: 'login_failed', user_id: memberId }), + (found) => found.length >= 2, + 'the refused sign-ins wrote no login_failed rows', + ); + // Twelve refusals from one (undetermined) address: rows at the 1st and 10th only. + expect(rows).toHaveLength(2); + const metadata = rows.map((r: any) => JSON.parse(String(r.metadata))); + expect(metadata.map((m: any) => m.attempts).sort((a: number, b: number) => a - b)).toEqual([1, 10]); + for (const [i, row] of rows.entries()) { + expect(metadata[i]).toMatchObject({ endpoint: '/sign-in/email', reason: 'IP_NOT_ALLOWED', rule: 'ip_allow_list' }); + expect(row.object_name).toBe('sys_user'); + expect(row.record_id).toBe(memberId); + expect(row.user_agent).toBe('dogfood/30924'); + } + expect(JSON.stringify(rows)).not.toContain(MEMBER_PASS); + expect(JSON.stringify(rows)).not.toContain(MEMBER); + }, 120_000); +});