Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/app/api/validate/__tests__/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ValidationData>>();

Expand Down Expand Up @@ -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({
Expand Down
7 changes: 7 additions & 0 deletions src/app/api/validate/route.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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 }
Expand Down
91 changes: 91 additions & 0 deletions src/lib/__tests__/task-catalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
13 changes: 12 additions & 1 deletion src/lib/__tests__/validation-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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));

Expand Down
30 changes: 30 additions & 0 deletions src/lib/task-catalog.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<TaskCatalogErrorKind, number> = {
'invalid-id': 400,
'outside-root': 403,
'not-found': 404,
'invalid-profile': 422,
};

export class TaskCatalogError extends Error {
constructor(
public readonly kind: TaskCatalogErrorKind,
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading