diff --git a/src/app/api/validate/__tests__/route.test.ts b/src/app/api/validate/__tests__/route.test.ts index 44f8985..adcc7b7 100644 --- a/src/app/api/validate/__tests__/route.test.ts +++ b/src/app/api/validate/__tests__/route.test.ts @@ -2,6 +2,7 @@ import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals import { NextRequest } from 'next/server'; import type { ValidationServiceOpts } from '@/lib/validation-service'; import { NetworkType, type ValidationData } from '@/lib/types'; +import { TaskCatalogError, type TaskCatalogErrorKind } from '@/lib/task-catalog'; const mockValidateUpgrade = jest.fn<(opts: ValidationServiceOpts) => Promise>(); @@ -30,6 +31,44 @@ describe('POST /api/validate', () => { jest.restoreAllMocks(); }); + it.each<[TaskCatalogErrorKind, number]>([ + ['invalid-id', 400], + ['outside-root', 403], + ['not-found', 404], + ['invalid-profile', 422], + ])('maps catalog error %s to status %i with its exact message', async (kind, status) => { + mockValidateUpgrade.mockRejectedValue(new TaskCatalogError(kind, `Profile error: ${kind}`)); + + const res = await POST( + createRequest({ + upgradeId: '2025-08-01-upgrade-qux', + network: 'mainnet', + userType: 'base-sc', + }) + ); + + expect(res.status).toBe(status); + expect(await res.json()).toEqual({ error: `Profile error: ${kind}` }); + }); + + it.each([ + [new Error('Simulation failed'), 'Simulation failed'], + ['unexpected rejection', 'Validation failed'], + ])('keeps a non-catalog rejection %p at 500 with the exact body', async (error, message) => { + mockValidateUpgrade.mockRejectedValue(error); + + const res = await POST( + createRequest({ + upgradeId: '2025-08-01-upgrade-qux', + network: 'mainnet', + userType: 'base-sc', + }) + ); + + expect(res.status).toBe(500); + expect(await res.json()).toEqual({ error: message }); + }); + it('accepts zeronet as a supported network', async () => { const res = await POST( createRequest({ diff --git a/src/app/api/validate/route.ts b/src/app/api/validate/route.ts index 7a17e09..e0f282a 100644 --- a/src/app/api/validate/route.ts +++ b/src/app/api/validate/route.ts @@ -1,4 +1,5 @@ import { validateUpgrade } from '@/lib/validation-service'; +import { TaskCatalogError, TASK_CATALOG_ERROR_STATUS } from '@/lib/task-catalog'; import { NextRequest, NextResponse } from 'next/server'; import { NetworkType } from '@/lib/types'; @@ -45,6 +46,12 @@ export async function POST(req: NextRequest) { return NextResponse.json({ success: true, data: validationResult }, { status: 200 }); } catch (error) { console.error('Validation failed:', error); + if (error instanceof TaskCatalogError) { + return NextResponse.json( + { error: error.message }, + { status: TASK_CATALOG_ERROR_STATUS[error.kind] } + ); + } return NextResponse.json( { error: error instanceof Error ? error.message : 'Validation failed' }, { status: 500 } diff --git a/src/lib/__tests__/task-catalog.test.ts b/src/lib/__tests__/task-catalog.test.ts index 727bd6a..ae706c5 100644 --- a/src/lib/__tests__/task-catalog.test.ts +++ b/src/lib/__tests__/task-catalog.test.ts @@ -36,6 +36,97 @@ it('discovers the default root from cwd and caches the catalog across cwd change expect(defaultTaskCatalog()).toBe(catalog); }); +describe('loadProfile', () => { + const profile = { + cmd: 'forge script Test', + ledgerId: 7, + rpcUrl: 'http://localhost:8545', + expectedDomainAndMessageHashes: { + address: '0x0000000000000000000000000000000000000001', + domainHash: '0x' + 'a'.repeat(64), + messageHash: '0x' + 'b'.repeat(64), + }, + stateOverrides: [], + stateChanges: [], + skipTaskOriginValidation: true, + }; + let profilePath: string; + + beforeEach(async () => { + profilePath = path.join( + tempDir, + 'active/evm/tasks/task/config/mainnet/validations/signer.json' + ); + await fs.mkdir(path.dirname(profilePath), { recursive: true }); + }); + + it('reports a missing Validation profile as not-found', () => { + const call = () => createTaskCatalog(tempDir).loadProfile('task', 'mainnet', 'missing'); + expect(call).toThrow(TaskCatalogError); + expect(call).toThrow(expect.objectContaining({ kind: 'not-found' })); + }); + + it('rethrows non-ENOENT profile read errors without wrapping them in TaskCatalogError', async () => { + await fs.mkdir(profilePath); + const call = () => createTaskCatalog(tempDir).loadProfile('task', 'mainnet', 'signer'); + expect(call).toThrow(expect.objectContaining({ code: 'EISDIR' })); + expect(call).not.toThrow(TaskCatalogError); + }); + + it.each([ + ['malformed JSON', '{', 'Invalid JSON:'], + ['schema-invalid JSON', '{}', 'ledgerId:'], + ])( + 'reports %s as invalid-profile with the validation summary', + async (_label, content, detail) => { + await fs.writeFile(profilePath, content); + const call = () => createTaskCatalog(tempDir).loadProfile('task', 'mainnet', 'signer'); + expect(call).toThrow(TaskCatalogError); + expect(call).toThrow(expect.objectContaining({ kind: 'invalid-profile' })); + expect(call).toThrow('Configuration has errors'); + expect(call).toThrow('Errors ('); + expect(call).toThrow(detail); + } + ); + + it.each(['taskId', 'network', 'name'])('rejects an invalid profile %s', field => { + const call = () => + createTaskCatalog(tempDir).loadProfile( + field === 'taskId' ? '../task' : 'task', + field === 'network' ? '../mainnet' : 'mainnet', + field === 'name' ? '../signer' : 'signer' + ); + expect(call).toThrow(TaskCatalogError); + expect(call).toThrow(expect.objectContaining({ kind: 'invalid-id' })); + }); + + it('rejects a Validation profile symlinked outside the root', async () => { + const root = path.join(tempDir, 'root'); + const link = path.join(root, 'active/evm/tasks/task/config/mainnet/validations/signer.json'); + await fs.mkdir(path.dirname(link), { recursive: true }); + await fs.writeFile(path.join(tempDir, 'outside.json'), JSON.stringify(profile)); + await fs.symlink(path.join(tempDir, 'outside.json'), link); + const call = () => createTaskCatalog(root).loadProfile('task', 'mainnet', 'signer'); + expect(call).toThrow(TaskCatalogError); + expect(call).toThrow(expect.objectContaining({ kind: 'outside-root' })); + }); + + it('loads a Validation profile symlinked to a file inside the root', async () => { + await fs.writeFile(path.join(tempDir, 'shared.json'), JSON.stringify(profile)); + await fs.symlink( + path.relative(path.dirname(profilePath), path.join(tempDir, 'shared.json')), + profilePath + ); + expect(createTaskCatalog(tempDir).loadProfile('task', 'mainnet', 'signer')).toEqual(profile); + }); + + it('loads the parsed Validation profile from the Task layout', async () => { + await fs.writeFile(profilePath, JSON.stringify({ ...profile, ignored: true })); + const catalog = createTaskCatalog(tempDir); + expect(catalog.loadProfile('task', 'mainnet', 'signer')).toEqual(profile); + }); +}); + describe('taskDirs', () => { it('rejects a dangling task symlink targeting a missing path outside the root', async () => { const root = path.join(tempDir, 'root'); diff --git a/src/lib/__tests__/validation-service.test.ts b/src/lib/__tests__/validation-service.test.ts index 949785a..346b0f6 100644 --- a/src/lib/__tests__/validation-service.test.ts +++ b/src/lib/__tests__/validation-service.test.ts @@ -2,7 +2,7 @@ import { afterAll, beforeAll, describe, expect, it, jest } from '@jest/globals'; import { promises as fs } from 'fs'; import os from 'os'; import path from 'path'; -import { resetContractDeploymentsRootCacheForTests } from '../deployments'; +import { resetContractDeploymentsRootCacheForTests, TaskCatalogError } from '../task-catalog'; import { NetworkType } from '../types'; const hashes = { @@ -69,6 +69,17 @@ describe('validateUpgrade', () => { await fs.rm(fixtureRoot, { recursive: true, force: true }); }); + it.each([ + ['missing', 'not-found'], + ['malformed', 'invalid-profile'], + ])('preserves the catalog error kind for a %s Validation profile', async (profile, kind) => { + await fs.rm(configPath, { force: true }); + if (profile === 'malformed') await fs.writeFile(configPath, '{'); + + await expect(validateUpgrade(opts)).rejects.toBeInstanceOf(TaskCatalogError); + await expect(validateUpgrade(opts)).rejects.toMatchObject({ kind }); + }); + it('returns the loaded validation profile ledgerId after simulation', async () => { await fs.writeFile(configPath, JSON.stringify(config)); diff --git a/src/lib/task-catalog.ts b/src/lib/task-catalog.ts index 724699a..4b9f368 100644 --- a/src/lib/task-catalog.ts +++ b/src/lib/task-catalog.ts @@ -1,5 +1,6 @@ import fs from 'fs'; import path from 'path'; +import { getValidationSummary, parseFromString } from './parser'; import { NetworkType, TaskStatus, Upgrade } from './types'; let cachedRoot: string | null = null; @@ -47,6 +48,13 @@ const MAX_STATUS_SEARCH_LINES = 20; export type TaskCatalogErrorKind = 'invalid-id' | 'outside-root' | 'not-found' | 'invalid-profile'; +export const TASK_CATALOG_ERROR_STATUS: Record = { + 'invalid-id': 400, + 'outside-root': 403, + 'not-found': 404, + 'invalid-profile': 422, +}; + export class TaskCatalogError extends Error { constructor( public readonly kind: TaskCatalogErrorKind, @@ -118,6 +126,28 @@ export function createTaskCatalog(root: string) { return { root, listTasks: (network: NetworkType) => listTasks(root, network), + loadProfile: (taskId: string, network: string, name: string) => { + assertValidId(taskId); + assertValidId(network); + assertValidId(name); + const { taskOriginDir } = taskDirs(root, taskId, network); + const profilePath = path.join(taskOriginDir, 'validations', `${name}.json`); + assertContainedPath(root, resolveExistingAncestor(root), profilePath); + let content: string; + try { + content = fs.readFileSync(profilePath, 'utf-8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + throw new TaskCatalogError('not-found', `Validation profile not found: ${profilePath}`); + } + throw error; + } + const parsed = parseFromString(content); + if (!parsed.success) { + throw new TaskCatalogError('invalid-profile', getValidationSummary(parsed)); + } + return parsed.config; + }, taskDirs: (taskId: string, network: string) => { assertValidId(taskId); assertValidId(network); diff --git a/src/lib/validation-service.ts b/src/lib/validation-service.ts index 81ff5dd..e5f1628 100644 --- a/src/lib/validation-service.ts +++ b/src/lib/validation-service.ts @@ -1,9 +1,6 @@ -import { promises as fs } from 'fs'; import path from 'path'; import { TASK_ORIGIN_COMMON_NAMES, TASK_ORIGIN_SIGNATURE_FILE_NAMES } from './constants'; -import { findContractDeploymentsRoot } from './deployments'; -import { getValidationSummary, parseFromString } from './parser'; -import { assertWithinDir } from './path-validation'; +import { defaultTaskCatalog } from './task-catalog'; import type { SafeTxTypedData } from './safe-typed-data'; import { StateDiffClient } from './state-diff'; import { verifyTaskOrigin } from './task-origin-validate'; @@ -28,65 +25,6 @@ export type ValidationServiceOpts = { taskConfigFileName: string; }; -const CONTRACT_DEPLOYMENTS_ROOT = findContractDeploymentsRoot(); -const stateDiffClient = new StateDiffClient(0, CONTRACT_DEPLOYMENTS_ROOT); - -async function getConfigData(opts: ValidationServiceOpts): Promise<{ - cfg: TaskConfig; - scriptPath: string; - networkConfigDir: string; - signatureDir: string; -}> { - const scriptPath = assertWithinDir( - path.join(CONTRACT_DEPLOYMENTS_ROOT, 'active', 'evm'), - CONTRACT_DEPLOYMENTS_ROOT - ); - const taskPath = assertWithinDir( - path.join(scriptPath, 'tasks', opts.upgradeId), - CONTRACT_DEPLOYMENTS_ROOT - ); - const networkConfigDir = assertWithinDir( - path.join(taskPath, 'config', opts.network), - CONTRACT_DEPLOYMENTS_ROOT - ); - const configDir = assertWithinDir( - path.join(networkConfigDir, 'validations'), - CONTRACT_DEPLOYMENTS_ROOT - ); - const configFileName = `${opts.taskConfigFileName}.json`; - const configPath = path.join(configDir, configFileName); - assertWithinDir(configPath, configDir); - - let configContent: string; - try { - configContent = await fs.readFile(configPath, 'utf-8'); - } catch (error: unknown) { - if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { - throw new Error(`ValidationService::getConfigData: Config file not found: ${configPath}`); - } - console.error(`❌ Error reading config file: ${error}`); - throw error; - } - - const parsedConfig = parseFromString(configContent); - - if (!parsedConfig.success) { - console.error('❌ Failed to parse config:', getValidationSummary(parsedConfig)); - throw new Error('ValidationService::getConfigData: Failed to parse config file'); - } - - console.log(`✅ Loaded config data from ${configFileName}`); - return { - cfg: parsedConfig.config, - scriptPath, - networkConfigDir, - signatureDir: assertWithinDir( - path.join(taskPath, 'signatures', opts.network), - CONTRACT_DEPLOYMENTS_ROOT - ), - }; -} - function getExpectedData(parsedConfig: TaskConfig): { stateOverrides: StateOverride[]; stateChanges: StateChange[]; @@ -103,7 +41,8 @@ function getExpectedData(parsedConfig: TaskConfig): { async function runStateDiffSimulation( scriptPath: string, - cfg: TaskConfig + cfg: TaskConfig, + stateDiffClient: StateDiffClient ): Promise<{ stateOverrides: StateOverride[]; stateChanges: StateChange[]; @@ -141,14 +80,12 @@ async function validateSigner( taskOriginDir: string, signatureDir: string, role: TaskOriginRole, + allowedDir: string, commonNameOverride?: string // Only used for taskCreator ): Promise { - assertWithinDir(taskOriginDir, CONTRACT_DEPLOYMENTS_ROOT); - // Get signatureFileName from constants (hardcoded for all roles) const signatureFileName = TASK_ORIGIN_SIGNATURE_FILE_NAMES[role]; const signatureFile = path.join(signatureDir, signatureFileName); - assertWithinDir(signatureFile, CONTRACT_DEPLOYMENTS_ROOT); // Get commonName: from config for taskCreator, from constants for facilitators const commonName = @@ -159,7 +96,7 @@ async function validateSigner( signatureFile, commonName, role, - allowedDir: CONTRACT_DEPLOYMENTS_ROOT, + allowedDir, }); return { @@ -174,7 +111,8 @@ async function validateSigner( async function runTaskOriginValidation( taskOriginDir: string, signatureDir: string, - config: TaskOriginValidationConfig + config: TaskOriginValidationConfig, + allowedDir: string ): Promise { const results: TaskOriginSignerResult[] = []; @@ -186,7 +124,7 @@ async function runTaskOriginValidation( const label = TASK_ORIGIN_ROLE_LABELS[role]; console.log(`🔐 Validating ${label} signature...`); try { - results.push(await validateSigner(taskOriginDir, signatureDir, role, commonName)); + results.push(await validateSigner(taskOriginDir, signatureDir, role, allowedDir, commonName)); console.log(` ✓ ${label} signature verified`); } catch (error) { const message = error instanceof Error ? error.message : 'Unknown error'; @@ -221,7 +159,10 @@ async function runTaskOriginValidation( export async function validateUpgrade(opts: ValidationServiceOpts): Promise { console.log(`🚀 Starting validation for ${opts.upgradeId} on ${opts.network}`); - const { cfg, scriptPath, networkConfigDir, signatureDir } = await getConfigData(opts); + const catalog = defaultTaskCatalog(); + const cfg = catalog.loadProfile(opts.upgradeId, opts.network, opts.taskConfigFileName); + const { evmDir, taskOriginDir, signaturesDir } = catalog.taskDirs(opts.upgradeId, opts.network); + const stateDiffClient = new StateDiffClient(0, catalog.root); // Determine task origin validation state let taskOriginValidation: TaskOriginValidation; @@ -242,9 +183,10 @@ export async function validateUpgrade(opts: ValidationServiceOpts): Promise