From f4678c48ca759047e634ce1603f7ee74d53c229e Mon Sep 17 00:00:00 2001 From: Canina Engineering Date: Sun, 25 Oct 2026 06:30:18 +0000 Subject: [PATCH] test(backend): isolate worker secrets and support HTTP listener --- .../worker-registration.spec.ts | 35 ++++++++++++++----- .../support-chat/support-chat.http.spec.ts | 14 ++++++-- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/backend/src/orchestration-worker/worker-registration.spec.ts b/backend/src/orchestration-worker/worker-registration.spec.ts index b4dd9c47..9928fe91 100644 --- a/backend/src/orchestration-worker/worker-registration.spec.ts +++ b/backend/src/orchestration-worker/worker-registration.spec.ts @@ -1,5 +1,8 @@ import { Test } from '@nestjs/testing'; -import { writeFileSync, chmodSync, symlinkSync, mkdirSync, rmSync } from 'fs'; +import { writeFileSync, chmodSync, symlinkSync, mkdirSync, rmSync, mkdtempSync } from 'fs'; +import fs = require('fs'); +import { tmpdir } from 'os'; +import { join } from 'path'; import { execFileSync } from 'child_process'; import { registerPrepareWorker } from './worker-registration'; import { loadPrepareWorkerConfig } from './worker-config'; @@ -7,10 +10,29 @@ import { linkSync } from 'fs'; describe('reviewed prepare-worker startup registration', () => { - const path = '/run/secrets/prepare_worker_grants'; + let root: string; + let secrets: string; + let path: string; + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'prepare-worker-registration-')); + secrets = join(root, 'run', 'secrets'); + mkdirSync(secrets, { recursive: true, mode: 0o700 }); + path = join(secrets, 'prepare_worker_grants'); + // Substitute only the root descriptor, retaining real openat-style traversal, + // O_NOFOLLOW, fstat, read bounds, ownership and permission validation. + const open = fs.openSync; + jest.spyOn(fs, 'openSync').mockImplementation((file, flags, mode) => + open(file === '/' ? root : file, flags, mode)); + }); + afterEach(() => { + jest.restoreAllMocks(); + rmSync(root, { recursive: true, force: true }); + }); + it('isolates secret fixtures from the host runtime secret directory', () => { + expect(path.startsWith('/run/secrets/')).toBe(false); + }); const valid = () => ({ grants: [{ id: 'worker', role: 'WORKFLOW_WORKER', credentialSha256: 'a'.repeat(64) }, { id: 'ci', role: 'STAGE_CI', credentialSha256: 'b'.repeat(64) }], workerIds: ['worker'], stageCiIds: ['ci'], artifactBaseUrl: 'https://stage.example.com/internal/prepare-worker/artifacts' }); it('loader itself rejects malformed SHA grants', () => { - mkdirSync('/run/secrets', { recursive: true }); const c = valid(); c.grants[0].credentialSha256 = 'secret-not-a-sha'; writeFileSync(path, JSON.stringify(c), { mode: 0o400 }); try { expect(() => loadPrepareWorkerConfig()).toThrow('Prepare worker startup configuration rejected'); } @@ -20,8 +42,7 @@ describe('reviewed prepare-worker startup registration', () => { expect(registerPrepareWorker({ PREPARE_WORKER_ENABLED: value })).toEqual([]); }); it.each(['missing', 'symlink', 'directory', 'fifo', 'oversize', 'group-write', 'world-write', 'hardlink'])('fails startup on unsafe file: %s', kind => { - mkdirSync('/run/secrets', { recursive: true }); - const other = '/run/secrets/test-other'; + const other = join(secrets, 'test-other'); try { if (kind === 'fifo') execFileSync('mkfifo', [path]); else if (kind === 'directory') mkdirSync(path); @@ -36,7 +57,6 @@ describe('reviewed prepare-worker startup registration', () => { } finally { rmSync(path, { recursive: true, force: true }); rmSync(other, { force: true }); } }); it.each(['extra', 'raw-token', 'wrong-role', 'overlap', 'duplicate-sha', 'missing-grant', 'http', 'credentials', 'localhost', 'query', 'bad-json', 'null'])('rejects unreviewed JSON: %s without leaking contents or logging', kind => { - mkdirSync('/run/secrets', { recursive: true }); const c: any = valid(); if (kind === 'extra') c.artifactDirectory = '/user-selected'; if (kind === 'raw-token') c.grants[0].token = 'DO_NOT_LOG_THIS_SECRET'; @@ -67,8 +87,7 @@ describe('reviewed prepare-worker startup registration', () => { } finally { await app.close(); } }); it('loads immutable reviewed JSON into the real transport registration', async () => { - mkdirSync('/run/secrets', { recursive: true }); - const file = '/run/secrets/prepare_worker_grants'; + const file = path; const config = { grants: [{ id: 'worker', role: 'WORKFLOW_WORKER', credentialSha256: 'a'.repeat(64) }, { id: 'ci', role: 'STAGE_CI', credentialSha256: 'b'.repeat(64) }], workerIds: ['worker'], stageCiIds: ['ci'], artifactBaseUrl: 'https://stage.example.com/internal/prepare-worker/artifacts' }; writeFileSync(file, JSON.stringify(config), { mode: 0o400 }); try { diff --git a/backend/src/support-chat/support-chat.http.spec.ts b/backend/src/support-chat/support-chat.http.spec.ts index 8ca7328a..9eebdb13 100644 --- a/backend/src/support-chat/support-chat.http.spec.ts +++ b/backend/src/support-chat/support-chat.http.spec.ts @@ -20,7 +20,10 @@ describe('support HTTP boundary', () => { beforeAll(async () => { process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters'; const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [{ provide: SupportChatSettingsService, useValue: { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } }, SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile(); - app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init(); + app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); + // Own the listener for the entire suite. Otherwise Supertest lets the first + // request start the server and close it while its concurrent peer is using it. + await app.listen(0, '127.0.0.1'); }); afterAll(() => app.close()); beforeEach(() => { @@ -45,7 +48,14 @@ describe('support HTTP boundary', () => { }); it('scopes wallet to validated identity across concurrent callers', async () => { const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول'}).expect(201))); - expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled(); + expect(replies[0].body.answer).toBe('موجودی کیف پول شما: 11 تومان.'); + expect(replies[1].body.answer).toBe('موجودی کیف پول شما: 22 تومان.'); + expect(prisma.user.findUnique).toHaveBeenCalledTimes(2); + for (const id of ['alice', 'bob']) { + expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { id }, select: { walletBalance: true } }); + } + expect(prisma.product.findMany).not.toHaveBeenCalled(); + expect(prisma.order.findMany).not.toHaveBeenCalled(); }); it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); }); it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); });