|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// The vendored auth library's OWN client-address source follows the |
| 4 | +// platform's client-address trust rule (`./client-address.ts`), the rule the |
| 5 | +// ADR-0069 D5 allow-list judges with and the D7 login audit stamps by: |
| 6 | +// |
| 7 | +// - forwarded headers count only when the deployment declares |
| 8 | +// `server.trustProxy` (`AuthManagerOptions.trustProxy`); |
| 9 | +// - otherwise the address is the transport's peer (`IHttpRequest.remoteAddress`); |
| 10 | +// - neither available ⇒ the library is handed NO address. |
| 11 | +// |
| 12 | +// One pin per branch. Each reads, off one composition, the three things the |
| 13 | +// library keys on a client address (`client-address-vendor.ts`): the session |
| 14 | +// row's `ip_address`, the refused-sign-in audit fingerprint, and the key its |
| 15 | +// per-address rate limiter consumes. The fixture is the D5/D7 suite's |
| 16 | +// (`client-ip-allow-list-trust-rule.test.ts`): `AuthPlugin.registerAuthRoutes` |
| 17 | +// mounted on a real Hono app in front of a real `AuthManager` on the installed |
| 18 | +// better-auth, with the transport peer supplied the way `@hono/node-server` |
| 19 | +// supplies it, as the Node request on `c.env.incoming`. |
| 20 | +// |
| 21 | +// Every request also carries the platform-owned header itself, set by the |
| 22 | +// caller: in no branch may a caller's copy reach the library. |
| 23 | +// |
| 24 | +// ADR-0112 is `code` AND `status`; the refused sign-in asserts both, so a |
| 25 | +// refusal from anywhere but the credential check cannot stand in for it. |
| 26 | + |
| 27 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
| 28 | +import { Hono } from 'hono'; |
| 29 | +import { AuthManager } from './auth-manager'; |
| 30 | +import { AuthPlugin } from './auth-plugin'; |
| 31 | +import { VENDOR_CLIENT_ADDRESS_HEADER } from './client-address-vendor'; |
| 32 | +import { createMemoryEngine } from './impersonation-bearer-rotation.test'; |
| 33 | +import { inviteForAudienceGate } from './audience-gate-test-support'; |
| 34 | +import type { PluginContext } from '@objectstack/core'; |
| 35 | + |
| 36 | +const SECRET = 'test-secret-at-least-32-chars-long!!'; |
| 37 | +const PASSWORD = 'S3cure!Passw0rd-24799'; |
| 38 | +const ORIGIN = 'http://localhost:3000'; |
| 39 | +const BASE = '/api/v1/auth'; |
| 40 | +const EMAIL = 'member.24799@example.com'; |
| 41 | + |
| 42 | +/** Documentation ranges (RFC 5737), and one private proxy hop. */ |
| 43 | +const CLIENT = '203.0.113.7'; |
| 44 | +const OTHER = '198.51.100.9'; |
| 45 | +const PROXY_HOP = '10.0.0.2'; |
| 46 | + |
| 47 | +/** The credential check's own refusal (ADR-0112 `code` + `status`). */ |
| 48 | +const CREDENTIAL_REFUSAL = { status: 401, code: 'INVALID_EMAIL_OR_PASSWORD' }; |
| 49 | + |
| 50 | +const mockCtx = () => |
| 51 | + ({ |
| 52 | + registerService: vi.fn(), |
| 53 | + getService: vi.fn((name: string) => (name === 'manifest' ? { register: vi.fn() } : undefined)), |
| 54 | + getServices: vi.fn(() => new Map()), |
| 55 | + hook: vi.fn(), |
| 56 | + trigger: vi.fn(), |
| 57 | + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, |
| 58 | + getKernel: vi.fn(), |
| 59 | + }) as unknown as PluginContext; |
| 60 | + |
| 61 | +async function verdict(res: Response): Promise<{ status: number; code?: string }> { |
| 62 | + const text = await res.text(); |
| 63 | + let code: string | undefined; |
| 64 | + try { |
| 65 | + const parsed = JSON.parse(text); |
| 66 | + code = parsed?.error?.code ?? parsed?.code; |
| 67 | + } catch { |
| 68 | + /* non-JSON body → no code */ |
| 69 | + } |
| 70 | + return { status: res.status, code }; |
| 71 | +} |
| 72 | + |
| 73 | +/** What the library keyed on one client address, per seam. */ |
| 74 | +interface Observed { |
| 75 | + /** `sys_session.ip_address` of the session the successful sign-in minted. */ |
| 76 | + session: unknown; |
| 77 | + /** The `login_failed` audit event's address, for the refused sign-in. */ |
| 78 | + refused: unknown; |
| 79 | + /** The address half of every rate-limit key consumed across both sign-ins. */ |
| 80 | + limiterKeys: string[]; |
| 81 | + /** ADR-0069 D7 `last_login_ip` after the successful sign-in. */ |
| 82 | + lastLoginIp: unknown; |
| 83 | +} |
| 84 | + |
| 85 | +/** One deployment, served through the REAL mount chain. */ |
| 86 | +async function serve(deployment: { trustProxy?: boolean }) { |
| 87 | + const engine = createMemoryEngine(); |
| 88 | + const events: Array<{ action: string; ipAddress?: string }> = []; |
| 89 | + const consumedKeys: string[] = []; |
| 90 | + const manager = new AuthManager({ |
| 91 | + secret: SECRET, |
| 92 | + baseUrl: ORIGIN, |
| 93 | + dataEngine: engine, |
| 94 | + getAuditSink: () => ({ |
| 95 | + recordAuthEvent: async (event: { action: string; ipAddress?: string }) => { |
| 96 | + events.push(event); |
| 97 | + }, |
| 98 | + }), |
| 99 | + // The library's limiter is on by default only in production; switch it on |
| 100 | + // and record every key it consumes, admitting every request. |
| 101 | + rateLimit: { enabled: true }, |
| 102 | + rateLimitStorage: { |
| 103 | + consume: async (key: string) => { |
| 104 | + consumedKeys.push(key); |
| 105 | + return { allowed: true, retryAfter: null }; |
| 106 | + }, |
| 107 | + }, |
| 108 | + ...deployment, |
| 109 | + } as any); |
| 110 | + |
| 111 | + const ctx = mockCtx(); |
| 112 | + const plugin = new AuthPlugin({ secret: SECRET }); |
| 113 | + await plugin.init(ctx); |
| 114 | + (plugin as any).authManager = manager; |
| 115 | + const app = new Hono(); |
| 116 | + (plugin as any).registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx); |
| 117 | + |
| 118 | + const signIn = (peer: string | undefined, headers: Record<string, string>, password: string) => |
| 119 | + app.request( |
| 120 | + `${ORIGIN}${BASE}/sign-in/email`, |
| 121 | + { |
| 122 | + method: 'POST', |
| 123 | + headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, |
| 124 | + body: JSON.stringify({ email: EMAIL, password }), |
| 125 | + }, |
| 126 | + peer ? { incoming: { socket: { remoteAddress: peer } } } : {}, |
| 127 | + ); |
| 128 | + |
| 129 | + await inviteForAudienceGate(manager, EMAIL); |
| 130 | + const signUp = await manager.handleRequest( |
| 131 | + new Request(`${ORIGIN}${BASE}/sign-up/email`, { |
| 132 | + method: 'POST', |
| 133 | + headers: { 'content-type': 'application/json', origin: ORIGIN }, |
| 134 | + body: JSON.stringify({ email: EMAIL, password: PASSWORD, name: 'Client Address Member' }), |
| 135 | + }), |
| 136 | + ); |
| 137 | + expect(signUp.status, `sign-up: ${await signUp.clone().text()}`).toBe(200); |
| 138 | + |
| 139 | + /** A refused, then a successful, sign-in from `peer` carrying `headers`. */ |
| 140 | + const observe = async (peer: string | undefined, headers: Record<string, string>): Promise<Observed> => { |
| 141 | + const sessionsBefore = (engine.tables.get('sys_session') ?? []).length; |
| 142 | + const eventsBefore = events.length; |
| 143 | + const keysBefore = consumedKeys.length; |
| 144 | + |
| 145 | + const refusedRes = await signIn(peer, headers, `${PASSWORD}-wrong`); |
| 146 | + expect(await verdict(refusedRes)).toEqual(CREDENTIAL_REFUSAL); |
| 147 | + const okRes = await signIn(peer, headers, PASSWORD); |
| 148 | + expect(okRes.status, await okRes.clone().text()).toBe(200); |
| 149 | + |
| 150 | + const minted = ((engine.tables.get('sys_session') ?? []) as any[]).slice(sessionsBefore); |
| 151 | + expect(minted, 'one session minted by the successful sign-in').toHaveLength(1); |
| 152 | + const refused = events.slice(eventsBefore).filter((e) => e.action === 'login_failed'); |
| 153 | + expect(refused, 'one login_failed event for the refused sign-in').toHaveLength(1); |
| 154 | + const limiterKeys = consumedKeys.slice(keysBefore).map((key) => key.split('|')[0]!); |
| 155 | + expect(limiterKeys, 'the library limiter consumed a key for each sign-in').toHaveLength(2); |
| 156 | + const user = ((engine.tables.get('sys_user') ?? []) as any[]).find((r) => r.email === EMAIL); |
| 157 | + |
| 158 | + return { |
| 159 | + session: minted[0]?.ip_address, |
| 160 | + refused: refused[0]?.ipAddress, |
| 161 | + limiterKeys, |
| 162 | + lastLoginIp: user?.last_login_ip, |
| 163 | + }; |
| 164 | + }; |
| 165 | + |
| 166 | + return { observe }; |
| 167 | +} |
| 168 | + |
| 169 | +beforeEach(() => { |
| 170 | + vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 171 | + vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 172 | +}); |
| 173 | +afterEach(() => { |
| 174 | + vi.restoreAllMocks(); |
| 175 | +}); |
| 176 | + |
| 177 | +describe('the vendored auth library keys on the client address the server established, and no other', () => { |
| 178 | + it('behind a declared trusted proxy, it records and keys on the forwarded client address', async () => { |
| 179 | + const d = await serve({ trustProxy: true }); |
| 180 | + |
| 181 | + const seen = await d.observe(PROXY_HOP, { |
| 182 | + 'x-forwarded-for': `${CLIENT}, ${PROXY_HOP}`, |
| 183 | + [VENDOR_CLIENT_ADDRESS_HEADER]: OTHER, |
| 184 | + }); |
| 185 | + |
| 186 | + expect(seen.session).toBe(CLIENT); |
| 187 | + expect(seen.refused).toBe(CLIENT); |
| 188 | + expect(seen.limiterKeys).toEqual([CLIENT, CLIENT]); |
| 189 | + // The same address the D7 login audit stamped. |
| 190 | + expect(seen.lastLoginIp).toBe(CLIENT); |
| 191 | + }); |
| 192 | + |
| 193 | + it('without a declared trusted proxy, it records and keys on the connection peer, whatever the request headers say', async () => { |
| 194 | + const d = await serve({}); |
| 195 | + |
| 196 | + const seen = await d.observe(CLIENT, { |
| 197 | + 'x-forwarded-for': OTHER, |
| 198 | + 'x-real-ip': OTHER, |
| 199 | + [VENDOR_CLIENT_ADDRESS_HEADER]: OTHER, |
| 200 | + }); |
| 201 | + |
| 202 | + expect(seen.session).toBe(CLIENT); |
| 203 | + expect(seen.refused).toBe(CLIENT); |
| 204 | + expect(seen.limiterKeys).toEqual([CLIENT, CLIENT]); |
| 205 | + expect(seen.lastLoginIp).toBe(CLIENT); |
| 206 | + }); |
| 207 | + |
| 208 | + it('when the server established no address, it is handed none, whatever the request headers say', async () => { |
| 209 | + // What the library answers when it is handed no address is its own, |
| 210 | + // environment-dependent behaviour (nothing in production, a loopback |
| 211 | + // placeholder in development and test) — so each deployment's answer to a |
| 212 | + // request carrying no header at all is the control, never a literal. |
| 213 | + for (const deployment of [{}, { trustProxy: true }]) { |
| 214 | + const d = await serve(deployment); |
| 215 | + const control = await d.observe(undefined, {}); |
| 216 | + const seen = await d.observe(undefined, { |
| 217 | + ...(deployment.trustProxy ? {} : { 'x-forwarded-for': OTHER, 'x-real-ip': OTHER }), |
| 218 | + [VENDOR_CLIENT_ADDRESS_HEADER]: OTHER, |
| 219 | + }); |
| 220 | + |
| 221 | + const label = deployment.trustProxy ? 'trusted proxy, nothing forwarded' : 'no trusted proxy'; |
| 222 | + expect(seen.session, label).toEqual(control.session); |
| 223 | + expect(seen.refused, label).toEqual(control.refused); |
| 224 | + expect(seen.limiterKeys, label).toEqual(control.limiterKeys); |
| 225 | + expect([seen.session, seen.refused, ...seen.limiterKeys], label).not.toContain(OTHER); |
| 226 | + // …and the D7 login audit stamped none either. |
| 227 | + expect(seen.lastLoginIp, label).toBeUndefined(); |
| 228 | + } |
| 229 | + }); |
| 230 | +}); |
0 commit comments