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
6 changes: 5 additions & 1 deletion ops/container-security/api-probe.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ const sqlite = require('/app/packages/api-server/node_modules/sqlite3');
assert(ready, 'API failed to become ready');
for (const path of ['/metrics', '/docs/json']) {
assert.equal((await fetch(base + path, {signal: AbortSignal.timeout(5000)})).status, 401);
assert.equal((await fetch(base + path, {signal: AbortSignal.timeout(5000), headers: {authorization: 'Bearer ' + process.env.OPERATIONS_TOKEN}})).status, 200);
const schema = 'synthetic-local-schema-reader-32-characters';
const token = path === '/metrics' ? process.env.OPERATIONS_TOKEN : schema;
const other = path === '/metrics' ? schema : process.env.OPERATIONS_TOKEN;
assert.equal((await fetch(base + path, {signal: AbortSignal.timeout(5000), headers: {authorization: 'Bearer ' + token}})).status, 200);
assert.equal((await fetch(base + path, {signal: AbortSignal.timeout(5000), headers: {authorization: 'Bearer ' + other}})).status, 401);
}
assert.equal((await fetch(base + '/explorer/answer', {method: 'POST', signal: AbortSignal.timeout(5000)})).status, 401);
const missing = await fetch(base + '/container-security-not-found', {signal: AbortSignal.timeout(5000)});
Expand Down
12 changes: 10 additions & 2 deletions ops/container-security/check.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!/usr/bin/env python3
"""Run image and TLS checks against disposable, isolated Docker fixtures."""
import argparse
from datetime import datetime, timedelta, timezone
from hashlib import sha256
import json
import os
from pathlib import Path
Expand Down Expand Up @@ -117,8 +119,14 @@ 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', 'OPERATIONS_TOKEN=synthetic-local-operations-token-32-characters'])
'-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',
'-e', 'OPERATIONS_GRANTS=' + json.dumps([
{'holder': holder, 'scope': scope, 'sha256': sha256(token.encode()).hexdigest(),
'expiresAt': (datetime.now(timezone.utc) + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M:%SZ')}
for holder, scope, token in [('monitor', 'metrics:read', 'synthetic-local-operations-token-32-characters'),
('docs', 'schema:read', 'synthetic-local-schema-reader-32-characters')]
])])
run(['docker', 'start', api])
print(run(['docker', 'exec', api, 'node', '/fixtures/api-probe.cjs'], timeout=60).strip(), flush=True)
healthcheck = json.loads(run(['docker', 'inspect', '--format', '{{json .Config.Healthcheck.Test}}', api]))
Expand Down
66 changes: 32 additions & 34 deletions ops/operator-access/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ route and nested plugin. It does not infer privileges from a URL spelling.
The public quota recognizes this metadata but independently verifies the
operator token before exempting a request. An unauthenticated caller cannot
consume operational results or bypass the public quota by naming a new path.
Successful authentication supplies the existing operator fingerprint to the
Successful authentication supplies the grant holder and credential fingerprint to the
request audit log. Missing operator configuration fails closed with 503.

Prometheus instrumentation remains registered in the parent application so it
Expand All @@ -31,37 +31,35 @@ The legacy `sys_users.role` column is profile metadata. Explorer publishing chec

## Credentials and rotation

API, prefetch and worker processes each read their own `OPERATIONS_TOKEN`.
Pipeline reads `PIPELINE_OPERATOR_TOKEN`. These variable names are a schema,
not a reason to share the values. Generate a separate random secret of at least
32 bytes for each service/instance. API `/metrics` and `/docs/json`, prefetch
metrics and worker metrics are read-only; pipeline credentials can trigger
work and must never be distributed to a monitoring-only client.

The existing single-token configuration remains supported. For a planned
rotation, configure the new value as the current token, and optionally set:

| Process | Previous value | Absolute deadline |
| --- | --- | --- |
| API / prefetch / worker | `OPERATIONS_TOKEN_PREVIOUS` | `OPERATIONS_TOKEN_PREVIOUS_EXPIRES_AT` |
| Pipeline | `PIPELINE_OPERATOR_TOKEN_PREVIOUS` | `PIPELINE_OPERATOR_TOKEN_PREVIOUS_EXPIRES_AT` |

The deadline must be canonical UTC (`YYYY-MM-DDTHH:mm:ssZ` or with exactly
three fractional digits), at most 24 hours after process startup. Prefer a
short window sized for the rollout. Both values must be distinct, at least
32 bytes, no more than 256 characters, and contain no whitespace/control
characters. Missing, malformed or overly long overlap settings fail closed
with 503. An already-expired previous slot is valid configuration but cannot
authenticate; the current token continues to work. Authentication compares
fixed-size hashes in constant time and identifies only the matching key's
short fingerprint in existing request audit records.

