From 443cf20c35475256eced85d2064d353fd6329699 Mon Sep 17 00:00:00 2001 From: shizn Date: Fri, 27 Nov 2026 23:13:25 -0800 Subject: [PATCH 1/3] Validate Auth0 signing configuration and registration email --- ops/container-security/check.py | 2 +- packages/api-server/README.md | 2 +- packages/api-server/__tests__/core/app-startup.ts | 2 +- packages/api-server/__tests__/helpers/app.ts | 2 +- .../__tests__/security/account-registration.test.ts | 9 +++++++++ .../__tests__/security/runtime-upgrade.test.ts | 6 ++++++ packages/api-server/src/plugins/auth/auth0.ts | 7 +++++-- .../src/plugins/services/user-service/index.ts | 2 +- 8 files changed, 25 insertions(+), 7 deletions(-) diff --git a/ops/container-security/check.py b/ops/container-security/check.py index f301b83fd6..632b6c162a 100644 --- a/ops/container-security/check.py +++ b/ops/container-security/check.py @@ -117,7 +117,7 @@ def create(suffix, image, command, options=()): '-e', 'DATABASE_URL=mysql://executoruser:executorpassword@tidb:4000/ossinsight_container_test', '-e', 'PLAYGROUND_DATABASE_URL=mysql://container_reader:webshellpassword@tidb:4000/ossinsight_container_test', '-e', 'REDIS_URL=redis://redis:6379/0', '-e', 'GITHUB_ACCESS_TOKENS=', - '-e', 'OPENAI_API_KEY=synthetic-test-key', '-e', 'AUTH0_SECRET=synthetic-local-hmac-secret', + '-e', 'OPENAI_API_KEY=synthetic-test-key', '-e', 'AUTH0_SECRET=synthetic-local-hmac-secret-for-testing', '-e', 'OPERATIONS_TOKEN=synthetic-local-operations-token-32-characters']) run(['docker', 'start', api]) print(run(['docker', 'exec', api, 'node', '/fixtures/api-probe.cjs'], timeout=60).strip(), flush=True) diff --git a/packages/api-server/README.md b/packages/api-server/README.md index c354b42141..5212fcc95e 100644 --- a/packages/api-server/README.md +++ b/packages/api-server/README.md @@ -200,7 +200,7 @@ share the same ioredis 5 client. Keep the queue names and existing credentials w rolling out dependency updates, and verify both authenticated metrics and the worker drain procedure below. -`AUTH0_SECRET` accepts a symmetric client secret. Public-key JWT verification uses +`AUTH0_SECRET` requires a randomly generated symmetric client secret of at least 32 bytes for HS256. Public-key JWT verification uses `AUTH0_DOMAIN`; PEM keys and certificates cannot be configured as HMAC secrets. Unsupported signing algorithms and critical JWT header extensions are rejected before key lookup, and the signature must still verify before an actor is assigned. diff --git a/packages/api-server/__tests__/core/app-startup.ts b/packages/api-server/__tests__/core/app-startup.ts index 575ed11733..740e10f546 100644 --- a/packages/api-server/__tests__/core/app-startup.ts +++ b/packages/api-server/__tests__/core/app-startup.ts @@ -24,7 +24,7 @@ test.each(['current-only', 'overlap', 'expired'] as const)('the production CLI b cwd: resolve(__dirname, '../..'), env: {PATH: process.env.PATH, NODE_ENV: 'test', CONFIGS_PATH: resolve(__dirname, '../../../../configs'), DATABASE_URL: db.url(), PLAYGROUND_DATABASE_URL: db.analyticsUrl(), REDIS_URL: redis.url(), - GITHUB_ACCESS_TOKENS: '', OPENAI_API_KEY: 'synthetic-test-key', AUTH0_SECRET: 'synthetic-local-hmac-secret', + GITHUB_ACCESS_TOKENS: '', OPENAI_API_KEY: 'synthetic-test-key', AUTH0_SECRET: 'synthetic-local-hmac-secret-for-testing', OPERATIONS_TOKEN: token, ...rotation}, stdio: ['ignore', 'pipe', 'pipe'], }); diff --git a/packages/api-server/__tests__/helpers/app.ts b/packages/api-server/__tests__/helpers/app.ts index 893927a024..6ece41a3d8 100644 --- a/packages/api-server/__tests__/helpers/app.ts +++ b/packages/api-server/__tests__/helpers/app.ts @@ -41,7 +41,7 @@ async function createApp () { EXPLORER_OUTPUT_ANSWER_IN_STREAM: false, OPENAI_API_KEY: 'fake', AUTH0_DOMAIN: 'auth0', - AUTH0_SECRET: 'auth0', + AUTH0_SECRET: 'synthetic-local-hmac-secret-for-testing', }; Object.assign(process.env, env); diff --git a/packages/api-server/__tests__/security/account-registration.test.ts b/packages/api-server/__tests__/security/account-registration.test.ts index 4336e2b116..bf6eba6f7e 100644 --- a/packages/api-server/__tests__/security/account-registration.test.ts +++ b/packages/api-server/__tests__/security/account-registration.test.ts @@ -33,6 +33,15 @@ function fixture(options: {binding?: any[]; indexes?: any[]; error?: number; win afterEach(() => jest.restoreAllMocks()); +test.each([true, false, undefined])('registration stores the profile email only when verified (%s)', async verified => { + const f = fixture(); + f.fetch.mockResolvedValue({...profile, email_verified: verified}); + expect(await f.service.findOrCreateUserByAccount(identity, 'synthetic-token')).toBe(99); + expect(f.connection.query).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO sys_users'), [ + profile.name, verified === true ? profile.email : '', false, profile.picture, expect.anything(), expect.anything(), true, + ]); +}); + test('existing identities avoid profile fetches and creation transactions', async () => { const f = fixture({binding: [{id: 7, userId: 7}]}); expect(await f.service.findOrCreateUserByAccount(identity, 'synthetic-token')).toBe(7); diff --git a/packages/api-server/__tests__/security/runtime-upgrade.test.ts b/packages/api-server/__tests__/security/runtime-upgrade.test.ts index 2925a4b7d8..9634411955 100644 --- a/packages/api-server/__tests__/security/runtime-upgrade.test.ts +++ b/packages/api-server/__tests__/security/runtime-upgrade.test.ts @@ -68,6 +68,12 @@ test('a public RSA verification key cannot be reused as an HMAC signing secret', } finally { await app.close(); fetchKeys.mockRestore(); } }); +test('symmetric Auth0 configuration requires at least 32 bytes', async () => { + await expect(authenticationApp('x'.repeat(31))).rejects.toThrow('at least 32 bytes'); + const app = await authenticationApp('x'.repeat(32)); + await app.close(); +}); + test('a PEM public key cannot be configured as the symmetric Auth0 client secret', async () => { const {publicKey} = generateKeyPairSync('rsa', {modulusLength: 2048}); const pem = publicKey.export({format: 'pem', type: 'spki'}).toString(); diff --git a/packages/api-server/src/plugins/auth/auth0.ts b/packages/api-server/src/plugins/auth/auth0.ts index ae0e4fb8ed..ede0768331 100644 --- a/packages/api-server/src/plugins/auth/auth0.ts +++ b/packages/api-server/src/plugins/auth/auth0.ts @@ -9,8 +9,8 @@ export interface Auth0UserInfo { name: string; picture: string; updated_at: string; - email: string; - email_verified: boolean; + email?: string; + email_verified?: boolean; } export const AUTH0_NAMESPACE = `https://ossinsight.io`; @@ -47,6 +47,9 @@ export default fp(async (app) => { if (secret && /-----BEGIN [A-Z ]*(?:KEY|CERTIFICATE)-----/.test(secret)) { throw new Error('AUTH0_SECRET must be a symmetric client secret; use AUTH0_DOMAIN for public-key verification.'); } + if (secret && Buffer.byteLength(secret.trim(), 'utf8') < 32) { + throw new Error('AUTH0_SECRET must contain at least 32 bytes for HS256.'); + } const audience = app.config.AUTH0_AUDIENCE?.trim(); const clientIds = new Set((app.config.AUTH0_ALLOWED_CLIENT_IDS || []).map(value => value.trim()).filter(Boolean)); const domain = app.config.AUTH0_DOMAIN; diff --git a/packages/api-server/src/plugins/services/user-service/index.ts b/packages/api-server/src/plugins/services/user-service/index.ts index 6f2fd9c7b4..624ad60d42 100644 --- a/packages/api-server/src/plugins/services/user-service/index.ts +++ b/packages/api-server/src/plugins/services/user-service/index.ts @@ -185,7 +185,7 @@ export class UserService { VALUES(?, ?, ?, ?, ?, ?, ?) `, [ userInfo.name, - userInfo.email, + userInfo.email_verified === true && typeof userInfo.email === 'string' ? userInfo.email : '', GET_EMAIL_UPDATES_DEFAULT, userInfo.picture, UserRole.USER, From 5f2b53dddfb3a83f56c0170cbc8e88d566672bf5 Mon Sep 17 00:00:00 2001 From: shizn Date: Sat, 28 Nov 2026 02:26:08 -0800 Subject: [PATCH 2/3] Honor account suspension throughout authenticated query and registration paths --- .../__tests__/core/account-registration.ts | 14 +++++ .../security/account-registration.test.ts | 28 ++++++++-- .../__tests__/security/answer-access.test.ts | 16 ++++++ .../plugins/services/user-service/index.ts | 54 +++++++++++-------- .../src/routes/q/playground/index.ts | 1 + 5 files changed, 88 insertions(+), 25 deletions(-) diff --git a/packages/api-server/__tests__/core/account-registration.ts b/packages/api-server/__tests__/core/account-registration.ts index 84e4cd319a..9e500d7d4b 100644 --- a/packages/api-server/__tests__/core/account-registration.ts +++ b/packages/api-server/__tests__/core/account-registration.ts @@ -69,6 +69,20 @@ test('an orphaned account cannot recreate or reassign its missing user', async ( expect(rows).toEqual([{user_id: 2147483000}]); }); +test('disabling and re-enabling a bound account takes effect on the next request', async () => { + const {service, identity, profile} = serviceFor('900000005'); + const fetch = jest.spyOn(service, 'fetchAuth0UserInfo').mockResolvedValue(profile); + const id = await service.findOrCreateUserByAccount(identity, 'synthetic-token'); + const request = {user: {sub: identity.sub}} as any; + await app.mysql.query('UPDATE sys_users SET enable = 0 WHERE id = ?', [id]); + await expect(service.checkAccountStatus(request)).rejects.toMatchObject({statusCode: 403}); + await expect(service.findOrCreateUserByAccount(identity, 'synthetic-token')).rejects.toMatchObject({statusCode: 403}); + await app.mysql.query('UPDATE sys_users SET enable = 1 WHERE id = ?', [id]); + await expect(service.checkAccountStatus(request)).resolves.toBeUndefined(); + await expect(service.findOrCreateUserByAccount(identity, 'synthetic-token')).resolves.toBe(id); + expect(fetch).toHaveBeenCalledTimes(1); +}); + test('missing production identity constraint blocks new registration before any user insert', async () => { const {service, identity} = serviceFor('900000003'); const before = await userCount(); diff --git a/packages/api-server/__tests__/security/account-registration.test.ts b/packages/api-server/__tests__/security/account-registration.test.ts index bf6eba6f7e..676464aeca 100644 --- a/packages/api-server/__tests__/security/account-registration.test.ts +++ b/packages/api-server/__tests__/security/account-registration.test.ts @@ -6,7 +6,7 @@ const identity = {sub: 'github|123', email: 'fixture@example.test', provider: 'g const profile = {sub: identity.sub, name: 'Fixture', email: identity.email, picture: 'https://example.test/avatar', nickname: 'fixture', updated_at: '', email_verified: true}; const uniqueIndex = ['provider', 'provider_account_id'].map(columnName => ({indexName: 'unique_identity', columnName, prefixLength: null})); -function fixture(options: {binding?: any[]; indexes?: any[]; error?: number; winningId?: number} = {}) { +function fixture(options: {binding?: any[]; indexes?: any[]; error?: number; winningId?: number; winningEnable?: number} = {}) { let binding = options.binding || []; const connection = { query: jest.fn(async (sql: string) => { @@ -16,7 +16,7 @@ function fixture(options: {binding?: any[]; indexes?: any[]; error?: number; win return [{}]; }), commit: jest.fn(async () => {}), - rollback: jest.fn(async () => {if (options.winningId) binding = [{id: options.winningId, userId: options.winningId}];}), + rollback: jest.fn(async () => {if (options.winningId) binding = [{id: options.winningId, userId: options.winningId, enable: options.winningEnable ?? 1}];}), release: jest.fn(), }; const pool = { @@ -43,12 +43,34 @@ test.each([true, false, undefined])('registration stores the profile email only }); test('existing identities avoid profile fetches and creation transactions', async () => { - const f = fixture({binding: [{id: 7, userId: 7}]}); + const f = fixture({binding: [{id: 7, userId: 7, enable: 1}]}); expect(await f.service.findOrCreateUserByAccount(identity, 'synthetic-token')).toBe(7); expect(f.fetch).not.toHaveBeenCalled(); expect(f.pool.getConnection).not.toHaveBeenCalled(); }); +test.each([0, false, null])('an inactive account (%p) is refused before registration or profile lookup', async enable => { + const f = fixture({binding: [{id: 7, userId: 7, enable}]}); + await expect(f.service.findOrCreateUserByAccount(identity, 'synthetic-token')).rejects.toMatchObject({statusCode: 403}); + expect(f.fetch).not.toHaveBeenCalled(); + expect(f.pool.getConnection).not.toHaveBeenCalled(); + expect(f.pool.query.mock.calls[0][0]).toContain('su.enable'); +}); + +test('a disabled concurrent registration winner is rejected on retry', async () => { + const f = fixture({error: 1062, winningId: 42, winningEnable: 0}); + await expect(f.service.findOrCreateUserByAccount(identity, 'synthetic-token')).rejects.toMatchObject({statusCode: 403}); + expect(f.connection.rollback).toHaveBeenCalledTimes(1); +}); + +test('checking an unregistered Playground identity never creates an account', async () => { + const f = fixture(); + await f.service.checkAccountStatus({user: {sub: identity.sub}} as any); + expect(f.pool.query).toHaveBeenCalledTimes(1); + expect(f.fetch).not.toHaveBeenCalled(); + expect(f.pool.getConnection).not.toHaveBeenCalled(); +}); + test.each([{binding: [{id: null, userId: 7}]}, {binding: [{id: 7, userId: 7}, {id: 8, userId: 8}]}])('ambiguous or orphaned binding %# cannot create a replacement identity', async ({binding}) => { const f = fixture({binding}); await expect(f.service.findOrCreateUserByAccount(identity, 'synthetic-token')).rejects.toMatchObject({statusCode: 409}); diff --git a/packages/api-server/__tests__/security/answer-access.test.ts b/packages/api-server/__tests__/security/answer-access.test.ts index d61bf1c5d8..a04044d2e5 100644 --- a/packages/api-server/__tests__/security/answer-access.test.ts +++ b/packages/api-server/__tests__/security/answer-access.test.ts @@ -76,6 +76,22 @@ test('playground SQL requires authentication before execution', async () => { } finally { await app.close(); } }); +test('a suspended account cannot start a Playground query', async () => { + const app = Fastify(); + const run = jest.fn(); + const checkAccountStatus = jest.fn(async () => { throw new APIError(403, 'Account is disabled.'); }); + app.decorate('authenticate', async () => {}); + app.decorate('userService', {checkAccountStatus} as any); + app.decorate('sqlRunner', {run}); + await app.register(playground); + try { + const response = await app.inject({method: 'POST', url: '/', payload: {type: 'repo', id: '42', sql: 'SELECT 1'}}); + expect(response.statusCode).toBe(403); + expect(checkAccountStatus).toHaveBeenCalledTimes(1); + expect(run).not.toHaveBeenCalled(); + } finally {await app.close();} +}); + describe('answer polling', () => { beforeEach(() => jest.useFakeTimers()); afterEach(() => jest.useRealTimers()); diff --git a/packages/api-server/src/plugins/services/user-service/index.ts b/packages/api-server/src/plugins/services/user-service/index.ts index 624ad60d42..3190148782 100644 --- a/packages/api-server/src/plugins/services/user-service/index.ts +++ b/packages/api-server/src/plugins/services/user-service/index.ts @@ -80,6 +80,14 @@ export default fp( } ); +function accountIdentity(subject: unknown): [string, string] { + const parts = typeof subject === 'string' ? subject.split('|') : []; + const [provider, id] = parts; + if (parts.length !== 2 || !/^[a-z0-9][a-z0-9_-]{0,19}$/.test(provider) || + !/^[\x21-\x7e]{1,128}$/.test(id)) throw new APIError(401, 'Invalid account identity.'); + return [provider, id]; +} + export class UserService { private identityConstraintReady?: Promise; constructor( @@ -147,27 +155,10 @@ export class UserService { async findOrCreateUserByAccount(user: Auth0UserMetadata & { sub: string }, token?: string): Promise { if (!token) throw new APIError(401, 'An authorization token is required.'); - const identity = typeof user?.sub === 'string' ? user.sub.split('|') : []; + const identity = accountIdentity(user?.sub); const [provider, idString] = identity; - if (identity.length !== 2 || !/^[a-z0-9][a-z0-9_-]{0,19}$/.test(provider) || - !/^[\x21-\x7e]{1,128}$/.test(idString)) throw new APIError(401, 'Invalid account identity.'); const githubLogin = user?.github_login || null; - const lookupSQL = `SELECT sa.user_id AS userId, su.id - FROM sys_accounts sa LEFT JOIN sys_users su ON su.id = sa.user_id - WHERE sa.provider = ? AND sa.provider_account_id = ?`; - const readBinding = (rows: Array<{id: number | null; userId: number}>): number | undefined => { - // An orphan is not a new identity: recreating it could resurrect a deleted - // account. Existing ambiguous or orphaned bindings require explicit repair. - if (rows.length > 1 || (rows.length === 1 && rows[0].id == null)) { - throw new APIError(409, 'Account binding requires administrator review.'); - } - return rows[0]?.id ?? undefined; - }; - const lookup = async () => { - const [rows] = await this.tidb.query(lookupSQL, [provider, idString]); - return readBinding(rows); - }; - const existing = await lookup(); + const existing = await this.readActiveBinding(identity); if (existing !== undefined) return existing; await this.requireUniqueAccountIdentity(); @@ -177,8 +168,7 @@ export class UserService { for (let attempt = 0; attempt < 3; attempt++) { try { const created = await withTransaction(this.tidb, async (conn) => { - const [rows] = await conn.query(lookupSQL + ' FOR UPDATE', [provider, idString]); - const winner = readBinding(rows); + const winner = await this.readActiveBinding(identity, conn); if (winner !== undefined) return winner; const [rs] = await conn.query(` INSERT INTO sys_users(name, email_address, email_get_updates, avatar_url, role, created_at, enable) @@ -209,7 +199,7 @@ export class UserService { // The losing transaction (including its provisional sys_users row) has // rolled back. Read the committed winner using a fresh transaction view. if ([1062, 1213, 9007].includes(errno)) { - const winner = await lookup(); + const winner = await this.readActiveBinding(identity); if (winner !== undefined) return winner; continue; } @@ -219,6 +209,26 @@ export class UserService { throw new APIError(503, 'Account registration is busy, please retry.'); } + async checkAccountStatus(request: FastifyRequest): Promise { + const identity = accountIdentity((request.user as Auth0User)?.sub); + await this.readActiveBinding(identity); + } + + private async readActiveBinding(identity: [string, string], connection?: Pick): Promise { + const sql = `SELECT sa.user_id AS userId, su.id, su.enable + FROM sys_accounts sa LEFT JOIN sys_users su ON su.id = sa.user_id + WHERE sa.provider = ? AND sa.provider_account_id = ?`; + const [rows] = await (connection ?? this.tidb).query(connection ? sql + ' FOR UPDATE' : sql, identity); + if (rows.length > 1 || (rows.length === 1 && rows[0].id == null)) { + throw new APIError(409, 'Account binding requires administrator review.'); + } + const account = rows[0]; + if (account && account.enable !== 1 && account.enable !== true) { + throw new APIError(403, 'Account is disabled.'); + } + return account?.id; + } + private async requireUniqueAccountIdentity(): Promise { if (!this.identityConstraintReady) { this.identityConstraintReady = (async () => { diff --git a/packages/api-server/src/routes/q/playground/index.ts b/packages/api-server/src/routes/q/playground/index.ts index a4462b004d..d165fa540f 100644 --- a/packages/api-server/src/routes/q/playground/index.ts +++ b/packages/api-server/src/routes/q/playground/index.ts @@ -20,6 +20,7 @@ const root: FastifyPluginAsync = async (app, opts) => { }, }}, }, async (request, reply) => { + await app.userService.checkAccountStatus(request); const { sql: sqlString, type, From 661a1d163d86fb4aa9ea47f9ceb0a1bb90f6ec47 Mon Sep 17 00:00:00 2001 From: shizn Date: Sat, 28 Nov 2026 03:22:02 -0800 Subject: [PATCH 3/3] Require authenticated TLS for production Redis connections --- ops/container-security/check.py | 26 +++++++++-- packages/api-server/README.md | 9 +++- .../__tests__/security/queue-worker.test.ts | 2 +- .../security/redis-connection.test.ts | 44 +++++++++++++++++++ packages/api-server/src/plugins/redis.ts | 4 +- .../api-server/src/utils/redis-connection.ts | 26 +++++++++++ packages/api-server/src/worker/config.ts | 7 +-- packages/api-server/src/worker/main.ts | 2 +- 8 files changed, 108 insertions(+), 12 deletions(-) create mode 100644 packages/api-server/__tests__/security/redis-connection.test.ts create mode 100644 packages/api-server/src/utils/redis-connection.ts diff --git a/ops/container-security/check.py b/ops/container-security/check.py index f301b83fd6..fcfe25cc9c 100644 --- a/ops/container-security/check.py +++ b/ops/container-security/check.py @@ -105,8 +105,28 @@ def create(suffix, image, command, options=()): if state['ExitCode']: raise RuntimeError(suffix + ' failed:\n' + output[-4000:] + run(['docker', 'logs', container])[-4000:]) print(output.strip(), flush=True) - redis = create('redis', REDIS, ['redis-server', '--save', '', '--appendonly', 'no', '--dir', '/tmp', '--maxmemory', '128mb', '--protected-mode', 'no'], - ['--network-alias=redis', '--user=999:999', '--read-only', '--cap-drop=ALL', + redis_dir = fixture / 'redis-tls' + redis_dir.mkdir() + run(['openssl', 'req', '-new', '-newkey', 'rsa:2048', '-nodes', '-subj', '/CN=redis', + '-keyout', str(redis_dir / 'server.key'), '-out', str(fixture / 'redis.csr')]) + (fixture / 'redis.ext').write_text('subjectAltName=DNS:redis\nextendedKeyUsage=serverAuth\n') + run(['openssl', 'x509', '-req', '-in', str(fixture / 'redis.csr'), '-CA', str(fixture / 'ca.pem'), + '-CAkey', str(fixture / 'ca.key'), '-CAcreateserial', '-days', '1', '-extfile', str(fixture / 'redis.ext'), + '-out', str(redis_dir / 'server.pem')]) + (redis_dir / 'ca.pem').write_bytes((fixture / 'ca.pem').read_bytes()) + for item in redis_dir.iterdir(): + item.chmod(0o444) + redis_volume = prefix + '-redis-tls' + run(['docker', 'volume', 'create', redis_volume]) + volumes.append(redis_volume) + redis_mount = 'type=volume,source=' + redis_volume + ',target=/tls' + redis_copy = create('redis-copy', args.api_image, ['true'], ['--mount', redis_mount]) + run(['docker', 'cp', str(redis_dir) + '/.', redis_copy + ':/tls']) + redis_password = uuid.uuid4().hex + redis = create('redis', REDIS, ['redis-server', '--save', '', '--appendonly', 'no', '--dir', '/tmp', '--maxmemory', '128mb', '--port', '0', + '--tls-port', '6379', '--tls-cert-file', '/tls/server.pem', '--tls-key-file', '/tls/server.key', + '--tls-ca-cert-file', '/tls/ca.pem', '--tls-auth-clients', 'no', '--requirepass', redis_password], + ['--network-alias=redis', '--mount', redis_mount + ',readonly', '--user=999:999', '--read-only', '--cap-drop=ALL', '--security-opt=no-new-privileges', '--memory=256m', '--cpus=1', '--tmpfs=/tmp:rw,noexec,nosuid,size=32m']) run(['docker', 'start', redis]) api = create('api', args.api_image, [], @@ -116,7 +136,7 @@ def create(suffix, image, command, options=()): '-e', 'NODE_EXTRA_CA_CERTS=/fixtures/ca.pem', '-e', 'API_SERVER_PORT=3451', '-e', 'DATABASE_URL=mysql://executoruser:executorpassword@tidb:4000/ossinsight_container_test', '-e', 'PLAYGROUND_DATABASE_URL=mysql://container_reader:webshellpassword@tidb:4000/ossinsight_container_test', - '-e', 'REDIS_URL=redis://redis:6379/0', '-e', 'GITHUB_ACCESS_TOKENS=', + '-e', 'REDIS_URL=rediss://:' + redis_password + '@redis:6379/0', '-e', 'GITHUB_ACCESS_TOKENS=', '-e', 'OPENAI_API_KEY=synthetic-test-key', '-e', 'AUTH0_SECRET=synthetic-local-hmac-secret', '-e', 'OPERATIONS_TOKEN=synthetic-local-operations-token-32-characters']) run(['docker', 'start', api]) diff --git a/packages/api-server/README.md b/packages/api-server/README.md index c354b42141..6170a1c8f0 100644 --- a/packages/api-server/README.md +++ b/packages/api-server/README.md @@ -11,7 +11,7 @@ Create a `.env` file in the `/packages/api-server` directory and fill in the fol | Name | Description | Default | |------------------------|------------------------------------------|----------------------------------------------------------------------------| | `DATABASE_URL` | Database URL to connect TiDB/MySQL. | Required; use a dedicated database account | -| `REDIS_URL` | URL to connect Redis. | `redis://localhost:6379/0` | +| `REDIS_URL` | Production requires authenticated TLS. | `rediss://user:@redis.example:6379/0` | | `GITHUB_ACCESS_TOKENS` | Personal access token of GitHub account. | | If you need to see the complete env file configuration instructions, please see the schema definition on the [./src/env.ts](./src/env.ts) file. @@ -49,6 +49,13 @@ npm run dev Open [http://localhost:3450](http://localhost:3450) to view it in the browser. +The API in production and the standalone Explorer worker require `rediss://` and a +password. The hostname must match the server certificate. If Redis uses a private +CA, set `NODE_EXTRA_CA_CERTS` to its PEM file before starting Node. Migrate the +Redis listener and provision the client credential before rolling out these +services. The API accepts a local `redis://` development or test configuration +when `NODE_ENV` is explicitly set to `development` or `test`. + ## Security boundaries Public named queries use the reviewed analytics catalog in `@ossinsight/types`. diff --git a/packages/api-server/__tests__/security/queue-worker.test.ts b/packages/api-server/__tests__/security/queue-worker.test.ts index 3ad944fd9d..ef582b7973 100644 --- a/packages/api-server/__tests__/security/queue-worker.test.ts +++ b/packages/api-server/__tests__/security/queue-worker.test.ts @@ -89,7 +89,7 @@ test('SQL services cannot leak message arguments, driver objects or child bindin const env = {DATABASE_URL: 'mysql://metadata:test@database.example/analytics', PLAYGROUND_DATABASE_URL: 'mysql://reader:test@database.example/analytics', - REDIS_URL: 'redis://:test@127.0.0.1:6379'}; + REDIS_URL: 'rediss://:fixture@redis.example:6379'}; test('worker connections enforce production TLS, bounded pools and separate analytics credentials', () => { const config = workerConfig(env); diff --git a/packages/api-server/__tests__/security/redis-connection.test.ts b/packages/api-server/__tests__/security/redis-connection.test.ts new file mode 100644 index 0000000000..c1af0e62eb --- /dev/null +++ b/packages/api-server/__tests__/security/redis-connection.test.ts @@ -0,0 +1,44 @@ +import Fastify from 'fastify'; +import fp from 'fastify-plugin'; +import Redis from 'ioredis'; +import redisPlugin from '../../src/plugins/redis'; +import {redisConnection} from '../../src/utils/redis-connection'; + +test('the driver and queue duplicates retain verified TLS and the selected database', () => { + const options = redisConnection('rediss://queue:fixture%3Apass@cache.example:6380/2', false); + const client = new Redis({...options, lazyConnect: true}); + const copy = client.duplicate(); + try { + for (const connection of [client, copy]) { + expect(connection.options).toMatchObject({host: 'cache.example', port: 6380, db: 2, + username: 'queue', password: 'fixture:pass', tls: {servername: 'cache.example', rejectUnauthorized: true}}); + } + } finally { copy.disconnect(); client.disconnect(); } +}); + +test.each(['redis://:fixture@cache.example/0', 'rediss://cache.example/0', + 'rediss://:fixture@cache.example/2?tls=false', 'rediss://:fixture@cache.example/invalid', + 'rediss://:fixture@cache.example:65536/0', 'http://cache.example'])( + 'production rejects unsupported Redis configurations without including credentials in errors', url => { + expect(() => redisConnection(url, false)).toThrow(/^Invalid Redis connection configuration\.$/); + }); + +test('explicit development mode permits the local test store', () => { + expect(redisConnection('redis://127.0.0.1:6379/0', true)).toEqual({host: '127.0.0.1', port: 6379, db: 0}); +}); + +test('the production API rejects plaintext configuration before connecting', async () => { + const saved = process.env.NODE_ENV; + const app = Fastify(); + try { + process.env.NODE_ENV = 'production'; + const config = {REDIS_URL: 'redis://:fixture@cache.example/0'}; + app.decorate('config', config); + await app.register(fp(async () => {}, {name: '@fastify/env'})); + await expect(app.register(redisPlugin)).rejects.toThrow('Invalid Redis connection configuration.'); + } finally { + if (saved === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = saved; + await app.close(); + } +}); diff --git a/packages/api-server/src/plugins/redis.ts b/packages/api-server/src/plugins/redis.ts index 29bb84f303..fcd761019d 100644 --- a/packages/api-server/src/plugins/redis.ts +++ b/packages/api-server/src/plugins/redis.ts @@ -1,9 +1,11 @@ import fp from "fastify-plugin"; import fastifyRedis from "@fastify/redis"; +import {redisConnection} from "../utils/redis-connection"; export default fp(async (app) => { app.register(fastifyRedis, { - url: app.config.REDIS_URL, connectTimeout: 5000, commandTimeout: 5000, + ...redisConnection(app.config.REDIS_URL, process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development'), + connectTimeout: 5000, commandTimeout: 5000, maxRetriesPerRequest: 1, enableOfflineQueue: false, }); }, { diff --git a/packages/api-server/src/utils/redis-connection.ts b/packages/api-server/src/utils/redis-connection.ts new file mode 100644 index 0000000000..c5c266a9aa --- /dev/null +++ b/packages/api-server/src/utils/redis-connection.ts @@ -0,0 +1,26 @@ +import {isIP} from 'node:net'; +import type {RedisOptions} from 'ioredis'; + +export function redisConnection(raw: string, allowPlaintext: boolean): RedisOptions { + // Driver options are constructed here. Query parameters cannot change the + // TLS policy or redirect the connection to another transport. + try { + const url = new URL(raw); + const secure = url.protocol === 'rediss:'; + const host = url.hostname.replace(/^\[|\]$/g, ''); + const port = url.port ? Number(url.port) : 6379; + const db = Number(url.pathname.slice(1)); + if ((!secure && !(allowPlaintext && url.protocol === 'redis:')) || + !host || (secure && !url.password) || url.search || url.hash || + !/^\/?(?:0|[1-9]\d*)?$/.test(url.pathname) || !Number.isSafeInteger(db) || + !Number.isInteger(port) || port < 1 || port > 65535) throw new Error(); + return { + host, port, db, + ...(url.username && {username: decodeURIComponent(url.username)}), + ...(url.password && {password: decodeURIComponent(url.password)}), + ...(secure && {tls: {rejectUnauthorized: true, ...(isIP(host) ? {} : {servername: host})}}), + }; + } catch { + throw new Error('Invalid Redis connection configuration.'); + } +} diff --git a/packages/api-server/src/worker/config.ts b/packages/api-server/src/worker/config.ts index 4c3c7ba902..fececa4d0a 100644 --- a/packages/api-server/src/worker/config.ts +++ b/packages/api-server/src/worker/config.ts @@ -1,4 +1,5 @@ import {secureDatabaseURL} from '@ossinsight/types'; +import {redisConnection} from '../utils/redis-connection'; import {completeDatabaseURL} from '../utils/db'; export function workerConfig(env: NodeJS.ProcessEnv) { @@ -18,11 +19,7 @@ export function workerConfig(env: NodeJS.ProcessEnv) { url.searchParams.set('multipleStatements', 'false'); return url.toString(); } - let redis: URL; - try { redis = new URL(env.REDIS_URL || ''); } catch { throw new Error('Redis configuration required.'); } - if (!['redis:', 'rediss:'].includes(redis.protocol) || !redis.hostname || !redis.password || - redis.search || redis.hash) throw new Error('Authenticated Redis configuration required.'); // Never fall back from the analytics account to the metadata writer account. return {high, low, timeout, database: database('DATABASE_URL'), - playground: database('PLAYGROUND_DATABASE_URL'), redis: redis.toString()}; + playground: database('PLAYGROUND_DATABASE_URL'), redis: redisConnection(env.REDIS_URL || '', false)}; } diff --git a/packages/api-server/src/worker/main.ts b/packages/api-server/src/worker/main.ts index 9c725b99c8..e1b640f19f 100644 --- a/packages/api-server/src/worker/main.ts +++ b/packages/api-server/src/worker/main.ts @@ -25,7 +25,7 @@ export async function main(checkOnly = false) { OPERATIONS_TOKEN_PREVIOUS: process.env.OPERATIONS_TOKEN_PREVIOUS, OPERATIONS_TOKEN_PREVIOUS_EXPIRES_AT: process.env.OPERATIONS_TOKEN_PREVIOUS_EXPIRES_AT, })); - const redis = new Redis(config.redis, {lazyConnect: true, maxRetriesPerRequest: null, + const redis = new Redis({...config.redis, lazyConnect: true, maxRetriesPerRequest: null, connectTimeout: 10000, enableOfflineQueue: false}); redis.on('error', () => log.error({event: 'worker_lifecycle', outcome: 'failed'})); let closing: Promise | undefined;