diff --git a/.changeset/system-config-cross-instance.md b/.changeset/system-config-cross-instance.md new file mode 100644 index 00000000..0275e8ea --- /dev/null +++ b/.changeset/system-config-cross-instance.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +A `system_config` change now takes effect on every instance within about a second, not only on the instance that took the write (#597). Each instance used to cache config for five minutes, so disabling a login method, removing an OAuth provider or turning on `phishing_resistant_only` could stay ineffective on the other replicas for that long. Each instance now compares a hash of the stored rows with its cached copy at most once a second and reloads when they differ. Direct database edits are picked up the same way. If that check cannot reach the database, the config read fails instead of serving a copy it cannot show is current. diff --git a/docs/configuration.md b/docs/configuration.md index c105f99d..3ed6c4a2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -559,9 +559,12 @@ reverts it to the environment variable. The value looks correct in the database process restarts. Change it through the admin endpoints, or change the environment variable, rather than editing the row. -Reads are cached in-process for five minutes. Both write paths already invalidate that cache, so a -change through the admin endpoints takes effect immediately; a direct database edit does not, and -is not visible until the entry expires. See [`getSystemConfig.ts`](../src/config/getSystemConfig.ts). +Reads are cached in-process. Once a second at most, each instance compares an `md5` of the stored +rows with the copy it holds and reloads when they differ, so a change made through the admin +endpoints on any instance, or a direct database edit, applies everywhere within about a second. +The instance that took an admin write also clears its own cache at once. If that check cannot reach +the database, the read fails rather than serve a copy it cannot show is current. See +[`getSystemConfig.ts`](../src/config/getSystemConfig.ts). ### Policy versions diff --git a/docs/production-operations.md b/docs/production-operations.md index d7e05f5f..0e2e5dba 100644 --- a/docs/production-operations.md +++ b/docs/production-operations.md @@ -217,14 +217,15 @@ Everything that has to agree between instances lives in Postgres: sessions and r (the rotation claim is a single statement the database serialises), the lockout counter (`auth_failures`), OTP codes, magic links, WebAuthn challenges, the OAuth `state` replay record (`oidc_payloads`), `system_config` and the audit trail. -Several instances behind a load balancer share all of it. +Several instances behind a load balancer share all of it. Each instance caches `system_config`, but +checks it against the stored rows at most once a second, so a config write on one instance applies +on the others within about a second. Some state is held in each process, and with more than one instance it behaves differently: | State | Where | With N instances | | --------------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Rate limit and slow-down counters | `express-rate-limit` and `express-slow-down` in-memory stores ([`src/middleware`](../src/middleware)) | Each instance counts on its own, so a client whose requests are spread across instances gets up to N times the configured budget. Route by client address at the load balancer, or enforce a limit at the proxy as well. The account notice limits on `POST /applications/account-notices` are keyed by application and user rather than address, so an application can send up to N times its notice allowance however requests are routed. | -| `system_config` cache | Five minutes per process ([`getSystemConfig.ts`](../src/config/getSystemConfig.ts)) | A config write clears the cache only on the instance that served it. The others keep the old values (roles, origins, login methods, lockout policy, token lifetimes) for up to five minutes. Restart the instances when a change must apply at once. | | Audit degraded flag | Five minutes after a failed audit write ([`auditHealth.ts`](../src/services/auditHealth.ts)) | `/health/status` reports `degraded` only on the instance whose write failed. Monitor every instance, not one. | ## Redaction diff --git a/src/config/getSystemConfig.ts b/src/config/getSystemConfig.ts index 9419608d..80cee9e7 100644 --- a/src/config/getSystemConfig.ts +++ b/src/config/getSystemConfig.ts @@ -4,28 +4,55 @@ * See LICENSE file in the project root for full license information */ +import { QueryTypes } from 'sequelize'; + import { SystemConfig as SysConfigModel } from '../models/systemConfig.js'; import { SystemConfig, SystemConfigSchema } from '../schemas/systemConfig.schema.js'; import getLogger from '../utils/logger.js'; const logger = getLogger('systemConfig'); +// A write on any instance, or a direct database edit, is seen everywhere within this long. +// Under it, reads come from memory; past it, one small fingerprint query decides whether +// the cached copy is still the stored one. +export const SYSTEM_CONFIG_CHECK_INTERVAL_MS = 1_000; + +// Hashes the stored content rather than reading "updatedAt": that column is written from +// each instance's own clock, so skew between replicas can make a newer write look older, +// and a direct UPDATE need not touch it at all. +const FINGERPRINT_SQL = `SELECT md5(coalesce(string_agg(key || '=' || value::text, ',' ORDER BY key), '')) AS fingerprint FROM system_config`; + let cachedConfig: SystemConfig | null = null; -let lastLoadedAt = 0; +let cachedFingerprint: string | null = null; +let lastCheckedAt = 0; +let generation = 0; +let inFlight: Promise | null = null; -const CACHE_TTL_MS = 300_000; // 5 minutes +async function readFingerprint(): Promise { + const rows = await SysConfigModel.sequelize!.query<{ fingerprint: string }>(FINGERPRINT_SQL, { + type: QueryTypes.SELECT, + }); -export async function getSystemConfig(): Promise { - const now = Date.now(); + return rows[0]?.fingerprint ?? ''; +} - if (cachedConfig && now - lastLoadedAt < CACHE_TTL_MS) { - return cachedConfig; +interface Loaded { + config: SystemConfig; + fingerprint: string; +} + +async function loadConfig(): Promise { + const fingerprint = await readFingerprint(); + + if (cachedConfig && fingerprint === cachedFingerprint) { + return { config: cachedConfig, fingerprint }; } + // The fingerprint is read first, so a write that lands between the two reads leaves an + // older fingerprint beside newer rows, and the next check reloads. It never pairs a + // current fingerprint with stale rows. const rows = await SysConfigModel.findAll(); - const raw = Object.fromEntries(rows.map((row) => [row.key, row.value])); - const parsed = SystemConfigSchema.safeParse(raw); if (!parsed.success) { @@ -33,13 +60,43 @@ export async function getSystemConfig(): Promise { throw new Error('Invalid system_config: runtime configuration failed schema validation'); } - cachedConfig = parsed.data; - lastLoadedAt = now; + return { config: parsed.data, fingerprint }; +} + +/** + * Fails closed: when the fingerprint query errors, the call throws rather than serve a copy + * that can no longer be shown to be current. + */ +export async function getSystemConfig(): Promise { + if (cachedConfig && Date.now() - lastCheckedAt < SYSTEM_CONFIG_CHECK_INTERVAL_MS) { + return cachedConfig; + } + + if (!inFlight) { + const startedIn = generation; + const startedAt = Date.now(); + + inFlight = loadConfig() + .then(({ config, fingerprint }) => { + if (startedIn === generation) { + cachedConfig = config; + cachedFingerprint = fingerprint; + lastCheckedAt = startedAt; + } + return config; + }) + .finally(() => { + if (startedIn === generation) inFlight = null; + }); + } - return cachedConfig; + return inFlight; } export function invalidateSystemConfigCache() { + generation += 1; cachedConfig = null; - lastLoadedAt = 0; + cachedFingerprint = null; + lastCheckedAt = 0; + inFlight = null; } diff --git a/tests/postgres/systemConfigFreshness.spec.ts b/tests/postgres/systemConfigFreshness.spec.ts new file mode 100644 index 00000000..7d08d215 --- /dev/null +++ b/tests/postgres/systemConfigFreshness.spec.ts @@ -0,0 +1,77 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { bootstrapSystemConfig } from '../../src/config/bootstrapSystemConfig.js'; +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { buildSystemConfig } from '../factories/systemConfigFactory.js'; + +type ConfigModule = typeof import('../../src/config/getSystemConfig.js'); + +// Each import after resetModules is a separate cache, standing in for a separate replica. +async function instance(): Promise { + vi.resetModules(); + const module = await import('../../src/config/getSystemConfig.js'); + const { initializeModels: init } = await import('../../src/models/index.js'); + await init(); + return module; +} + +// Backdates updatedAt, as a replica with a slow clock would, to show it is not relied on. +async function setAppName(value: string) { + await getSequelize().query( + `UPDATE system_config SET value = to_jsonb(:value::text), "updatedAt" = now() - interval '1 day' WHERE key = 'app_name'`, + { replacements: { value } }, + ); +} + +let now = 1_000_000; + +beforeAll(async () => { + await initializeModels(); + for (const [key, value] of Object.entries( + buildSystemConfig({ frontend_url: 'http://localhost:5174' }), + )) { + await getSequelize().query( + `INSERT INTO system_config (key, value, "createdAt", "updatedAt") + VALUES (:key, :value, now(), now()) + ON CONFLICT (key) DO NOTHING`, + { replacements: { key, value: JSON.stringify(value) } }, + ); + } + await bootstrapSystemConfig(); + vi.spyOn(Date, 'now').mockImplementation(() => now); +}); + +afterAll(async () => { + vi.restoreAllMocks(); + await getSequelize().close(); +}); + +describe('system_config freshness across instances', () => { + it('shows a write made elsewhere once the check interval passes, even with a backdated updatedAt', async () => { + await setAppName('BeforeWrite'); + const a = await instance(); + const b = await instance(); + + expect((await a.getSystemConfig()).app_name).toBe('BeforeWrite'); + expect((await b.getSystemConfig()).app_name).toBe('BeforeWrite'); + + await setAppName('AfterWrite'); + a.invalidateSystemConfigCache(); + + expect((await a.getSystemConfig()).app_name).toBe('AfterWrite'); + expect((await b.getSystemConfig()).app_name).toBe('BeforeWrite'); + + now += b.SYSTEM_CONFIG_CHECK_INTERVAL_MS; + + expect((await b.getSystemConfig()).app_name).toBe('AfterWrite'); + }); + + it('keeps the cached copy while the stored rows are unchanged', async () => { + const a = await instance(); + const first = await a.getSystemConfig(); + + now += a.SYSTEM_CONFIG_CHECK_INTERVAL_MS; + + expect(await a.getSystemConfig()).toBe(first); + }); +}); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index 2ef8e25a..98209716 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -35,6 +35,7 @@ vi.mock('../../src/models/systemConfig.js', () => ({ // The transaction object carries LOCK because the provider edits read the row // FOR UPDATE, so the double has to offer what the real one does. transaction: vi.fn((fn: any) => fn({ LOCK: { UPDATE: 'UPDATE' } })), + query: vi.fn(async () => [{ fingerprint: '' }]), }, }, })); diff --git a/tests/unit/config/getSystemConfig.spec.ts b/tests/unit/config/getSystemConfig.spec.ts index 137a9cc6..440bd8a2 100644 --- a/tests/unit/config/getSystemConfig.spec.ts +++ b/tests/unit/config/getSystemConfig.spec.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { buildSystemConfig } from '../../factories/systemConfigFactory.js'; @@ -7,89 +7,153 @@ vi.unmock('../../../src/config/getSystemConfig'); const rowsFrom = (config: Record) => Object.entries(config).map(([key, value]) => ({ key, value })); +async function load() { + const { SystemConfig } = await import('../../../src/models/systemConfig'); + const module = await import('../../../src/config/getSystemConfig'); + const findAll = SystemConfig.findAll as any; + const query = SystemConfig.sequelize!.query as any; + query.mockResolvedValue([{ fingerprint: 'v1' }]); + return { ...module, findAll, query }; +} + describe('getSystemConfig', () => { + let now = 1_000_000; + beforeEach(() => { vi.resetModules(); vi.clearAllMocks(); + now = 1_000_000; + vi.spyOn(Date, 'now').mockImplementation(() => now); }); - it('fetches and validates config from DB when cache empty', async () => { - const { SystemConfig } = await import('../../../src/models/systemConfig'); - - (SystemConfig.findAll as any).mockResolvedValue(rowsFrom(buildSystemConfig())); + afterEach(() => { + vi.restoreAllMocks(); + }); - const { getSystemConfig } = await import('../../../src/config/getSystemConfig'); + it('fetches and validates config from DB when cache empty', async () => { + const { getSystemConfig, findAll, query } = await load(); + findAll.mockResolvedValue(rowsFrom(buildSystemConfig())); const result = await getSystemConfig(); - expect(SystemConfig.findAll).toHaveBeenCalled(); + expect(query).toHaveBeenCalledWith(expect.stringContaining('md5'), { type: 'SELECT' }); + expect(findAll).toHaveBeenCalledTimes(1); expect(result.app_name).toBe('SeamlessAuth'); expect(result.default_roles).toEqual(['user']); }); it('throws when the stored config fails schema validation', async () => { - const { SystemConfig } = await import('../../../src/models/systemConfig'); - - (SystemConfig.findAll as any).mockResolvedValue([{ key: 'app_name', value: 'ab' }]); - - const { getSystemConfig } = await import('../../../src/config/getSystemConfig'); + const { getSystemConfig, findAll } = await load(); + findAll.mockResolvedValue([{ key: 'app_name', value: 'ab' }]); await expect(getSystemConfig()).rejects.toThrow(/Invalid system_config/); }); - it('returns cached config when within TTL', async () => { - const { SystemConfig } = await import('../../../src/models/systemConfig'); + it('serves from memory without a query inside the check interval', async () => { + const { getSystemConfig, findAll, query, SYSTEM_CONFIG_CHECK_INTERVAL_MS } = await load(); + findAll.mockResolvedValue(rowsFrom(buildSystemConfig())); - (SystemConfig.findAll as any).mockResolvedValue(rowsFrom(buildSystemConfig())); + const first = await getSystemConfig(); + now += SYSTEM_CONFIG_CHECK_INTERVAL_MS - 1; + const second = await getSystemConfig(); + + expect(second).toBe(first); + expect(query).toHaveBeenCalledTimes(1); + expect(findAll).toHaveBeenCalledTimes(1); + }); - const { getSystemConfig } = await import('../../../src/config/getSystemConfig'); + it('keeps the cached copy when the fingerprint is unchanged', async () => { + const { getSystemConfig, findAll, query, SYSTEM_CONFIG_CHECK_INTERVAL_MS } = await load(); + findAll.mockResolvedValue(rowsFrom(buildSystemConfig())); const first = await getSystemConfig(); + now += SYSTEM_CONFIG_CHECK_INTERVAL_MS; const second = await getSystemConfig(); - expect(SystemConfig.findAll).toHaveBeenCalledTimes(1); - expect(second).toEqual(first); + expect(second).toBe(first); + expect(query).toHaveBeenCalledTimes(2); + expect(findAll).toHaveBeenCalledTimes(1); }); - it('refreshes cache after TTL expires', async () => { - const { SystemConfig } = await import('../../../src/models/systemConfig'); - - (SystemConfig.findAll as any) + it('reloads within the check interval when another instance changes the config', async () => { + const { getSystemConfig, findAll, query, SYSTEM_CONFIG_CHECK_INTERVAL_MS } = await load(); + findAll .mockResolvedValueOnce(rowsFrom(buildSystemConfig({ app_name: 'AppOne' }))) .mockResolvedValueOnce(rowsFrom(buildSystemConfig({ app_name: 'AppTwo' }))); - const { getSystemConfig } = await import('../../../src/config/getSystemConfig'); + expect((await getSystemConfig()).app_name).toBe('AppOne'); - const first = await getSystemConfig(); + query.mockResolvedValue([{ fingerprint: 'v2' }]); + now += SYSTEM_CONFIG_CHECK_INTERVAL_MS; - // simulate time passing - vi.spyOn(Date, 'now') - .mockReturnValueOnce(Date.now() + 1) - .mockReturnValueOnce(Date.now() + 400_000); // > TTL + expect((await getSystemConfig()).app_name).toBe('AppTwo'); + expect(findAll).toHaveBeenCalledTimes(2); + }); - const second = await getSystemConfig(); + it('treats an empty fingerprint result as an empty table', async () => { + const { getSystemConfig, findAll, query } = await load(); + query.mockResolvedValue([]); + findAll.mockResolvedValue(rowsFrom(buildSystemConfig())); - expect(second.app_name).not.toBe(first.app_name); - expect(SystemConfig.findAll).toHaveBeenCalledTimes(2); + await expect(getSystemConfig()).resolves.toMatchObject({ app_name: 'SeamlessAuth' }); }); - it('invalidates cache manually', async () => { - const { SystemConfig } = await import('../../../src/models/systemConfig'); + it('fails closed when the fingerprint cannot be read once the interval has passed', async () => { + const { getSystemConfig, findAll, query, SYSTEM_CONFIG_CHECK_INTERVAL_MS } = await load(); + findAll.mockResolvedValue(rowsFrom(buildSystemConfig())); + await getSystemConfig(); + + query.mockRejectedValueOnce(new Error('connection terminated')); + now += SYSTEM_CONFIG_CHECK_INTERVAL_MS; + + await expect(getSystemConfig()).rejects.toThrow('connection terminated'); + + // The failed check did not extend the cached copy, so the next call checks again. + await expect(getSystemConfig()).resolves.toMatchObject({ app_name: 'SeamlessAuth' }); + expect(query).toHaveBeenCalledTimes(3); + }); + + it('shares one load between concurrent callers', async () => { + const { getSystemConfig, findAll, query } = await load(); + findAll.mockResolvedValue(rowsFrom(buildSystemConfig())); + + const [a, b] = await Promise.all([getSystemConfig(), getSystemConfig()]); + + expect(a).toBe(b); + expect(query).toHaveBeenCalledTimes(1); + expect(findAll).toHaveBeenCalledTimes(1); + }); - (SystemConfig.findAll as any) + it('invalidates cache manually', async () => { + const { getSystemConfig, invalidateSystemConfigCache, findAll } = await load(); + findAll .mockResolvedValueOnce(rowsFrom(buildSystemConfig({ app_name: 'AppOne' }))) .mockResolvedValueOnce(rowsFrom(buildSystemConfig({ app_name: 'AppTwo' }))); - const { getSystemConfig, invalidateSystemConfigCache } = - await import('../../../src/config/getSystemConfig'); - await getSystemConfig(); + invalidateSystemConfigCache(); + + expect((await getSystemConfig()).app_name).toBe('AppTwo'); + expect(findAll).toHaveBeenCalledTimes(2); + }); + + it('does not let a load started before an invalidation repopulate the cache', async () => { + const { getSystemConfig, invalidateSystemConfigCache, findAll } = await load(); + let release!: (rows: unknown) => void; + findAll + .mockReturnValueOnce(new Promise((resolve) => (release = resolve))) + .mockResolvedValueOnce(rowsFrom(buildSystemConfig({ app_name: 'AfterWrite' }))); + + const stale = getSystemConfig(); + await vi.waitFor(() => expect(findAll).toHaveBeenCalledTimes(1)); invalidateSystemConfigCache(); + const fresh = getSystemConfig(); - const result = await getSystemConfig(); + release(rowsFrom(buildSystemConfig({ app_name: 'BeforeWrite' }))); - expect(result.app_name).toBe('AppTwo'); - expect(SystemConfig.findAll).toHaveBeenCalledTimes(2); + expect((await stale).app_name).toBe('BeforeWrite'); + expect((await fresh).app_name).toBe('AfterWrite'); + expect((await getSystemConfig()).app_name).toBe('AfterWrite'); }); });