Each process captures the configuration once at startup and checks the old
deadline on every request. Expiry requires no restart; restarting with the
same absolute deadline cannot renew it. Once the running process observes
expiry, a backward clock adjustment cannot revive the old value. Removing
the previous slot and restarting revokes it immediately. Keep host time
synchronized; expiration depends on the host clock.
The API, worker and prefetch processes read their own `OPERATIONS_GRANTS`.
Pipeline reads `PIPELINE_OPERATOR_GRANTS`. Set these variables to JSON arrays.
Each entry has a holder (a service or individual identifier), one scope, the lowercase
SHA-256 digest of a secret bearer token and an absolute UTC expiration. Supply only
the grants needed by that process. Generate a separate high-entropy bearer token
of at least 32 random bytes for each holder, service and capability. The caller
keeps the token in its secret store and sends it over HTTPS. The server needs its
digest. For example, the following shows the configuration shape with placeholders:

```json
[{"holder":"monitoring","scope":"metrics:read","sha256":"<64 lowercase hex digits>","expiresAt":"<UTC timestamp>"}]
```

| Capability | Consumers |
| --- | --- |
| `metrics:read` | API, worker or prefetch metrics scraper |
| `schema:read` | API client reading the private schema at `/docs/json` |
| `pipeline:backfill` | Pipeline client submitting a warehouse backfill |

A configured policy is authoritative. Malformed entries or duplicate digests
disable access. Each process reads its policy at startup and checks expiration
on each request. Overlap independently expiring grants for the same holder during
rotation. Removing a grant and restarting the process revokes it immediately.

**Migration.** Provision grants and the corresponding client secrets before deploying.
Without a grants policy the former API, worker and prefetch tokens authorize only
metrics. Their existing current/previous rotation and 24-hour maximum overlap still
apply. Schema access and pipeline backfills require their named grants. The old
`PIPELINE_OPERATOR_TOKEN` alone cannot start work. Keep host clocks synchronized.

### Planned change

Expand All @@ -76,7 +74,7 @@ synchronized; expiration depends on the host clock.
Do not place values in shell arguments, CI logs, tickets or this document.
Use existing secret-management infrastructure when available; a new
service and new cloud permissions are not prerequisites for this change.
3. Set new/current plus old/previous with a short absolute deadline. Replace
3. Publish the new grant and give the previous one a short absolute deadline. Replace
runtime files atomically and restart each service with its new environment.
Drain API upstreams one at a time; pause and drain worker queues and restore
their prior paused states; wait until prefetch is idle and pipeline has no
Expand All @@ -85,7 +83,7 @@ synchronized; expiration depends on the host clock.
files atomically, keeping their current owner and restrictive mode. Reload
Prometheus and wait for fresh successful scrapes. Check API health, public
behavior, pipeline health and worker readiness as applicable.
5. Remove the previous slot from the environment and PM2 configuration, then
5. Remove the previous grant from the environment and PM2 configuration, then
restart using the same controlled procedure. Verify old=401, new=200,
anonymous=401 and cross-service tokens=401. Confirm fresh monitoring data
and restore all upstreams/queue states. Record fingerprints, timestamps,
Expand Down
18 changes: 8 additions & 10 deletions packages/api-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,18 +141,16 @@ tables. Prefetch-only queries still require an existing shared result.

### Operations access and audit records

Set a private `OPERATIONS_TOKEN` (32–256 characters with at least 32 random bytes)
for the API and prefetch deployments, and configure the Prometheus scraper to send
`Authorization: Bearer <token>`. `/metrics` and `/docs/json` deny unauthenticated
requests; an unconfigured token disables these endpoints with 503. Health checks
remain available. The prefetch metrics listener defaults to `127.0.0.1`; changing
`METRICS_HOST` does not remove token authentication. Apply scraper configuration
before deploying these endpoint restrictions to avoid a monitoring gap.
Configure a `metrics:read` grant for each scraper and a separate `schema:read`
grant for private schema readers. Provision them before deploying. See the
[operator grants and migration guide](../../ops/operator-access/README.md).
The prefetch metrics listener defaults to `127.0.0.1` and requires a bearer token.
The public health check remains available.

