From 5a195e12daff869c2a53a38d4fac9db9adc8749c Mon Sep 17 00:00:00 2001 From: Jack Chuma Date: Sat, 14 Nov 2026 10:03:46 -0500 Subject: [PATCH] refactor(upgrade-config): list Validation profiles through the Task catalog J-Engine-Session: toshi:c3193bba-dcb1-44ce-98c1-8f0c9a44bf2f --- .../upgrade-config/__tests__/route.test.ts | 161 ++++++++---------- src/app/api/upgrade-config/route.ts | 84 +++------ src/app/page.tsx | 2 +- src/components/UserSelection.tsx | 8 +- src/components/UserSummary.tsx | 2 +- src/lib/__tests__/task-catalog.test.ts | 87 ++++++++++ src/lib/task-catalog.ts | 45 ++++- 7 files changed, 221 insertions(+), 168 deletions(-) diff --git a/src/app/api/upgrade-config/__tests__/route.test.ts b/src/app/api/upgrade-config/__tests__/route.test.ts index 65c7188..81a9c47 100644 --- a/src/app/api/upgrade-config/__tests__/route.test.ts +++ b/src/app/api/upgrade-config/__tests__/route.test.ts @@ -1,18 +1,16 @@ +import fs from 'fs/promises'; +import os from 'os'; +import path from 'path'; import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals'; import { NextRequest } from 'next/server'; +import * as taskCatalog from '@/lib/task-catalog'; -const mockReaddir = jest.fn<(path: string) => Promise>(); +let fixtureRoot: string; +let tempDir: string; -jest.unstable_mockModule('fs', () => ({ - promises: { - readdir: mockReaddir, - }, -})); - -const mockFindContractDeploymentsRoot = jest.fn<() => string>(); - -jest.unstable_mockModule('@/lib/deployments', () => ({ - findContractDeploymentsRoot: mockFindContractDeploymentsRoot, +jest.unstable_mockModule('@/lib/task-catalog', () => ({ + ...taskCatalog, + defaultTaskCatalog: () => taskCatalog.createTaskCatalog(fixtureRoot), })); const { GET } = await import('../route'); @@ -25,100 +23,85 @@ function createRequest(params: Record): NextRequest { return new NextRequest(url); } +function validationsDir(): string { + return path.join( + fixtureRoot, + 'active', + 'evm', + 'tasks', + 'task', + 'config', + 'mainnet', + 'validations' + ); +} + describe('GET /api/upgrade-config', () => { - beforeEach(() => { - jest.clearAllMocks(); - jest.spyOn(console, 'log').mockImplementation(() => {}); - jest.spyOn(console, 'warn').mockImplementation(() => {}); - jest.spyOn(console, 'error').mockImplementation(() => {}); - mockFindContractDeploymentsRoot.mockReturnValue('/mock-root'); - mockReaddir.mockResolvedValue(['config1.json']); + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'profile-route-')); + fixtureRoot = path.join(tempDir, 'root'); + await fs.mkdir(fixtureRoot); }); - afterEach(() => { - jest.restoreAllMocks(); + afterEach(async () => { + await fs.rm(tempDir, { recursive: true, force: true }); }); - describe('missing parameters', () => { - it('returns 400 when network is missing', async () => { - const res = await GET(createRequest({ upgradeId: 'test' })); - expect(res.status).toBe(400); - const body = await res.json(); - expect(body.error).toMatch(/missing required parameter/i); - }); + it.each(['network', 'upgradeId'])('returns 400 when required %s is missing', async missing => { + const params: Record = { network: 'mainnet', upgradeId: 'task' }; + delete params[missing]; - it('returns 400 when upgradeId is missing', async () => { - const res = await GET(createRequest({ network: 'mainnet' })); - expect(res.status).toBe(400); - const body = await res.json(); - expect(body.error).toMatch(/missing required parameter/i); - }); - }); + const res = await GET(createRequest(params)); - describe('path traversal prevention', () => { - it.each(['..', 'foo/bar', 'main net', '.'])( - 'returns 400 when network is "%s"', - async network => { - const res = await GET(createRequest({ network, upgradeId: 'test' })); - expect(res.status).toBe(400); - const body = await res.json(); - expect(body.error).toMatch(/invalid network/i); - } - ); - it('returns 400 when upgradeId contains path separators', async () => { - const res = await GET(createRequest({ network: 'mainnet', upgradeId: 'foo/bar' })); - expect(res.status).toBe(400); - const body = await res.json(); - expect(body.error).toMatch(/invalid network or upgradeId/i); + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ + error: 'Missing required parameters: network and upgradeId are required', }); }); - describe('valid safe characters', () => { - it('accepts hyphens in network names', async () => { - const res = await GET(createRequest({ network: 'op-mainnet', upgradeId: 'test' })); - expect(res.status).toBe(200); - }); - }); + it('returns 500 with the existing message for other filesystem errors', async () => { + const validations = validationsDir(); + await fs.mkdir(path.dirname(validations), { recursive: true }); + await fs.writeFile(validations, 'not a directory'); - describe('happy path', () => { - it('returns only JSON config options in directory order with formatted names', async () => { - mockReaddir.mockResolvedValue(['b-profile.json', 'README.md', 'a.json']); - const res = await GET(createRequest({ network: 'mainnet', upgradeId: 'test' })); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body).toEqual({ - configOptions: [ - { fileName: 'b-profile', displayName: 'B Profile' }, - { fileName: 'a', displayName: 'A' }, - ], - }); - }); + const res = await GET(createRequest({ network: 'mainnet', upgradeId: 'task' })); - it('returns 200 with empty array on ENOENT', async () => { - const enoentError = Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); - mockReaddir.mockRejectedValue(enoentError); - const res = await GET(createRequest({ network: 'mainnet', upgradeId: 'test' })); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.configOptions).toEqual([]); - }); + expect(res.status).toBe(500); + expect(await res.json()).toEqual({ error: 'Failed to fetch upgrade configuration' }); }); - describe('post-validation', () => { - it('returns 500 on unexpected fs errors', async () => { - mockReaddir.mockRejectedValue(new Error('Unexpected disk error')); - const res = await GET(createRequest({ network: 'mainnet', upgradeId: 'test' })); - expect(res.status).toBe(500); - const body = await res.json(); - expect(body.error).toMatch(/failed to fetch upgrade configuration/i); - }); + it.each([ + { params: { network: '../network', upgradeId: 'task' }, status: 400 }, + { params: { network: 'mainnet', upgradeId: '../task' }, status: 400 }, + { params: { network: 'mainnet', upgradeId: 'task' }, status: 403 }, + { params: { network: 'mainnet', upgradeId: 'missing' }, status: 404 }, + ])('maps catalog errors to $status for $params', async ({ params, status }) => { + if (status === 403) { + const outside = path.join(tempDir, 'outside'); + await fs.mkdir(outside); + await fs.mkdir(path.dirname(validationsDir()), { recursive: true }); + await fs.symlink(outside, validationsDir()); + } + + const res = await GET(createRequest(params)); + + expect(res.status).toBe(status); + expect(await res.json()).toEqual({ error: expect.any(String) }); }); - describe('does not call fs', () => { - it('readdir not called when validation rejects', async () => { - await GET(createRequest({ network: '..', upgradeId: 'test' })); - expect(mockReaddir).not.toHaveBeenCalled(); - expect(mockFindContractDeploymentsRoot).not.toHaveBeenCalled(); + it('returns exactly the catalog profile names and display names', async () => { + const validations = validationsDir(); + await fs.mkdir(validations, { recursive: true }); + await fs.writeFile( + path.join(validations, 'signer-role.json'), + '{"ledgerId": 42, "name": "ignored", "displayName": "Ignored"}' + ); + + const res = await GET(createRequest({ network: 'mainnet', upgradeId: 'task' })); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + configOptions: [{ name: 'signer-role', displayName: 'Signer Role' }], }); }); }); diff --git a/src/app/api/upgrade-config/route.ts b/src/app/api/upgrade-config/route.ts index 3fa282d..665ef85 100644 --- a/src/app/api/upgrade-config/route.ts +++ b/src/app/api/upgrade-config/route.ts @@ -1,14 +1,21 @@ -import { promises as fs } from 'fs'; -import path from 'path'; import { NextRequest, NextResponse } from 'next/server'; -import { findContractDeploymentsRoot } from '@/lib/deployments'; -import { assertWithinDir } from '@/lib/path-validation'; - -const toDisplayName = (name: string) => - name - .split('-') - .map(word => word.charAt(0).toUpperCase() + word.slice(1)) - .join(' '); +import { defaultTaskCatalog, TaskCatalogError } from '@/lib/task-catalog'; + +function errorResponse(error: unknown) { + if (error instanceof TaskCatalogError) { + const status = { + 'invalid-id': 400, + 'outside-root': 403, + 'not-found': 404, + 'invalid-profile': 500, + }[error.kind]; + if (status !== 500) { + return NextResponse.json({ error: error.message }, { status }); + } + } + console.error('Error fetching upgrade config:', error); + return NextResponse.json({ error: 'Failed to fetch upgrade configuration' }, { status: 500 }); +} export async function GET(req: NextRequest) { const url = new URL(req.url); @@ -22,63 +29,10 @@ export async function GET(req: NextRequest) { ); } - const safePathPattern = /^[a-zA-Z0-9_-]+$/; - if (!safePathPattern.test(network) || !safePathPattern.test(upgradeId)) { - return NextResponse.json( - { - error: - 'Invalid network or upgradeId: only alphanumeric characters, hyphens, and underscores are allowed', - }, - { status: 400 } - ); - } - - const contractDeploymentsRoot = findContractDeploymentsRoot(); - const validationsJoinedPath = path.join( - contractDeploymentsRoot, - 'active', - 'evm', - 'tasks', - upgradeId, - 'config', - network, - 'validations' - ); - - // Verify the resolved path is within the allowed directory - let validationsPath: string; - try { - validationsPath = assertWithinDir(validationsJoinedPath, contractDeploymentsRoot); - } catch { - return NextResponse.json({ error: 'Invalid path: access denied' }, { status: 403 }); - } - try { - const entries = await fs.readdir(validationsPath); - const jsonFiles = entries.filter(file => file.endsWith('.json')); - - const configOptions = jsonFiles.map(configFile => { - const baseName = configFile.replace(/\.json$/, ''); - return { fileName: baseName, displayName: toDisplayName(baseName) }; - }); - - console.log( - 'Found %d config options for %s:', - configOptions.length, - `${network}/${upgradeId}`, - configOptions.map(c => c.displayName) - ); - + const configOptions = defaultTaskCatalog().listProfiles(upgradeId, network); return NextResponse.json({ configOptions }, { status: 200 }); } catch (error) { - const err = error as NodeJS.ErrnoException; - - if (err?.code === 'ENOENT') { - console.warn(`Validations path does not exist: ${validationsPath}`); - return NextResponse.json({ configOptions: [] }, { status: 200 }); - } - - console.error('Error fetching upgrade config:', error); - return NextResponse.json({ error: 'Failed to fetch upgrade configuration' }, { status: 500 }); + return errorResponse(error); } } diff --git a/src/app/page.tsx b/src/app/page.tsx index 2f92515..ba0a717 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -138,7 +138,7 @@ export default function Home() { {currentStep === 'validation' && selectedUpgrade && ( ) : ( availableUsers.map(option => { - const isSelected = selectedUser?.fileName === option.fileName; + const isSelected = selectedUser?.name === option.name; return ( setSelectedUser(option)} @@ -117,7 +117,7 @@ export function UserSelection({ network, upgradeId, onSelect }: UserSelectionPro {option.displayName}

