diff --git a/ops/container-security/check.py b/ops/container-security/check.py index f301b83fd6..ff93792028 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,8 +136,8 @@ 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', 'OPENAI_API_KEY=synthetic-test-key', '-e', 'AUTH0_SECRET=synthetic-local-hmac-secret', + '-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-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 8333a24dd1..639c1eb862 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`. @@ -219,7 +226,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__/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/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/__tests__/security/runtime-upgrade.test.ts b/packages/api-server/__tests__/security/runtime-upgrade.test.ts index fcdc8afd53..860dc666ec 100644 --- a/packages/api-server/__tests__/security/runtime-upgrade.test.ts +++ b/packages/api-server/__tests__/security/runtime-upgrade.test.ts @@ -70,6 +70,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 5a7c7e507a..cbcfc43616 100644 --- a/packages/api-server/src/plugins/auth/auth0.ts +++ b/packages/api-server/src/plugins/auth/auth0.ts @@ -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/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;