wishforge-ide/tests/canonical.test.ts
eust-w 82d35a3708 fix: use one canonical JSON implementation for digests and signatures
The API signed Runner tasks with keys sorted by localeCompare, while the
runner verified with code-unit order; environment keys such as
API_URL/API2 or DB_HOST/DBA sort differently, so valid deployment tasks
were rejected with INVALID_SIGNATURE. A third copy lived in the agent
package.

canonicalJson now lives in @wishforge/contracts (code-unit key order,
undefined properties omitted, non-JSON values rejected) and is used by
the API digest, Runner task signing/verification, the runner's state
digest and agent bundle digests. Binding digests computed by the old
locale-dependent order may differ, so releases requested before this
change must be requested again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:04:36 +08:00

50 lines
2.2 KiB
TypeScript

import { generateKeyPairSync } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import { canonicalJson } from '@wishforge/contracts';
import { signRunnerTask, verifyRunnerTask, type RunnerTask } from '@wishforge/runtime';
import { digest } from '../apps/api/src/domain/policy.js';
describe('canonical JSON shared by every digest and signature', () => {
it('orders keys by code unit, omits undefined properties and rejects non-JSON values', () => {
expect(canonicalJson({ b: 1, a: [undefined, { d: undefined, c: 'x' }], aC: true, ab: null })).toBe(
'{"a":[null,{"c":"x"}],"aC":true,"ab":null,"b":1}',
);
for (const value of [NaN, Infinity, () => 1, Symbol('x'), 1n, undefined])
expect(() => canonicalJson(value)).toThrow(TypeError);
});
it('lets the control plane digest and the runner signature agree on mixed-case configuration keys', () => {
// localeCompare and code-unit order disagree on these keys; the API signs and the runner verifies.
const config = { API_URL: 'https://api.example', API2: 'x', DB_HOST: 'db', DBA: 'y' };
expect(digest(config)).toBe(digest(JSON.parse(canonicalJson(config))));
const { privateKey, publicKey } = generateKeyPairSync('ed25519');
const task = {
schemaVersion: 1,
id: 'task-1',
tenantId: 'alpha',
environmentId: 'env-1',
nonce: 'nonce-1',
issuedAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 60_000).toISOString(),
action: 'deploy',
target: 'compose',
release: {
schemaVersion: 1,
id: 'release-1',
tenantId: 'alpha',
environmentId: 'env-1',
sourceCommit: 'a'.repeat(40),
image: `registry.example/app@sha256:${'b'.repeat(64)}`,
containerPort: 3000,
healthPath: '/health',
smokeChecks: [{ path: '/items', expectedStatus: 200 }],
expectedPreviousReleaseId: null,
config,
},
} as unknown as RunnerTask;
const signed = signRunnerTask(task, 'v1', privateKey);
const keys = { v1: publicKey.export({ type: 'spki', format: 'pem' }).toString() };
expect(verifyRunnerTask(signed, { tenantId: 'alpha', environmentId: 'env-1', publicKeys: keys }).id).toBe('task-1');
});
});