API audit records include request ID, verified actor, route pattern, concrete resource, source IP,
status and duration. Auth0 principals are recorded only after JWT verification;
privileged operations additionally resolve the stored user ID. Operator access
records a token fingerprint. Reviewed public query names and validated resource
records the named grant holder and a token fingerprint. Reviewed public query names and validated resource
IDs identify the accessed resource. Numeric/enum query parameters are allowlisted;
duplicate, invalid, unknown and free-text parameters are omitted and counted.
These records omit tokens, bodies and raw URLs/querystrings. Unknown query names
Expand Down Expand Up @@ -219,7 +217,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 Expand Up @@ -268,7 +266,7 @@ The API still produces the two `explorer_*_concurrent_queue` queues. Run their
consumer from this package using Node 24 LTS and `pnpm worker`; old deployments
may have a `packages/job-server` checkout that is no longer in this repository.
The new worker needs only `DATABASE_URL`, `PLAYGROUND_DATABASE_URL`, `REDIS_URL`
and `OPERATIONS_TOKEN` in its private `.env.worker` (separate from the API’s `.env`). It does not need an OpenAI key,
and `OPERATIONS_GRANTS` for metrics in its private `.env.worker` (separate from the API’s `.env`). It does not need an OpenAI key,
GitHub tokens, Auth0 secrets or Data Service keys, and cannot generate prompts.

Use a metadata account with access to the Explorer records and a separate
Expand Down
16 changes: 13 additions & 3 deletions packages/api-server/__tests__/core/app-startup.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {grant} from '../helpers/operator-grants';
import {spawn} from 'node:child_process';
import {once} from 'node:events';
import {createServer} from 'node:net';
Expand All @@ -13,6 +14,8 @@ type Rotation = 'current-only' | 'overlap' | 'expired';
const token = 'synthetic-local-operations-token-32-characters';
const previous = 'synthetic-previous-operations-token-32-characters';

const schemaToken = 'synthetic-local-schema-reader-32-characters';