- {option.fileName} + {option.name}

diff --git a/src/components/UserSummary.tsx b/src/components/UserSummary.tsx index 168e3b1..0011168 100644 --- a/src/components/UserSummary.tsx +++ b/src/components/UserSummary.tsx @@ -22,7 +22,7 @@ export function UserSummary({ selectedUser, onChange }: UserSummaryProps) { {selectedUser.displayName}

- {selectedUser.fileName} + {selectedUser.name}

diff --git a/src/lib/__tests__/task-catalog.test.ts b/src/lib/__tests__/task-catalog.test.ts index 727bd6a..f41e408 100644 --- a/src/lib/__tests__/task-catalog.test.ts +++ b/src/lib/__tests__/task-catalog.test.ts @@ -114,6 +114,93 @@ describe('taskDirs', () => { }); }); +describe('listProfiles', () => { + it('propagates other filesystem errors unchanged', async () => { + const validations = path.join( + tempDir, + 'active', + 'evm', + 'tasks', + 'task', + 'config', + 'mainnet', + 'validations' + ); + await fs.mkdir(path.dirname(validations), { recursive: true }); + await fs.writeFile(validations, 'not a directory'); + + const call = () => createTaskCatalog(tempDir).listProfiles('task', 'mainnet'); + expect(call).not.toThrow(TaskCatalogError); + expect(call).toThrow(expect.objectContaining({ code: 'ENOTDIR' })); + }); + + it.each([false, true])( + 'reports not-found for missing validations (Task exists: %s)', + async taskExists => { + if (taskExists) { + await fs.mkdir(path.join(tempDir, 'active', 'evm', 'tasks', 'task'), { recursive: true }); + } + const call = () => createTaskCatalog(tempDir).listProfiles('task', 'mainnet'); + expect(call).toThrow(TaskCatalogError); + expect(call).toThrow(expect.objectContaining({ kind: 'not-found' })); + } + ); + + it.each([ + 'active/evm', + 'active/evm/tasks/task', + 'active/evm/tasks/task/signatures/mainnet', + 'active/evm/tasks/task/config/mainnet', + 'active/evm/tasks/task/config/mainnet/validations', + ])('rejects an escaping profile listing path at %s', async relativePath => { + const root = path.join(tempDir, 'root'); + const outside = path.join(tempDir, 'outside'); + const link = path.join(root, relativePath); + await fs.mkdir(outside); + await fs.mkdir(path.dirname(link), { recursive: true }); + await fs.symlink(outside, link); + const call = () => createTaskCatalog(root).listProfiles('task', 'mainnet'); + expect(call).toThrow(TaskCatalogError); + expect(call).toThrow(expect.objectContaining({ kind: 'outside-root' })); + }); + + it.each([ + ['../task', 'mainnet'], + ['task', '../network'], + ['', 'mainnet'], + ['task', ''], + ])('rejects invalid Task id or network (%j, %j)', (taskId, network) => { + const call = () => createTaskCatalog(tempDir).listProfiles(taskId, network); + expect(call).toThrow(TaskCatalogError); + expect(call).toThrow(expect.objectContaining({ kind: 'invalid-id' })); + }); + + it('lists only JSON files sorted by name with display names, including malformed profiles', async () => { + const validations = path.join( + tempDir, + 'active', + 'evm', + 'tasks', + 'task', + 'config', + 'mainnet', + 'validations' + ); + await fs.mkdir(validations, { recursive: true }); + await fs.writeFile(path.join(validations, 'z-last.json'), '{"ledgerId": 99}'); + await fs.writeFile(path.join(validations, 'a-first.json'), 'not valid JSON'); + await fs.writeFile(path.join(validations, 'README.md'), 'ignore me'); + await fs.writeFile(path.join(validations, 'other.JSON'), '{}'); + await fs.mkdir(path.join(validations, 'directory.json')); + + const catalog = createTaskCatalog(tempDir); + expect(catalog.listProfiles('task', 'mainnet')).toEqual([ + { name: 'a-first', displayName: 'A First' }, + { name: 'z-last', displayName: 'Z Last' }, + ]); + }); +}); + describe('listTasks', () => { it('omits a Task with a regular-file network config without dropping a ready sibling', async () => { await makeTask('2025-06-04-safe', 'mainnet', '# Safe\n\nStatus: READY TO SIGN'); diff --git a/src/lib/task-catalog.ts b/src/lib/task-catalog.ts index 724699a..558307b 100644 --- a/src/lib/task-catalog.ts +++ b/src/lib/task-catalog.ts @@ -115,19 +115,48 @@ function isListingPathInsideRoot(root: string, realRoot: string, filePath: strin export function createTaskCatalog(root: string) { root = path.resolve(root); + const checkedTaskDirs = (taskId: string, network: string) => { + assertValidId(taskId); + assertValidId(network); + const dirs = taskDirs(root, taskId, network); + const realRoot = resolveExistingAncestor(root); + for (const dir of Object.values(dirs)) { + assertContainedPath(root, realRoot, dir); + } + return dirs; + }; return { root, listTasks: (network: NetworkType) => listTasks(root, network), - taskDirs: (taskId: string, network: string) => { - assertValidId(taskId); - assertValidId(network); - const dirs = taskDirs(root, taskId, network); - const realRoot = resolveExistingAncestor(root); - for (const dir of Object.values(dirs)) { - assertContainedPath(root, realRoot, dir); + listProfiles: (taskId: string, network: string) => { + const { taskOriginDir } = checkedTaskDirs(taskId, network); + const validationsDir = path.join(taskOriginDir, 'validations'); + assertContainedPath(root, resolveExistingAncestor(root), validationsDir); + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(validationsDir, { withFileTypes: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + throw new TaskCatalogError( + 'not-found', + `Validations directory does not exist: ${validationsDir}` + ); + } + throw error; } - return dirs; + return entries + .filter(entry => entry.isFile() && entry.name.endsWith('.json')) + .map(entry => entry.name.slice(0, -5)) + .sort() + .map(name => ({ + name, + displayName: name + .split('-') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' '), + })); }, + taskDirs: checkedTaskDirs, }; }