import { describe, it, expect, vi } from 'vitest'; import os from 'node:os'; import fs from 'node:fs'; import path from 'node:path'; import { WaggleDB } from '@waggle/core'; import { createInMemoryMemoryStore } from '@waggle/memory-contract'; import { buildWorkspaceNowBlock } from '../../src/local/routes/workspace-context.js'; /** * R6-006 path-traversal regression. * * `buildWorkspaceNowBlock` builds session-directory paths from an unvalidated * `workspaceId` (dataDir/workspaces//sessions), * enabling an existence/count probe outside the workspaces root. A guard * (assertSafeSegment) now runs at the entry of the helper and THROWS a * { statusCode: 400 } error before the value touches the filesystem; the * calling route handlers propagate that to Fastify's default error handler. * * These are unit tests against the exported helper directly (a full route * inject is impractical — the route needs heavy memory/wsManager decorators). */ describe('R6-006 workspace-context path traversal', () => { // A throwaway data dir; the guard fires before this is ever read for the // malicious cases, and the valid case short-circuits on a null wsManager.get. const tmpDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wctx-traversal-')); const waggleDb = new WaggleDB(':memory:'); const maliciousIds = ['../evil', '..%2f..', '../../etc', 'ws/../../secret', '..\\evil']; for (const bad of maliciousIds) { it(`rejects traversal workspaceId ${JSON.stringify(bad)} with a 400 error before any fs access`, async () => { const wsManager = { get: vi.fn(() => ({ id: bad, name: 'evil' })), }; const memory = createInMemoryMemoryStore(); const count = vi.spyOn(memory, 'count'); let thrown: unknown; try { await buildWorkspaceNowBlock({ dataDir: tmpDataDir, workspaceId: bad, wsManager, waggleDb, memory, }); } catch (e) { thrown = e; } expect(thrown).toBeInstanceOf(Error); expect((thrown as { statusCode?: number }).statusCode).toBe(400); // Guard short-circuits BEFORE the workspace and its memory are touched. expect(wsManager.get).not.toHaveBeenCalled(); expect(count).not.toHaveBeenCalled(); }); } it('does NOT reject a normal valid workspaceId', async () => { const validId = 'workspace-123_AB'; const wsManager = { // Return null so the helper cleanly returns null after the guard passes — // proving the guard did not reject a valid segment. get: vi.fn(() => null), }; const result = await buildWorkspaceNowBlock({ dataDir: tmpDataDir, workspaceId: validId, wsManager, waggleDb, memory: createInMemoryMemoryStore(), }); // Guard passed, so execution proceeded to the (mocked) wsManager.get. expect(wsManager.get).toHaveBeenCalledWith(validId); expect(result).toBeNull(); }); });