async function withRunningAPI(mode: Rotation, check: (base: string, db: TiDBDatabase) => Promise<void>) {
const db = await bootstrapTestDatabase();
const redis = await bootstrapTestRedis();
Expand All @@ -21,6 +24,10 @@ async function withRunningAPI(mode: Rotation, check: (base: string, db: TiDBData
await once(reservation, 'listening');
const port = (reservation.address() as AddressInfo).port;
await new Promise<void>((done, reject) => reservation.close(error => error ? reject(error) : done()));
const grants = [grant(token, 'metrics:read', 'monitor'), grant(schemaToken, 'schema:read', 'docs')];
if (mode !== 'current-only') {
grants.push(grant(previous, 'metrics:read', 'monitor', new Date(Date.now() + (mode === 'overlap' ? 60000 : -1000)).toISOString()));
}
const rotation = mode === 'current-only' ? {} : {OPERATIONS_TOKEN_PREVIOUS: previous,
OPERATIONS_TOKEN_PREVIOUS_EXPIRES_AT: new Date(Date.now() + (mode === 'overlap' ? 60000 : -1000)).toISOString()};
const child = spawn(process.execPath, [require.resolve('fastify-cli/cli.js'), 'start', '--options',
Expand All @@ -30,7 +37,7 @@ async function withRunningAPI(mode: Rotation, check: (base: string, db: TiDBData
DATABASE_URL: db.url(), PLAYGROUND_DATABASE_URL: db.analyticsUrl(), REDIS_URL: redis.url(),
GITHUB_ACCESS_TOKENS: '', OPENAI_API_KEY: 'synthetic-test-key', AUTH0_SECRET: secret,
AUTH0_AUDIENCE: audience, AUTH0_DOMAIN: issuer,
OPERATIONS_TOKEN: token, ...rotation},
OPERATIONS_TOKEN: token, OPERATIONS_GRANTS: JSON.stringify(grants), ...rotation},
stdio: ['ignore', 'pipe', 'pipe'],
});
const exited = once(child, 'exit');
Expand Down Expand Up @@ -62,9 +69,12 @@ test.each(['current-only', 'overlap', 'expired'] as const)('the production CLI b
await withRunningAPI(mode, async base => {
for (const path of ['/metrics', '/docs/json']) {
expect((await fetch(base + path)).status).toBe(401);
expect((await fetch(base + path, {headers: {authorization: `Bearer ${token}`}})).status).toBe(200);
const authorized = path === '/metrics' ? token : schemaToken;
const other = path === '/metrics' ? schemaToken : token;
expect((await fetch(base + path, {headers: {authorization: `Bearer ${authorized}`}})).status).toBe(200);
expect((await fetch(base + path, {headers: {authorization: `Bearer ${other}`}})).status).toBe(401);
const old = await fetch(base + path, {headers: {authorization: `Bearer ${previous}`}});
expect(old.status).toBe(mode === 'overlap' ? 200 : 401);
expect(old.status).toBe(path === '/metrics' && mode === 'overlap' ? 200 : 401);
expect(old.headers.get('cache-control')).toBe('no-store');
}
expect((await fetch(base + '/explorer/answer', {method: 'POST'})).status).toBe(401);
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
6 changes: 6 additions & 0 deletions packages/api-server/__tests__/helpers/operator-grants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {createHash} from 'node:crypto';
import type {OperatorCapability} from '@ossinsight/types/dist/operator-token';

export function grant(token: string, scope: OperatorCapability, holder: string, expiresAt = new Date(Date.now() + 60000).toISOString()) {
return {holder, scope, sha256: createHash('sha256').update(token).digest('hex'), expiresAt};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import Fastify from 'fastify';
import {createCapabilityVerifier, OperatorCapability} from '@ossinsight/types/dist/operator-token';
import {grant} from '../helpers/operator-grants';
import {registerOperatorAuth} from '../../../pipeline/src/utils/operator-auth';

const monitor = 'fixture-monitor-reader-with-more-than-32-bytes';
const schema = 'fixture-schema-reader-with-more-than-32-bytes';
const scheduler = 'fixture-backfill-writer-with-more-than-32-bytes';
const start = Date.parse('2030-03-01T12:00:00Z');
const expiry = new Date(start + 60000).toISOString();
const entries = [
grant(monitor, 'metrics:read', 'prometheus', expiry),
grant(schema, 'schema:read', 'catalog', expiry),
grant(scheduler, 'pipeline:backfill', 'warehouse', expiry),
];

test.each(['metrics:read', 'schema:read', 'pipeline:backfill'] as OperatorCapability[])('each grant authorizes exactly its capability: %s', scope => {
let clock = start;
const verify = createCapabilityVerifier({grants: JSON.stringify(entries)}, scope, () => clock);
for (const [index, token] of [monitor, schema, scheduler].entries()) {
const result = verify('Bearer ' + token);
expect(result.status).toBe(scope === entries[index].scope ? 'accepted' : 'rejected');
if (result.status === 'accepted') expect(result).toMatchObject({holder: entries[index].holder});
}
clock += 60000;
for (const token of [monitor, schema, scheduler]) expect(verify('Bearer ' + token).status).toBe('rejected');
clock = start;
expect(verify('Bearer ' + monitor).status).toBe('rejected');
});

test('malformed policies and credential reuse cannot fall back to a shared secret', () => {
for (const grants of ['broken', '{}', '[]', JSON.stringify([entries[0], {...entries[0], scope: 'schema:read'}]),
JSON.stringify([{...entries[1], sha256: entries[0].sha256}]), JSON.stringify([{...entries[1], expiresAt: '2030-02-30T00:00:00Z'}]),
JSON.stringify([{...entries[1], scope: 'all'}]), JSON.stringify([{...entries[1], holder: 'log\nentry'}])]) {
const verify = createCapabilityVerifier({current: monitor, grants}, 'schema:read', () => start);
expect(verify('Bearer ' + monitor).status).toBe('unconfigured');
}
expect(createCapabilityVerifier({current: monitor}, 'metrics:read')('Bearer ' + monitor).status).toBe('accepted');
for (const scope of ['schema:read', 'pipeline:backfill'] as const) {
expect(createCapabilityVerifier({current: monitor}, scope)('Bearer ' + monitor).status).toBe('unconfigured');
}
});

test('pipeline grants are checked before handlers and unassigned routes fail closed', async () => {
const app = Fastify();
const execute = jest.fn(async request => ({actor: request.operatorActor}));
registerOperatorAuth(app, {grants: JSON.stringify([
grant(schema, 'schema:read', 'catalog'), grant(scheduler, 'pipeline:backfill', 'warehouse'),
])});
app.post('/run', {config: {pipelineCapability: 'pipeline:backfill'}}, execute);
app.post('/unassigned', execute);
try {
expect((await app.inject({method: 'POST', url: '/run', headers: {authorization: 'Bearer ' + schema}})).statusCode).toBe(401);
expect((await app.inject({method: 'POST', url: '/unassigned', headers: {authorization: 'Bearer ' + scheduler}})).statusCode).toBe(403);
expect(execute).not.toHaveBeenCalled();
const result = await app.inject({method: 'POST', url: '/run', headers: {authorization: 'Bearer ' + scheduler}});
expect(result.statusCode).toBe(200);
expect(result.json().actor).toMatch(/^pipeline-operator:warehouse:[a-f0-9]{12}$/);
expect(execute).toHaveBeenCalledTimes(1);
} finally {await app.close();}
});
Loading
Loading