Files
claude-mem/tests/server/auth-api-key.test.ts
Alex Newman 36b0929fae Server-beta: Postgres storage + independent runtime + BullMQ queue (Phases 1–3) (#2351)
* Add server beta runtime foundation

* Address server beta review findings

* Resolve server beta review comments

* Tighten server beta review follow-ups

* Harden server beta auth and search

* Avoid unnecessary FTS rebuilds

* Block scoped keys from creating projects

* Release BullMQ claims best effort on close

* Address server beta review blockers

* Reset BullMQ claims best effort

* Add Postgres observation storage foundation

* feat(server-beta): add independent runtime service

Introduce src/server/runtime/ as a self-contained server-beta runtime
that owns its lifecycle, Postgres bootstrap, and HTTP boundary without
depending on WorkerService.

ServerBetaService wraps the existing Server class, exposes
/healthz and /v1/info with runtime="server-beta", and persists state
to dedicated paths (.server-beta.pid|.port|.runtime.json). The four
boundary managers (queue, generation worker, provider registry, event
broadcaster) are intentionally disabled in this phase and report their
status through /v1/info; later phases activate them.

Adds plans/2026-05-07-finish-bullmq-branch-ship-plan.md to track the
remaining work for this branch.

Phase 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): route CLI lifecycle and bundle separate runtime

scripts/build-hooks.js now produces plugin/scripts/server-beta-service.cjs
as a separate Node CJS bundle, alongside the existing worker-service
bundle. The server-beta runtime is now installable independently.

src/npx-cli/commands/server.ts routes start|stop|restart|status to the
server-beta lifecycle instead of the legacy worker. The worker keeps its
own start|stop|restart|status under the worker namespace; the two
runtimes can be operated independently.

src/services/worker-service.ts adds a server-* command parser branch
that delegates to the sibling server-beta-service.cjs bundle so
direct worker-service invocations still route to the right runtime.

tests/npx-cli-server-namespace.test.ts updated to expect server-beta
lifecycle routing.

Includes rebuilt plugin/scripts/*.cjs bundles produced by
build-and-sync.

Phase 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): add BullMQ job queue primitives

Introduce src/server/jobs/ as the queue-side primitives that Phase 3 of
the server-beta runtime needs to operate.

types.ts defines a discriminated union over the four job kinds (event,
event-batch, summary, reindex) and maps each to a per-kind BullMQ queue
name and deterministic-ID prefix.

job-id.ts builds deterministic, colon-free BullMQ jobIds from
(kind, team, project, source). The colon ban exists because BullMQ uses
':' as a Redis key separator internally; embedding ':' in jobIds
breaks scan and state lookups.

ServerJobQueue.ts is a thin wrapper over BullMQ Queue + Worker that
enforces autorun:false, default concurrency 1, and an attached error
listener — all per BullMQ docs requirements. Test seams accept queue
and worker factories so unit tests do not need Redis.

outbox.ts publishes through the Postgres ObservationGenerationJob
repository as canonical history. enqueueOutbox writes the row first,
then publishes to BullMQ; if BullMQ throws, the row is transitioned to
failed and a failed event is appended. reconcileOnStartup re-enqueues
queued + processing rows after a restart, replacing terminal BullMQ
jobs that may still be holding the deterministic ID slot. markCompleted
and markFailed wrap transitionStatus and append the matching event row.

Includes 20 unit tests covering deterministic ID stability, colon-free
output, queue lifecycle, error-listener attachment, double-start
refusal, idempotent enqueue, BullMQ failure rollback, startup
reconciliation, max-attempts skipping, and completion / failure /
retry transitions.

Phase 3 commit 1 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): activate queue boundary in runtime service

Wire ActiveServerBetaQueueManager into the server-beta runtime graph.
The active manager owns one ServerJobQueue per generation kind (event,
event-batch, summary, reindex) and surfaces lane metadata through
boundary health.

Selection is opt-in and fail-fast: if CLAUDE_MEM_QUEUE_ENGINE is set to
bullmq the active manager is constructed (and any Redis/config error
throws — no silent fallback to SQLite, per Phase 3 anti-pattern guard).
For any other engine the disabled boundary remains so worker-era and
test setups stay compatible.

Widens ServerBetaBoundaryHealth.status to a discriminated union
('disabled' | 'active' | 'errored') with optional details. The disabled
adapter still emits status='disabled', which keeps the existing
server-beta-service test green.

ServerBetaService receives the manager through a new optional
queueManager field on CreateServerBetaServiceOptions so test graphs
and Phase 4 wiring can inject custom managers.

Adds tests/server/runtime/active-queue-manager.test.ts covering bullmq
guard, active health shape, per-kind queue access, close behavior, and
post-close errored health.

Phase 3 commit 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(server-beta): cap /v1/events/batch at 500 events

Prevents unbounded array DoS surface flagged in PR review.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 01:20:07 -07:00

225 lines
6.7 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { Database } from 'bun:sqlite';
import {
createServerApiKey,
hashServerApiKey,
revokeServerApiKey,
verifyServerApiKey,
} from '../../src/server/auth/api-key-service.js';
import { requireServerAuth } from '../../src/server/middleware/auth.js';
import { ProjectsRepository, TeamsRepository } from '../../src/storage/sqlite/index.js';
describe('server API key auth', () => {
let db: Database;
beforeEach(() => {
db = new Database(':memory:');
db.run('PRAGMA foreign_keys = ON');
});
afterEach(() => {
db.close();
});
it('creates raw keys once while storing only a hash', () => {
const created = createServerApiKey(db, {
name: 'Team key',
teamId: null,
projectId: null,
scopes: ['memories:read'],
});
expect(created.rawKey).toStartWith('cmem_');
expect(created.record.keyHash).toBe(hashServerApiKey(created.rawKey));
expect(created.record.keyHash).not.toContain(created.rawKey);
expect(created.record.prefix).toBe(created.rawKey.slice(0, 10));
});
it('verifies required scopes and rejects revoked keys', () => {
const created = createServerApiKey(db, {
name: 'Scoped key',
scopes: ['memories:read'],
});
expect(verifyServerApiKey(db, created.rawKey, ['memories:read'])?.record.id).toBe(created.record.id);
expect(verifyServerApiKey(db, created.rawKey, ['memories:write'])).toBeNull();
revokeServerApiKey(db, created.record.id);
expect(verifyServerApiKey(db, created.rawKey, ['memories:read'])).toBeNull();
});
it('middleware allows localhost local-dev without a bearer token', () => {
const middleware = requireServerAuth(() => db, { authMode: 'local-dev', allowLocalDevBypass: true });
const req: any = {
ip: '127.0.0.1',
socket: {},
header: (name: string) => name.toLowerCase() === 'host' ? '127.0.0.1:37777' : undefined,
};
const res: any = {
status: () => res,
json: () => {},
};
let calledNext = false;
middleware(req, res, () => {
calledNext = true;
});
expect(calledNext).toBe(true);
expect(req.authContext).toMatchObject({ mode: 'local-dev', scopes: ['local-dev'] });
});
it('middleware requires explicit opt-in before local-dev bypass is honored', () => {
const middleware = requireServerAuth(() => db, { authMode: 'local-dev' });
const req: any = {
ip: '127.0.0.1',
socket: { remoteAddress: '127.0.0.1' },
header: (name: string) => name.toLowerCase() === 'host' ? 'localhost:37777' : undefined,
};
const res: any = {
statusCode: 200,
status(code: number) {
this.statusCode = code;
return this;
},
json: () => {},
};
let calledNext = false;
middleware(req, res, () => {
calledNext = true;
});
expect(calledNext).toBe(false);
expect(res.statusCode).toBe(401);
});
it('middleware blocks local-dev bypass when forwarded proxy headers are present', () => {
const middleware = requireServerAuth(() => db, { authMode: 'local-dev', allowLocalDevBypass: true });
const req: any = {
ip: '127.0.0.1',
socket: { remoteAddress: '127.0.0.1' },
header: (name: string) => {
const normalized = name.toLowerCase();
if (normalized === 'host') return 'claude-mem.example.com';
if (normalized === 'x-forwarded-for') return '203.0.113.10';
return undefined;
},
};
const res: any = {
statusCode: 200,
status(code: number) {
this.statusCode = code;
return this;
},
json: () => {},
};
let calledNext = false;
middleware(req, res, () => {
calledNext = true;
});
expect(calledNext).toBe(false);
expect(res.statusCode).toBe(401);
});
it('middleware accepts bracketed IPv6 loopback host headers in explicit local-dev mode', () => {
const middleware = requireServerAuth(() => db, { authMode: 'local-dev', allowLocalDevBypass: true });
const req: any = {
ip: '::1',
socket: { remoteAddress: '::1' },
header: (name: string) => name.toLowerCase() === 'host' ? '[::1]:37777' : undefined,
};
const res: any = {
status: () => res,
json: () => {},
};
let calledNext = false;
middleware(req, res, () => {
calledNext = true;
});
expect(calledNext).toBe(true);
expect(req.authContext).toMatchObject({ mode: 'local-dev', scopes: ['local-dev'] });
});
it('middleware defaults to API-key auth when auth mode is not explicitly set', () => {
const originalAuthMode = process.env.CLAUDE_MEM_AUTH_MODE;
delete process.env.CLAUDE_MEM_AUTH_MODE;
try {
const middleware = requireServerAuth(() => db);
const req: any = {
ip: '127.0.0.1',
socket: { remoteAddress: '127.0.0.1' },
header: (name: string) => name.toLowerCase() === 'host' ? 'localhost:37777' : undefined,
};
const res: any = {
statusCode: 200,
body: null,
status(code: number) {
this.statusCode = code;
return this;
},
json(body: unknown) {
this.body = body;
},
};
let calledNext = false;
middleware(req, res, () => {
calledNext = true;
});
expect(calledNext).toBe(false);
expect(res.statusCode).toBe(401);
expect(res.body).toMatchObject({ error: 'Unauthorized' });
} finally {
if (originalAuthMode === undefined) {
delete process.env.CLAUDE_MEM_AUTH_MODE;
} else {
process.env.CLAUDE_MEM_AUTH_MODE = originalAuthMode;
}
}
});
it('middleware requires a scoped bearer API key outside local-dev fallback', () => {
const team = new TeamsRepository(db).create({ name: 'Core' });
const project = new ProjectsRepository(db).create({ name: 'Project' });
const created = createServerApiKey(db, {
name: 'Write key',
teamId: team.id,
projectId: project.id,
scopes: ['memories:write'],
});
const middleware = requireServerAuth(() => db, {
authMode: 'api-key',
requiredScopes: ['memories:write'],
});
const req: any = {
ip: '10.0.0.5',
socket: {},
header: (name: string) => name.toLowerCase() === 'authorization' ? `Bearer ${created.rawKey}` : undefined,
};
const res: any = {
status: () => res,
json: () => {},
};
let calledNext = false;
middleware(req, res, () => {
calledNext = true;
});
expect(calledNext).toBe(true);
expect(req.authContext).toMatchObject({
mode: 'api-key',
apiKeyId: created.record.id,
teamId: team.id,
projectId: project.id,
scopes: ['memories:write'],
});
});
});