Skip to content
Open
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
28 changes: 24 additions & 4 deletions ops/container-security/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, [],
Expand All @@ -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)
Expand Down
11 changes: 9 additions & 2 deletions packages/api-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<password>@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.
Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion packages/api-server/__tests__/helpers/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
44 changes: 44 additions & 0 deletions packages/api-server/__tests__/security/redis-connection.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof config>('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();
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
3 changes: 3 additions & 0 deletions packages/api-server/src/plugins/auth/auth0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 3 additions & 1 deletion packages/api-server/src/plugins/redis.ts
Original file line number Diff line number Diff line change
@@ -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,
});
}, {
Expand Down
26 changes: 26 additions & 0 deletions packages/api-server/src/utils/redis-connection.ts
Original file line number Diff line number Diff line change
@@ -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.');
}
}
7 changes: 2 additions & 5 deletions packages/api-server/src/worker/config.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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)};
}
2 changes: 1 addition & 1 deletion packages/api-server/src/worker/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> | undefined;
Expand Down
Loading