check-food-interop.mjs (11254B)
1 import assert from 'node:assert/strict'; 2 import { createHash } from 'node:crypto'; 3 import { 4 lstat, 5 mkdtemp, 6 readFile, 7 readdir, 8 rm, 9 writeFile 10 } from 'node:fs/promises'; 11 import { tmpdir } from 'node:os'; 12 import { join } from 'node:path'; 13 import { spawnSync } from 'node:child_process'; 14 import { fileURLToPath } from 'node:url'; 15 import { format, resolveConfig } from 'prettier'; 16 import { webTemplates } from '../tests/conformance/food-writer-cases.ts'; 17 import { qualifiedTemplates } from '../tests/conformance/food-qualified-matrix.ts'; 18 import { createFoodReplay } from '../tests/conformance/food-bidirectional.ts'; 19 20 const web = fileURLToPath(new URL('../', import.meta.url)); 21 const root = fileURLToPath(new URL('../../', import.meta.url)); 22 const fixture = new URL( 23 '../tests/conformance/food-writer-rust.v1.json', 24 import.meta.url 25 ); 26 const qualifiedFixture = new URL( 27 '../tests/conformance/food-qualified-writer-rust.v1.json', 28 import.meta.url 29 ); 30 const args = process.argv.slice(2); 31 assert.ok( 32 args.length === 0 || 33 (args.length === 1 && ['--write', '--write-qualified'].includes(args[0])), 34 'expected no arguments, --write or browser-only --write-qualified' 35 ); 36 assert.equal(process.versions.node, '24.21.0'); 37 const run = (command, argv, cwd = root) => { 38 // Compiler and cache waits on a busy host have no outer elapsed cutoff. 39 const result = spawnSync(command, argv, { 40 cwd, 41 encoding: 'utf8', 42 maxBuffer: 1024 * 1024 43 }); 44 assert.ifError(result.error); 45 assert.equal(result.signal, null, `${command} interrupted`); 46 return result; 47 }; 48 const success = (command, argv, cwd = root) => { 49 const result = run(command, argv, cwd); 50 assert.equal(result.status, 0, result.stderr || result.stdout); 51 return result.stdout; 52 }; 53 const cargo = [ 54 '+1.99.0', 55 'run', 56 '--manifest-path', 57 'contracts/interop/food_availability/oracle/Cargo.toml', 58 '--locked', 59 '--offline', 60 '--quiet', 61 '--' 62 ]; 63 const names = [ 64 'corpus.v1.json', 65 'source_profile.v1.json', 66 'provenance.v1.json', 67 'oracle/src/main.rs' 68 ]; 69 async function ownedInput(name) { 70 const path = new URL( 71 `../../contracts/interop/food_availability/${name}`, 72 import.meta.url 73 ); 74 const info = await lstat(path); 75 assert.ok( 76 info.isFile() && 77 !info.isSymbolicLink() && 78 info.size > 0 && 79 info.size <= 1024 * 1024 80 ); 81 const bytes = await readFile(path); 82 assert.equal(bytes.length, info.size); 83 return bytes; 84 } 85 const readInputs = () => 86 Promise.all(names.map(async (name) => [name, await ownedInput(name)])); 87 const inputs = await readInputs(); 88 const corpus = inputs[0][1]; 89 success(process.execPath, ['tools/check-source.mjs'], web); 90 success('cargo', [...cargo, '--check']); 91 assert.equal( 92 success('cargo', [...cargo, '--emit']), 93 corpus.toString(), 94 'current pinned Rust corpus differs' 95 ); 96 const temporary = await mkdtemp(join(tmpdir(), 'harvestcircle-food-interop-')); 97 try { 98 const candidate = join(temporary, 'web.json'); 99 await writeFile(candidate, JSON.stringify(webTemplates, null, 2) + '\n'); 100 const actual = JSON.parse( 101 success('cargo', [...cargo, '--consume-web', candidate]) 102 ); 103 for (const mutation of ['tag', 'amount']) { 104 const altered = webTemplates.map((row) => ({ 105 ...row, 106 wire_parts: { 107 ...row.wire_parts, 108 tags: row.wire_parts.tags.map((tag) => [...tag]) 109 } 110 })); 111 const price = altered[0].wire_parts.tags.find((tag) => tag[0] === 'price'); 112 assert.ok(price); 113 if (mutation === 'tag') price[0] = 'different-price'; 114 else price[1] = '1e3'; 115 await writeFile(candidate, JSON.stringify(altered, null, 2) + '\n'); 116 const rejected = run('cargo', [...cargo, '--consume-web', candidate]); 117 assert.equal( 118 rejected.status, 119 101, 120 `actual Rust accepted ${mutation} mutation or did not execute` 121 ); 122 assert.ok( 123 rejected.stderr.includes('website template rejected:'), 124 rejected.stderr 125 ); 126 console.log( 127 JSON.stringify({ 128 direction: 'WEB_TO_RUST_NEGATIVE', 129 batch: 'original', 130 mutation, 131 exit_code: rejected.status, 132 actual_stderr: rejected.stderr 133 }) 134 ); 135 } 136 if (args[0] === '--write') { 137 // Refresh producer provenance only after actual Rust corpus equality, 138 // website consumption and hostile-template rejection have succeeded. 139 const digest = (bytes) => createHash('sha256').update(bytes).digest('hex'); 140 const provenance = JSON.parse(inputs[2][1].toString()); 141 assert.equal(provenance.public_source.revision, actual.revision); 142 assert.equal(provenance.source_copy.sha256, digest(inputs[1][1])); 143 assert.equal(provenance.corpus.sha256, digest(corpus)); 144 const producerNames = [ 145 'oracle/Cargo.toml', 146 'oracle/Cargo.lock', 147 'oracle/rust-toolchain.toml', 148 'oracle/src/main.rs' 149 ]; 150 assert.deepEqual( 151 provenance.producer.files.map((row) => row.path).sort(), 152 producerNames.toSorted() 153 ); 154 assert.match( 155 success('rustup', ['run', '1.99.0', 'rustc', '--version']), 156 /^rustc 1\.99\.0 / 157 ); 158 assert.match( 159 (await ownedInput('oracle/rust-toolchain.toml')).toString(), 160 /^channel = "1\.99\.0"$/m 161 ); 162 provenance.producer.rust_toolchain = '1.99.0'; 163 provenance.producer.files = await Promise.all( 164 producerNames.map(async (path) => { 165 const bytes = await ownedInput(path); 166 return { path, sha256: digest(bytes), bytes: bytes.length }; 167 }) 168 ); 169 await writeFile( 170 new URL( 171 '../../contracts/interop/food_availability/provenance.v1.json', 172 import.meta.url 173 ), 174 JSON.stringify(provenance, null, 2) + '\n' 175 ); 176 } 177 // The replay must bind the refreshed producer provenance, never stale bytes 178 // read before an explicitly requested regeneration. 179 const receipt = createFoodReplay(actual, webTemplates, await readInputs()); 180 if (args[0] === '--write') { 181 // Producer output must satisfy the same pinned formatting policy as lint. 182 // Format only the actual Rust replay, before its raw-byte manifest is built. 183 const filepath = fileURLToPath(fixture); 184 await writeFile( 185 fixture, 186 await format(JSON.stringify(receipt), { 187 ...(await resolveConfig(filepath)), 188 filepath 189 }) 190 ); 191 } else 192 assert.deepEqual( 193 JSON.parse(await readFile(fixture, 'utf8')), 194 receipt, 195 'checked website/Rust replay is stale; regenerate explicitly with --write' 196 ); 197 // Qualify a separate browser-owned boundary batch. The original sixteen 198 // recipes/shared manifest remain byte-exact and are still checked above. 199 await writeFile( 200 candidate, 201 JSON.stringify(qualifiedTemplates, null, 2) + '\n' 202 ); 203 const qualifiedActual = JSON.parse( 204 success('cargo', [...cargo, '--consume-web', candidate]) 205 ); 206 const qualifiedControls = [ 207 'amount-digits', 208 'fraction-digits', 209 'quantity-zero', 210 'quantity-unit', 211 'published-unsafe', 212 'created-unsafe', 213 'text-format', 214 'identifier-space', 215 'operational-marker', 216 'price-frequency' 217 ]; 218 for (const mutation of qualifiedControls) { 219 const altered = qualifiedTemplates.map((row) => ({ 220 ...row, 221 wire_parts: { 222 ...row.wire_parts, 223 tags: row.wire_parts.tags.map((tag) => [...tag]) 224 } 225 })); 226 const row = altered[0]; 227 const tag = (name) => { 228 const found = row.wire_parts.tags.find((value) => value[0] === name); 229 assert.ok(found, `missing qualified ${name}`); 230 return found; 231 }; 232 if (mutation === 'amount-digits') tag('price')[1] = '1'.repeat(29); 233 else if (mutation === 'fraction-digits') 234 tag('price')[1] = '0.' + '0'.repeat(27) + '1'; 235 else if (mutation === 'quantity-zero') tag('radroots:quantity')[1] = '0'; 236 else if (mutation === 'quantity-unit') tag('radroots:quantity')[2] = 'lb'; 237 else if (mutation === 'published-unsafe') 238 tag('published_at')[1] = '9007199254740992'; 239 else if (mutation === 'created-unsafe') row.created_at = 9007199254740992; 240 else if (mutation === 'text-format') tag('title')[1] = 'Food\u200d'; 241 else if (mutation === 'identifier-space') 242 tag('d')[1] = 'invalid identifier'; 243 else if (mutation === 'operational-marker') 244 tag('radroots:quantity')[0] = 'radroots:bin'; 245 else tag('price').push('weekly'); 246 await writeFile(candidate, JSON.stringify(altered, null, 2) + '\n'); 247 const rejected = run('cargo', [...cargo, '--consume-web', candidate]); 248 assert.equal( 249 rejected.status, 250 101, 251 `actual Rust accepted qualified ${mutation} or did not execute` 252 ); 253 assert.ok( 254 rejected.stderr.includes('website template rejected:'), 255 rejected.stderr 256 ); 257 console.log( 258 JSON.stringify({ 259 direction: 'WEB_TO_RUST_NEGATIVE', 260 batch: 'qualified', 261 mutation, 262 exit_code: rejected.status, 263 actual_stderr: rejected.stderr 264 }) 265 ); 266 } 267 const qualifiedReceipt = createFoodReplay( 268 qualifiedActual, 269 qualifiedTemplates, 270 await readInputs() 271 ); 272 if (['--write', '--write-qualified'].includes(args[0])) { 273 // Browser-only mode writes only this replay. Native/shared producer and 274 // original fixture/manifest outputs are checked without regeneration. 275 const filepath = fileURLToPath(qualifiedFixture); 276 await writeFile( 277 qualifiedFixture, 278 await format(JSON.stringify(qualifiedReceipt), { 279 ...(await resolveConfig(filepath)), 280 filepath 281 }) 282 ); 283 } else 284 assert.deepEqual( 285 JSON.parse(await readFile(qualifiedFixture, 'utf8')), 286 qualifiedReceipt, 287 'qualified browser/Rust replay is stale; regenerate explicitly with --write-qualified' 288 ); 289 // The shared consumer manifest binds these exact provenance/replay bytes. 290 success( 291 process.execPath, 292 [ 293 'tools/generate-interop-manifest.mjs', 294 ...(args[0] === '--write' ? ['--write'] : []) 295 ], 296 web 297 ); 298 const tests = ( 299 await readdir(new URL('../tests/conformance/', import.meta.url)) 300 ) 301 .filter((name) => name.endsWith('.test.ts')) 302 .sort(); 303 assert.ok(tests.length >= 5, 'missing conformance consumers'); 304 for (const required of [ 305 'food-reader.test.ts', 306 'food-writer.test.ts', 307 'food-corpus.test.ts', 308 'food-bidirectional.test.ts', 309 'food-qualified-matrix.test.ts' 310 ]) 311 assert.ok( 312 tests.includes(required), 313 `missing actual conformance consumer: ${required}` 314 ); 315 const output = success( 316 process.execPath, 317 ['--test', ...tests.map((name) => `tests/conformance/${name}`)], 318 web 319 ); 320 process.stdout.write(output); 321 const vectors = JSON.parse(corpus.toString()).vectors; 322 const readerCases = vectors.filter((row) => row.signed_wires.event).length; 323 assert.equal(readerCases, 18); 324 console.log( 325 JSON.stringify({ 326 result: 'PASS', 327 qualification: 'FIXTURE_ONLY_NOT_DEPLOYED_TERA', 328 revision: receipt.revision, 329 reader_cases: readerCases, 330 writer_cases: webTemplates.length, 331 qualified_writer_cases: qualifiedTemplates.length, 332 deliberate_mutations_rejected_by_actual_rust: 333 2 + qualifiedControls.length, 334 signing: 'NOT_RUN_NO_KEYS' 335 }) 336 ); 337 } finally { 338 await rm(temporary, { recursive: true, force: true }); 339 }