Skip to content
Open
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
161 changes: 72 additions & 89 deletions src/app/api/upgrade-config/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -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<string[]>>();
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');
Expand All @@ -25,100 +23,85 @@ function createRequest(params: Record<string, string>): 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<string, string> = { 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' }],
});
});
});
84 changes: 19 additions & 65 deletions src/app/api/upgrade-config/route.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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);
}
}
2 changes: 1 addition & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export default function Home() {

{currentStep === 'validation' && selectedUpgrade && (
<ValidationResults
userType={selectedUser?.fileName || ''}
userType={selectedUser?.name || ''}
network={selectedNetwork || ''}
upgradeId={selectedUpgrade.id}
onProceedToLedgerSigning={handleProceedToLedgerSigning}
Expand Down
8 changes: 4 additions & 4 deletions src/components/UserSelection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Button } from './ui/Button';
import { SectionHeader } from './ui/SectionHeader';

export interface ConfigOption {
fileName: string;
name: string;
displayName: string;
}

Expand Down Expand Up @@ -94,11 +94,11 @@ export function UserSelection({ network, upgradeId, onSelect }: UserSelectionPro
</div>
) : (
availableUsers.map(option => {
const isSelected = selectedUser?.fileName === option.fileName;
const isSelected = selectedUser?.name === option.name;

return (
<Card
key={option.fileName}
key={option.name}
interactive
selected={isSelected}
onClick={() => setSelectedUser(option)}
Expand All @@ -117,7 +117,7 @@ export function UserSelection({ network, upgradeId, onSelect }: UserSelectionPro
{option.displayName}
</h3>
<p className="text-xs text-[var(--cds-text-secondary)] font-mono mt-0.5">
{option.fileName}
{option.name}
</p>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/UserSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function UserSummary({ selectedUser, onChange }: UserSummaryProps) {
{selectedUser.displayName}
</h3>
<p className="text-xs text-[var(--cds-text-secondary)] font-mono mt-0.5">
{selectedUser.fileName}
{selectedUser.name}
</p>
</div>
</div>
Expand Down
Loading
Loading