Clear remaining M0/M1 bugs on master (T-22, T-25, T-27, T-31, T-35)

This commit is contained in:
Boki 2026-11-27 16:19:09 -05:00
parent 9e259ca43b
commit b20fc28e45
8 changed files with 245 additions and 252 deletions

View file

@ -291,7 +291,22 @@ function isValidIpv6WithZoneId(host: string): boolean {
return parseIpv6Hextets(addr) !== null && VALID_IPV6_ZONE_ID.test(zone);
}
function decodeMongoHost(rawHost: string, isBracketedIpv6 = false): string {
const FORBIDDEN_MONGO_UNIX_SOCKET_CHARS = /[?#@:\\[\],\s]/;
function isUnixDomainSocketHost(decodedHost: string): boolean {
return (
decodedHost.startsWith('/') &&
decodedHost.endsWith('.sock') &&
!hasAsciiControlChar(decodedHost) &&
!FORBIDDEN_MONGO_UNIX_SOCKET_CHARS.test(decodedHost)
);
}
function decodeMongoHost(
rawHost: string,
isBracketedIpv6 = false,
allowUnixSocket = false
): string {
// MongoDB driver 6.22.0 decodes seed hostnames once in HostAddress.fromString during
// URI parsing and a second time when ServerDescription.hostAddress reparses the
// serialized address for ConnectionPool/Monitor. Decode iteratively to a fixed point
@ -324,6 +339,9 @@ function decodeMongoHost(rawHost: string, isBracketedIpv6 = false): string {
if (current.includes('%') && !(isBracketedIpv6 && isValidIpv6WithZoneId(current))) {
throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`);
}
if (!isBracketedIpv6 && allowUnixSocket && isUnixDomainSocketHost(current)) {
return current;
}
const forbiddenChars = isBracketedIpv6
? FORBIDDEN_MONGO_IPV6_HOST_CHARS
: FORBIDDEN_MONGO_HOST_CHARS;
@ -335,7 +353,8 @@ function decodeMongoHost(rawHost: string, isBracketedIpv6 = false): string {
function parseMongoHostPort(
segment: string,
defaultPort: number | undefined
defaultPort: number | undefined,
allowUnixSocket = false
): MongoTargetHost | null {
const trimmed = segment.trim();
if (!trimmed) {
@ -375,10 +394,13 @@ function parseMongoHostPort(
const colonIdx = trimmed.indexOf(':');
if (colonIdx === -1) {
const host = decodeMongoHost(trimmed).trim();
const host = decodeMongoHost(trimmed, false, allowUnixSocket).trim();
if (!host) {
return null;
}
if (allowUnixSocket && isUnixDomainSocketHost(host)) {
return { host, port: undefined };
}
return { host, port: defaultPort };
}
if (trimmed.indexOf(':', colonIdx + 1) !== -1) {
@ -491,8 +513,9 @@ function parseMongoTarget(uri?: string): ParsedMongoTarget {
}
const hosts: MongoTargetHost[] = [];
const allowUnixSocket = scheme === 'mongodb';
for (const segment of hostList.split(',')) {
const parsedHost = parseMongoHostPort(segment, defaultPort);
const parsedHost = parseMongoHostPort(segment, defaultPort, allowUnixSocket);
if (parsedHost) {
hosts.push(parsedHost);
}

View file

@ -114,6 +114,7 @@ function isValidMongoUri(uri: string): boolean {
// Match mongodb-connection-string-url: authority ends at '/' or '?', never '#'
const delimiterMatch = /[/?]/.exec(rest);
const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest;
const remainder = delimiterMatch ? rest.slice(delimiterMatch.index) : '';
if (!authority || authority.includes('#')) {
return false;
}
@ -125,6 +126,11 @@ function isValidMongoUri(uri: string): boolean {
if (firstAtIndex !== -1 && authority.indexOf('@', firstAtIndex + 1) !== -1) {
return false;
}
// Match mongodb-connection-string-url: without userinfo in authority, an unencoded '@'
// later in the path or query is rejected by the MongoDB driver.
if (firstAtIndex === -1 && remainder.includes('@')) {
return false;
}
const hostList = firstAtIndex >= 0 ? authority.slice(firstAtIndex + 1) : authority;
if (!hostList) {

View file

@ -554,6 +554,33 @@ describe('Config Schemas', () => {
});
describe('mongodbConfigSchema', () => {
it('should reject no-credential URIs with unencoded @ after path/query while allowing credentialed URIs (T-31)', () => {
expect(() =>
mongodbConfigSchema.parse({
uri: 'mongodb://localhost:27017/db@foo',
database: 'testdb',
})
).toThrow();
expect(() =>
mongodbConfigSchema.parse({
uri: 'mongodb://localhost:27017/db?appName=a@b',
database: 'testdb',
})
).toThrow();
expect(() =>
mongodbConfigSchema.parse({
uri: 'mongodb://user:pass@localhost:27017/db?appName=a@b',
database: 'testdb',
})
).not.toThrow();
expect(() =>
mongodbConfigSchema.parse({
uri: 'mongodb://prod_user:strong-secret@%2Fvar%2Frun%2Fmongodb%2Fmongod.sock/stock',
database: 'stock',
})
).not.toThrow();
});
it('should accept minimal config', () => {
const config = mongodbConfigSchema.parse({
uri: 'mongodb://localhost:27017',

View file

@ -1,244 +1,129 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { QueueManager } from '../src/queue-manager';
import type { QueueManagerConfig, RedisConfig } from '../src/types';
import type { Queue } from '../src/queue';
import { QueueManager, type QueueManagerDependencies } from '../src/queue-manager';
import type { QueueManagerConfig, QueueWorkerConfig } from '../src/types';
describe.skip('QueueManager', () => {
// Skipping these tests as they require real Redis connection
// TODO: Create mock implementation or use testcontainers
function createOfflineDeps() {
const redisQuit = mock(async () => 'OK');
const redisDisconnect = mock(() => {});
const createdQueues: Array<{
name: string;
workerConfig: QueueWorkerConfig;
close: ReturnType<typeof mock>;
}> = [];
const mockRedisConfig: RedisConfig = {
host: 'localhost',
port: 6379,
const deps: QueueManagerDependencies = {
createRedis: mock(
() =>
({
on: mock(() => {}),
quit: redisQuit,
disconnect: redisDisconnect,
}) as unknown as ReturnType<NonNullable<QueueManagerDependencies['createRedis']>>
),
createQueue: mock(
(
name: string,
_redisConfig: unknown,
_defaultJobOptions: unknown,
workerConfig: QueueWorkerConfig
) => {
const close = mock(async () => {});
const workerCount = workerConfig.startWorker ? (workerConfig.workers ?? 0) : 0;
createdQueues.push({ name, workerConfig, close });
return {
getName: () => name,
getWorkerCount: () => workerCount,
add: mock(async () => ({ id: `job-${name}` })),
close,
} as unknown as Queue;
}
),
};
return { deps, createdQueues, redisQuit, redisDisconnect };
}
function createConfig(overrides: Partial<QueueManagerConfig> = {}): QueueManagerConfig {
return {
redis: {
host: '127.0.0.1',
port: 16379,
db: 15,
},
serviceName: 'test-service',
delayWorkerStart: true,
...overrides,
};
}
describe('QueueManager', () => {
const mockLogger = {
info: mock(() => {}),
error: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
trace: mock(() => {}),
};
fatal: mock(() => {}),
child: mock(() => mockLogger),
} as unknown as ConstructorParameters<typeof QueueManager>[2];
let stubs: ReturnType<typeof createOfflineDeps>;
beforeEach(() => {
stubs = createOfflineDeps();
});
describe('constructor', () => {
it('should create queue manager with default config', () => {
const manager = new QueueManager(mockRedisConfig);
it('creates a QueueManager offline using injected dependencies', async () => {
const manager = new QueueManager(createConfig(), undefined, mockLogger, stubs.deps);
expect(manager).toBeDefined();
expect(manager.getConfig().serviceName).toBe('test-service');
expect(manager.getConfig().delayWorkerStart).toBe(true);
await manager.shutdown();
});
it('should create queue manager with custom config', () => {
const config: QueueManagerConfig = {
defaultJobOptions: {
attempts: 5,
removeOnComplete: 50,
},
enableMetrics: true,
enableScheduler: true,
};
const manager = new QueueManager(mockRedisConfig, config, mockLogger);
expect(manager).toBeDefined();
it('forces Redis DB 0 when serviceName is configured for cross-service queues', async () => {
const manager = new QueueManager(
createConfig({ serviceName: 'orchestrator', redis: { host: '127.0.0.1', port: 16379, db: 7 } }),
undefined,
mockLogger,
stubs.deps
);
expect(manager.getConfig().redis.db).toBe(0);
await manager.shutdown();
});
});
describe('queue operations', () => {
let manager: QueueManager;
it('creates, deduplicates, and lists queues without connecting to QA Dragonfly', async () => {
const manager = new QueueManager(createConfig(), undefined, mockLogger, stubs.deps);
try {
const q1 = manager.getQueue('alpha');
const q2 = manager.getQueue('alpha');
const q3 = manager.getQueue('beta');
beforeEach(() => {
manager = new QueueManager(mockRedisConfig, {}, mockLogger);
});
it('should create or get queue', () => {
const queue = manager.createQueue('test-queue');
expect(queue).toBeDefined();
expect(queue.getName()).toBe('test-queue');
});
it('should return same queue instance', () => {
const queue1 = manager.createQueue('test-queue');
const queue2 = manager.createQueue('test-queue');
expect(queue1).toBe(queue2);
});
it('should create queue with options', () => {
const queue = manager.createQueue('test-queue', {
concurrency: 5,
workers: 2,
});
expect(queue).toBeDefined();
});
it('should get existing queue', () => {
manager.createQueue('test-queue');
const queue = manager.getQueue('test-queue');
expect(queue).toBeDefined();
});
it('should return undefined for non-existent queue', () => {
const queue = manager.getQueue('non-existent');
expect(queue).toBeUndefined();
});
it('should list all queues', () => {
manager.createQueue('queue1');
manager.createQueue('queue2');
const queues = manager.getQueues();
expect(queues).toHaveLength(2);
expect(queues.map(q => q.getName())).toContain('queue1');
expect(queues.map(q => q.getName())).toContain('queue2');
});
it('should check if queue exists', () => {
manager.createQueue('test-queue');
expect(manager.hasQueue('test-queue')).toBe(true);
expect(manager.hasQueue('non-existent')).toBe(false);
});
});
describe('cache operations', () => {
let manager: QueueManager;
beforeEach(() => {
manager = new QueueManager(mockRedisConfig, {}, mockLogger);
});
it('should create cache', () => {
const cache = manager.createCache('test-cache');
expect(cache).toBeDefined();
});
it('should get existing cache', () => {
manager.createCache('test-cache');
const cache = manager.getCache('test-cache');
expect(cache).toBeDefined();
});
it('should return same cache instance', () => {
const cache1 = manager.createCache('test-cache');
const cache2 = manager.createCache('test-cache');
expect(cache1).toBe(cache2);
});
});
describe('service discovery', () => {
let manager: QueueManager;
beforeEach(() => {
manager = new QueueManager(mockRedisConfig, {}, mockLogger);
});
it('should configure service name', () => {
manager.configureService('test-service');
expect((manager as any).serviceName).toBe('test-service');
});
it('should register queue route', () => {
manager.configureService('test-service');
manager.registerQueueRoute({
service: 'remote-service',
handler: 'process',
queueName: '{remote-service_process}',
});
expect(manager.hasRoute('remote-service', 'process')).toBe(true);
});
it('should send to remote queue', async () => {
manager.configureService('test-service');
manager.registerQueueRoute({
service: 'remote-service',
handler: 'process',
queueName: '{remote-service_process}',
});
const jobId = await manager.sendToQueue('remote-service', 'process', { data: 'test' });
expect(jobId).toBeDefined();
});
it('should send to local queue', async () => {
manager.configureService('test-service');
manager.createQueue('{test-service_process}');
const jobId = await manager.sendToQueue('test-service', 'process', { data: 'test' });
expect(jobId).toBeDefined();
expect(q1).toBe(q2);
expect(q1).not.toBe(q3);
expect(stubs.createdQueues).toHaveLength(2);
expect(manager.getQueueNames()).toHaveLength(2);
expect(q1.getWorkerCount()).toBe(0);
} finally {
await manager.shutdown();
}
});
});
describe('shutdown', () => {
it('should shutdown gracefully', async () => {
const manager = new QueueManager(mockRedisConfig, {}, mockLogger);
manager.createQueue('test-queue');
it('closes created queues and Redis connection once even on concurrent shutdown calls', async () => {
const manager = new QueueManager(createConfig(), undefined, mockLogger, stubs.deps);
manager.getQueue('alpha');
await manager.shutdown();
expect((manager as any).isShuttingDown).toBe(true);
});
it('should handle multiple shutdown calls', async () => {
const manager = new QueueManager(mockRedisConfig, {}, mockLogger);
const promise1 = manager.shutdown();
const promise2 = manager.shutdown();
expect(promise1).toBe(promise2);
await promise1;
});
});
describe('metrics', () => {
it('should get global stats', async () => {
const manager = new QueueManager(
mockRedisConfig,
{
enableMetrics: true,
},
mockLogger
);
manager.createQueue('queue1');
manager.createQueue('queue2');
const stats = await manager.getGlobalStats();
expect(stats).toBeDefined();
expect(stats.totalQueues).toBe(2);
});
it('should get queue stats', async () => {
const manager = new QueueManager(
mockRedisConfig,
{
enableMetrics: true,
},
mockLogger
);
const _queue = manager.createQueue('test-queue');
const stats = await manager.getQueueStats('test-queue');
expect(stats).toBeDefined();
expect(stats.name).toBe('test-queue');
});
});
describe('rate limiting', () => {
it('should apply rate limit rules', () => {
const manager = new QueueManager(
mockRedisConfig,
{
rateLimiter: {
rules: [
{
name: 'api-limit',
max: 100,
duration: 60000,
scope: 'global',
},
],
},
},
mockLogger
);
const rateLimiter = (manager as any).rateLimiter;
expect(rateLimiter).toBeDefined();
const [r1, r2] = await Promise.all([manager.shutdown(), manager.shutdown()]);
expect(r1).toBeUndefined();
expect(r2).toBeUndefined();
expect(stubs.createdQueues[0]?.close).toHaveBeenCalledTimes(1);
expect(stubs.redisQuit).toHaveBeenCalledTimes(1);
});
});
});

View file

@ -289,7 +289,7 @@ export function identity(
entry = sha256(readSourceFile(absolute));
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
if (code === 'ENOENT' || code === 'ENOTDIR') {
entry = 'deleted';
} else if ((code === 'EACCES' || code === 'EPERM') && !tracked.has(path)) {
entry = 'unreadable';

View file

@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { chmodSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { prepareDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
@ -353,4 +353,36 @@ describe('existing-path research benchmark', () => {
expect(afterDelete.source.dirty).toBe(true);
});
});
test('identity hashes tracked files as deleted when their parent directory is replaced by a regular file (T-25)', () => {
withTempGitRepo(repoDir => {
const dirPath = join(repoDir, 'nested');
const nestedFile = join(dirPath, 'file.txt');
mkdirSync(dirPath, { recursive: true });
writeFileSync(nestedFile, 'hello\n');
runGit(repoDir, ['add', 'nested/file.txt']);
runGit(repoDir, [
'-c',
'user.name=Test User',
'-c',
'user.email=test@example.com',
'commit',
'-m',
'add nested file',
]);
rmSync(dirPath, { recursive: true, force: true });
writeFileSync(dirPath, 'now a regular file\n');
const result = identity({ sourceRoot: repoDir });
expect(result.source.contentSha256).toBe(
expectedSourceSha256([
['nested', sha256(readFileSync(dirPath))],
['nested/file.txt', 'deleted'],
['tracked.txt', sha256(readFileSync(join(repoDir, 'tracked.txt')))],
])
);
expect(result.source.dirty).toBe(true);
});
});
});

View file

@ -1,4 +1,3 @@
import { randomUUID } from 'node:crypto';
import { expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import {
@ -14,7 +13,8 @@ import { researchAgentDatabaseError } from '../../apps/stock/web-api/src/service
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
const agent = `agent:${randomUUID()}` as const;
const fixtureUuid = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
const agent = `agent:${fixtureUuid(1)}` as const;
const token = 'sb-research.fixture-token';
const adminToken = 'operator-test-secret-12345678901234567890';
const serviceToken = 'service-test-secret-123456789012345678901';
@ -156,9 +156,9 @@ test('resolver denies all dataset operations including canonical dataset exports
});
test('resolver exact write capabilities refuse trading, operators, foreign evidence and ownership impersonation', async () => {
const projectId = randomUUID(),
experimentId = randomUUID(),
familyId = randomUUID();
const projectId = fixtureUuid(2),
experimentId = fixtureUuid(3),
familyId = fixtureUuid(4);
const query = mock(async (sql: string) => ({
rows: sql.includes('token_hash')
? [{ id: agent, enabled: true, policy: { allowedProjectIds: [projectId] } }]
@ -183,7 +183,7 @@ test('resolver exact write capabilities refuse trading, operators, foreign evide
'/api/v2/runs/' + experimentId + '/reproduce',
`/api/v2/experiments/${experimentId}/cancel`,
`/api/v2/strategies/${familyId}/versions`,
`/api/v2/research-projects/${randomUUID()}/hypotheses`,
`/api/v2/research-projects/${fixtureUuid(5)}/hypotheses`,
]) {
expect(await check(path)).toBeInstanceOf(Response);
expect(((await check(path)) as Response).status).toBe(403);
@ -199,26 +199,26 @@ test('resolver exact write capabilities refuse trading, operators, foreign evide
});
test('resolver scopes GET and HEAD reads to granted projects, templates and owned resources', async () => {
const grantedProject = randomUUID(),
ungrantedProject = randomUUID(),
grantedBacktest = randomUUID(),
ungrantedBacktest = randomUUID(),
grantedHypothesis = randomUUID(),
ungrantedHypothesis = randomUUID(),
missingHypothesis = randomUUID(),
grantedArtifact = randomUUID(),
ungrantedArtifact = randomUUID(),
ownedExperiment = randomUUID(),
ownedExperiment2 = randomUUID(),
foreignExperiment = randomUUID(),
ownedWalkForward = randomUUID(),
foreignWalkForward = randomUUID(),
ownedRun = randomUUID(),
foreignRun = randomUUID(),
permittedStrategy = randomUUID(),
unpermittedStrategy = randomUUID(),
permittedVersion = randomUUID(),
unpermittedVersion = randomUUID();
const grantedProject = fixtureUuid(10),
ungrantedProject = fixtureUuid(11),
grantedBacktest = fixtureUuid(12),
ungrantedBacktest = fixtureUuid(13),
grantedHypothesis = fixtureUuid(14),
ungrantedHypothesis = fixtureUuid(15),
missingHypothesis = fixtureUuid(16),
grantedArtifact = fixtureUuid(17),
ungrantedArtifact = fixtureUuid(18),
ownedExperiment = fixtureUuid(19),
ownedExperiment2 = fixtureUuid(20),
foreignExperiment = fixtureUuid(21),
ownedWalkForward = fixtureUuid(22),
foreignWalkForward = fixtureUuid(23),
ownedRun = fixtureUuid(24),
foreignRun = fixtureUuid(25),
permittedStrategy = fixtureUuid(26),
unpermittedStrategy = fixtureUuid(27),
permittedVersion = fixtureUuid(28),
unpermittedVersion = fixtureUuid(29);
const query = mock(async (sql: string, values?: unknown[]) => {
if (sql.includes('FROM research_agents WHERE token_hash=')) {
@ -451,16 +451,16 @@ test('quota diagnostics remain distinguishable from arbitrary database failures;
});
test('artifact reads check run ownership before resolving evidence for research agents while preserving operator access', async () => {
const projectId = randomUUID(),
artifactId = randomUUID(),
revisionId = randomUUID(),
foreignRunId = randomUUID(),
const projectId = fixtureUuid(30),
artifactId = fixtureUuid(31),
revisionId = fixtureUuid(32),
foreignRunId = fixtureUuid(33),
now = new Date().toISOString();
const resolveAll = mock(async () => [
{
runId: foreignRunId,
backtestId: randomUUID(),
backtestId: fixtureUuid(34),
metricsVersion: 'canonical-analytics/v1' as const,
metricPath: 'analytics.metrics.sharpeRatio' as const,
strategyVersionId: null,

View file

@ -279,6 +279,26 @@ describe('Environment safety & multi-env isolation', () => {
}
});
test('allows MongoDB Unix domain socket (.sock) URIs in production env-safety guard (T-27)', () => {
const prodUnixCfg = makeConfig({
environment: 'production',
pgPassword: 'strong-prod-pg-password',
mongoUri: 'mongodb://prod_user:strong-prod-mongo-pass@%2Fvar%2Frun%2Fmongodb%2Fmongod.sock/stock',
mongoDatabase: 'stock',
});
expect(() => assertEnvironmentSafety(prodUnixCfg, 'webApi', {})).not.toThrow();
const prodUnixDevPassCfg = makeConfig({
environment: 'production',
pgPassword: 'strong-prod-pg-password',
mongoUri: 'mongodb://prod_user:trading_mongo_dev@%2Fvar%2Frun%2Fmongodb%2Fmongod.sock/stock',
mongoDatabase: 'stock',
});
expect(() => assertEnvironmentSafety(prodUnixDevPassCfg, 'webApi', {})).toThrow(
/cannot use a default dev\/qa credential/
);
});
test('blocks multi-host MongoDB seed lists targeting QA loopback :27017 for dataIngestion and dataPipeline', () => {
const qaFirstIngestion = makeConfig({
environment: 'development',