Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/system-config-cross-instance.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 6 additions & 3 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 3 additions & 2 deletions docs/production-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
81 changes: 69 additions & 12 deletions src/config/getSystemConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,99 @@
* 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<SystemConfig> | null = null;

const CACHE_TTL_MS = 300_000; // 5 minutes
async function readFingerprint(): Promise<string> {
const rows = await SysConfigModel.sequelize!.query<{ fingerprint: string }>(FINGERPRINT_SQL, {
type: QueryTypes.SELECT,
});

export async function getSystemConfig(): Promise<SystemConfig> {
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<Loaded> {
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) {
logger.error(`Invalid system_config on runtime load: ${parsed.error.message}`);
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<SystemConfig> {
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;
}
77 changes: 77 additions & 0 deletions tests/postgres/systemConfigFreshness.spec.ts
Original file line number Diff line number Diff line change
@@ -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<ConfigModule> {
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);
});
});
1 change: 1 addition & 0 deletions tests/setup/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '' }]),
},
},
}));
Expand Down
Loading