diff --git a/.github/workflows/release-all.yml b/.github/workflows/release-all.yml index a488456557..b551495333 100644 --- a/.github/workflows/release-all.yml +++ b/.github/workflows/release-all.yml @@ -2220,14 +2220,22 @@ jobs: run: | SRC="$PWD/src" set -euo pipefail - ND="${RUNNER_TEMP}/node-ia32" + # RUNNER_TEMP is a Windows path, D:\a\_temp. GNU tar reads anything + # before a colon as a REMOTE HOST (host:path, for rmt), so + # `tar -C D:\a\_temp/node-ia32` died with "Cannot open: No such file + # or directory" - v12.32, the first release whose win32 job got this + # far. So the shell works on the POSIX form of the path, tar is given + # only relative names, and node-gyp gets the Windows form it expects. + ND="$(cygpath -u "$RUNNER_TEMP")/node-ia32" mkdir -p "$ND/ia32" "$ND/Release" # Headers (same for every arch); try /download/release then /dist. - bash "$SRC/releases/fetch.sh" --optional -o /tmp/nodehdr.tar.gz \ + bash "$SRC/releases/fetch.sh" --optional -o "$ND/node-headers.tar.gz" \ "https://nodejs.org/download/release/${NODE_FULL}/node-${NODE_FULL}-headers.tar.gz" \ - || bash "$SRC/releases/fetch.sh" -o /tmp/nodehdr.tar.gz \ + || bash "$SRC/releases/fetch.sh" -o "$ND/node-headers.tar.gz" \ "https://nodejs.org/dist/${NODE_FULL}/node-${NODE_FULL}-headers.tar.gz" - tar -xzf /tmp/nodehdr.tar.gz -C "$ND" --strip-components=1 + (cd "$ND" && tar -xzf node-headers.tar.gz --strip-components=1 && rm -f node-headers.tar.gz) + test -f "$ND/include/node/node.h" \ + || { echo "::error::The Node.js ${NODE_FULL} headers did not unpack into $ND/include/node."; exit 1; } # The 32-bit import library, at the two paths node-gyp may look in. It # comes from wekan/node-patches, which is also where the node-win32.exe # in this bundle comes from (nobody else builds either any more), so the @@ -2235,8 +2243,8 @@ jobs: bash "$SRC/releases/fetch.sh" -o "$ND/ia32/node.lib" \ "https://github.com/wekan/node-patches/releases/download/${NODE_FULL}/node-win32.lib" cp "$ND/ia32/node.lib" "$ND/Release/node.lib" - export npm_config_nodedir="$ND" - echo "Cross-building ia32 native modules against nodedir $ND (fork node.lib)." + export npm_config_nodedir="$(cygpath -w "$ND")" + echo "Cross-building ia32 native modules against nodedir $npm_config_nodedir (fork node.lib)." cd bundle/programs/server rm -rf node_modules bash "$SRC/releases/npm-retry.sh" npm install @@ -2257,6 +2265,11 @@ jobs: # packages load it through Npm.require(). This removes only what it can prove # nothing requires, and refuses any policy entry the graph says IS reached. node "$SRC/releases/prune-unreachable-npm.mjs" ../.. + # bcrypt and argon2 publish no win32-ia32 prebuild, so the rebuild above + # must have COMPILED both, and accounts-password imports them with no + # fallback. A cross-build that quietly did nothing still zips and passes + # 7z t, and only fails at the first sign-in - so read the binaries. + node "$SRC/releases/check-addon-arch.mjs" ../.. ia32 bcrypt argon2 - name: Check the binaries the win32 bundle needs exist if: steps.preflight.outputs.skip != 'true' diff --git a/releases/check-addon-arch.mjs b/releases/check-addon-arch.mjs new file mode 100644 index 0000000000..7eb033427d --- /dev/null +++ b/releases/check-addon-arch.mjs @@ -0,0 +1,162 @@ +#!/usr/bin/env node +// Check that a Windows bundle's native addons are built for its own CPU. +// +// node releases/check-addon-arch.mjs [package ...] +// +// Why. The win32 bundle is assembled on a 64-bit runner from the amd64 bundle, +// and its addons (bcrypt and argon2, which Meteor's accounts-password imports +// with no fallback) are cross-compiled with npm_config_arch=ia32. If any step +// of that quietly does nothing - a skipped rebuild, a nodedir node-gyp did not +// use - the zip still builds, still passes `7z t`, and ships a 64-bit or Linux +// .node that a 32-bit node.exe cannot load. Nobody would see it until the +// first person tried to sign in. So this reads the binary itself. +// +// What it checks. Every *.node outside a prebuilds/ directory is what Node's +// require() or node-gyp-build's build/Release lookup loads, so each must be a +// PE file for the wanted machine. prebuilds/ holds one directory per platform +// and node-gyp-build opens only the matching one, so other platforms' files +// there are expected and ignored. Each package named on the command line must +// have at least one loadable addon for the wanted CPU, in build output or in +// its own prebuilds/win32-/. +// +// A package whose package.json `os` or `cpu` excludes this target is skipped +// as well, by the same rule npm itself applies: the amd64 bundle carries +// platform packages such as @img/sharp-linux-x64 (os: linux), which their +// parent package only ever loads on that platform. + +import { readdirSync, openSync, readSync, closeSync, statSync, readFileSync, existsSync } from 'node:fs'; +import { join, relative, sep, resolve, dirname } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +export const PE_MACHINE = { ia32: 0x014c, x64: 0x8664, arm64: 0xaa64 }; + +// The binary format and, for PE, its machine field. +export function readBinaryKind(file) { + const fd = openSync(file, 'r'); + try { + const head = Buffer.alloc(64); + const n = readSync(fd, head, 0, 64, 0); + if (n >= 4 && head.readUInt32BE(0) === 0x7f454c46) return { format: 'ELF' }; + if (n >= 4 && [0xcffaedfe, 0xcefaedfe, 0xcafebabe].includes(head.readUInt32BE(0))) { + return { format: 'Mach-O' }; + } + if (n < 64 || head.toString('latin1', 0, 2) !== 'MZ') return { format: 'unknown' }; + const peOffset = head.readUInt32LE(0x3c); + const pe = Buffer.alloc(6); + if (readSync(fd, pe, 0, 6, peOffset) < 6 || pe.toString('latin1', 0, 4) !== 'PE\0\0') { + return { format: 'unknown' }; + } + return { format: 'PE', machine: pe.readUInt16LE(4) }; + } finally { + closeSync(fd); + } +} + +// npm's os/cpu rule: a list excludes a value when it names it with "!", or +// when it names only positive values and this is not one of them. +export function listAllows(list, value) { + if (!Array.isArray(list) || list.length === 0) return true; + if (list.includes(`!${value}`)) return false; + const positive = list.filter((v) => !v.startsWith('!')); + return positive.length === 0 || positive.includes(value); +} + +// The package a file belongs to, if its package.json declares a platform +// this target is not: such a package is never loaded here. +function foreignPlatformPackage(bundle, file, arch) { + let dir = dirname(file); + while (dir.length >= bundle.length) { + const manifest = join(dir, 'package.json'); + if (existsSync(manifest)) { + try { + const pkg = JSON.parse(readFileSync(manifest, 'utf8')); + if (!listAllows(pkg.os, 'win32') || !listAllows(pkg.cpu, arch)) return relative(bundle, dir); + } catch { + // An unreadable manifest declares nothing. + } + return null; + } + if (dirname(dir) === dir) break; + dir = dirname(dir); + } + return null; +} + +function walk(dir, out = []) { + for (const e of readdirSync(dir, { withFileTypes: true })) { + const p = join(dir, e.name); + if (e.isDirectory()) walk(p, out); + else if (e.isFile() && e.name.endsWith('.node')) out.push(p); + } + return out; +} + +const describe = (k) => + k.format === 'PE' + ? `PE machine 0x${k.machine.toString(16).padStart(4, '0')}` + : k.format; + +export function checkAddonArch(bundle, arch, packages = []) { + const want = PE_MACHINE[arch]; + if (!want) throw new Error(`unknown arch ${arch}; expected one of ${Object.keys(PE_MACHINE).join(', ')}`); + const errors = []; + const good = []; + const skipped = []; + const files = walk(bundle); + for (const f of files) { + const foreign = foreignPlatformPackage(bundle, f, arch); + if (foreign) { + skipped.push(relative(bundle, f)); + continue; + } + const parts = relative(bundle, f).split(sep); + const pi = parts.lastIndexOf('prebuilds'); + const kind = readBinaryKind(f); + const ok = kind.format === 'PE' && kind.machine === want; + if (pi === -1) { + if (ok) good.push(f); + else errors.push(`${relative(bundle, f)} is ${describe(kind)}, not a ${arch} Windows addon`); + } else if (parts[pi + 1] === `win32-${arch}`) { + if (ok) good.push(f); + else errors.push(`${relative(bundle, f)} is ${describe(kind)}, in the ${arch} prebuilds`); + } + } + for (const name of packages) { + // Every copy of the package in the bundle, by its node_modules/ path. + const dirs = new Set( + files + .map((f) => relative(bundle, f).split(sep)) + .map((parts) => { + for (let i = parts.length - 2; i >= 0; i--) { + if (parts[i] === name && parts[i - 1] === 'node_modules') return parts.slice(0, i + 1).join(sep); + } + return null; + }) + .filter(Boolean), + ); + if (dirs.size === 0) { + errors.push(`no native addon of ${name} is in the bundle at all`); + continue; + } + for (const d of dirs) { + if (!good.some((g) => relative(bundle, g).startsWith(d + sep))) { + errors.push(`${d} has no ${arch} Windows addon to load`); + } + } + } + return { errors, good: good.map((g) => relative(bundle, g)), skipped }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + const [bundle, arch, ...packages] = process.argv.slice(2); + if (!bundle || !arch || !statSync(bundle, { throwIfNoEntry: false })?.isDirectory()) { + console.error('usage: check-addon-arch.mjs [package ...]'); + process.exit(2); + } + const { errors, good, skipped } = checkAddonArch(bundle, arch, packages); + for (const g of good) console.log(`ok ${g}`); + for (const s of skipped) console.log(`-- ${s} (its package is for another platform)`); + for (const e of errors) console.log(`::error::${e}`); + if (errors.length) process.exit(1); + console.log(`check-addon-arch: ${good.length} ${arch} addon(s), all loadable by a ${arch} node.exe.`); +} diff --git a/tests/win32BundleBuild.test.cjs b/tests/win32BundleBuild.test.cjs new file mode 100644 index 0000000000..e2b35f6cfe --- /dev/null +++ b/tests/win32BundleBuild.test.cjs @@ -0,0 +1,225 @@ +'use strict'; +(async () => { + +// Plain-Node guard for the win32 bundle job. +// Run: node tests/win32BundleBuild.test.cjs +// +// build-win32 was skipped every release until the Node.js resolver learned +// node-patches' Windows checksum name, so the first release to run it, v12.32, +// was the first to reach its later steps - and it died on the first new one: +// +// tar: D\:\a\\_temp/node-ia32: Cannot open: No such file or directory +// +// RUNNER_TEMP is a Windows path, and GNU tar reads `D:` as a REMOTE HOST. The +// job now hands tar only relative names on the POSIX form of the path. +// +// The next step it had never reached was just as untested: bcrypt and argon2 +// publish no win32-ia32 prebuild, so they must be compiled, and +// accounts-password imports both with no fallback. releases/check-addon-arch.mjs +// reads each shipped addon's PE header so that a cross-build that silently did +// nothing fails the job instead of the first sign-in. + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const ROOT = path.join(__dirname, '..'); +const read = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8'); +const { checkAddonArch, readBinaryKind, listAllows, PE_MACHINE } = await import( + '../releases/check-addon-arch.mjs' +); + +let passed = 0; +function test(name, fn) { + fn(); + passed += 1; + console.log(' ok -', name); +} + +// ── workflow helpers ─────────────────────────────────────────────────────── +const code = (text) => text.split('\n').filter((l) => !/^\s*#/.test(l)).join('\n'); +function jobs(workflow) { + const out = {}; + const re = /\n ([a-z0-9-]+):\n/g; + const starts = []; + let m; + while ((m = re.exec(workflow))) starts.push({ name: m[1], at: m.index }); + starts.forEach((s, i) => { + out[s.name] = workflow.slice(s.at, i + 1 < starts.length ? starts[i + 1].at : undefined); + }); + return out; +} +const workflows = fs + .readdirSync(path.join(ROOT, '.github/workflows')) + .filter((f) => /\.ya?ml$/.test(f)) + .map((f) => ({ f, text: read(`.github/workflows/${f}`) })); +const windowsJobs = workflows.flatMap(({ f, text }) => + Object.entries(jobs(text)) + .filter(([, body]) => /runs-on:\s*windows/.test(body)) + .map(([name, body]) => ({ f, name, body: code(body) })), +); +const win32 = windowsJobs.find((j) => j.name === 'build-win32'); + +console.log('win32BundleBuild:'); + +test('there are Windows jobs to check, build-win32 among them', () => { + assert.ok(windowsJobs.length >= 3, `found ${windowsJobs.length} Windows jobs`); + assert.ok(win32, 'release-all.yml has a build-win32 job on a Windows runner'); +}); + +test('build-win32 gives tar no drive-letter path', () => { + assert.ok(/ND="\$\(cygpath -u "\$RUNNER_TEMP"\)\/node-ia32"/.test(win32.body), + 'the nodedir is built on the POSIX form of RUNNER_TEMP'); + assert.ok(/\(cd "\$ND" && tar -xzf node-headers\.tar\.gz --strip-components=1/.test(win32.body), + 'tar extracts by relative name inside the nodedir'); + assert.ok(/test -f "\$ND\/include\/node\/node\.h"/.test(win32.body), + 'and the headers are checked to have arrived'); + assert.ok(/export npm_config_nodedir="\$\(cygpath -w "\$ND"\)"/.test(win32.body), + 'node-gyp gets the Windows form of the nodedir'); +}); + +// Negative, and for every Windows job: no tar line may name RUNNER_TEMP or +// GITHUB_WORKSPACE, or a variable assigned from them without cygpath -u. +test('no Windows job hands tar a Windows path', () => { + for (const job of windowsJobs) { + const windowsVars = [...job.body.matchAll(/\b([A-Z_][A-Z0-9_]*)="?\$\{?(?:RUNNER_TEMP|GITHUB_WORKSPACE)\b/g)] + .map((m) => m[1]); + for (const line of job.body.split('\n').filter((l) => /\btar\s+-?[a-zA-Z]*[xc]/.test(l))) { + assert.ok(!/RUNNER_TEMP|GITHUB_WORKSPACE/.test(line), + `${job.f} ${job.name}: tar is given a Windows path: ${line.trim()}`); + for (const v of windowsVars) { + assert.ok(!new RegExp(`\\$\\{?${v}\\b`).test(line), + `${job.f} ${job.name}: tar is given $${v}, a Windows path: ${line.trim()}`); + } + } + } +}); + +test('build-win32 checks its addons after the rebuild and trims', () => { + const at = (s) => win32.body.indexOf(s); + const check = at('releases/check-addon-arch.mjs" ../.. ia32 bcrypt argon2'); + assert.ok(check !== -1, 'build-win32 runs check-addon-arch.mjs for ia32 bcrypt and argon2'); + assert.ok(at('npm-retry.sh" npm install') < check, 'after the rebuild'); + assert.ok(at('bundle-trim.mjs') < check && at('prune-unreachable-npm.mjs') < check, + 'and after everything that deletes files'); + assert.ok(check < at('Create win32 zip'), 'and before the zip is made'); +}); + +// ── check-addon-arch.mjs itself, on real PE/ELF headers ───────────────────── +function pe(machine) { + const b = Buffer.alloc(0x90); + b.write('MZ', 0, 'latin1'); + b.writeUInt32LE(0x80, 0x3c); + b.write('PE\0\0', 0x80, 'latin1'); + b.writeUInt16LE(machine, 0x84); + return b; +} +const ELF = Buffer.concat([Buffer.from([0x7f, 0x45, 0x4c, 0x46]), Buffer.alloc(60)]); + +function bundle(files) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'addon-arch-')); + for (const [rel, content] of Object.entries(files)) { + const f = path.join(dir, rel); + fs.mkdirSync(path.dirname(f), { recursive: true }); + fs.writeFileSync(f, typeof content === 'string' ? content : content); + } + return dir; +} +const AP = 'programs/server/npm/node_modules/meteor/accounts-password/node_modules'; +function withBundle(files, fn) { + const dir = bundle(files); + try { + fn(dir); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +test('the PE machine field is read, and ELF is told apart', () => { + withBundle({ 'a.node': pe(PE_MACHINE.ia32), 'b.node': pe(PE_MACHINE.x64), 'c.node': ELF }, (d) => { + assert.deepStrictEqual(readBinaryKind(path.join(d, 'a.node')), { format: 'PE', machine: 0x014c }); + assert.deepStrictEqual(readBinaryKind(path.join(d, 'b.node')), { format: 'PE', machine: 0x8664 }); + assert.deepStrictEqual(readBinaryKind(path.join(d, 'c.node')), { format: 'ELF' }); + }); +}); + +test('compiled ia32 bcrypt and argon2 pass', () => { + withBundle({ + [`${AP}/bcrypt/build/Release/bcrypt_lib.node`]: pe(PE_MACHINE.ia32), + [`${AP}/bcrypt/prebuilds/win32-x64/bcrypt.node`]: pe(PE_MACHINE.x64), + [`${AP}/argon2/build/Release/argon2.node`]: pe(PE_MACHINE.ia32), + [`${AP}/argon2/prebuilds/linux-x64/argon2.glibc.node`]: ELF, + }, (d) => { + const r = checkAddonArch(d, 'ia32', ['bcrypt', 'argon2']); + assert.deepStrictEqual(r.errors, []); + assert.strictEqual(r.good.length, 2); + }); +}); + +test('a matching prebuild counts, as node-gyp-build would load it', () => { + withBundle({ + [`${AP}/bcrypt/prebuilds/win32-ia32/bcrypt.node`]: pe(PE_MACHINE.ia32), + }, (d) => assert.deepStrictEqual(checkAddonArch(d, 'ia32', ['bcrypt']).errors, [])); +}); + +// Negative: what the job shipped if the cross-build quietly did nothing. +test('only the x64 prebuilds - no ia32 build - fails for each package', () => { + withBundle({ + [`${AP}/bcrypt/prebuilds/win32-x64/bcrypt.node`]: pe(PE_MACHINE.x64), + [`${AP}/argon2/prebuilds/win32-x64/argon2.glibc.node`]: pe(PE_MACHINE.x64), + }, (d) => { + const { errors } = checkAddonArch(d, 'ia32', ['bcrypt', 'argon2']); + assert.strictEqual(errors.length, 2); + assert.ok(errors.every((e) => /has no ia32 Windows addon to load/.test(e))); + }); +}); + +test('a build for the wrong CPU, or a Linux one, is refused', () => { + withBundle({ [`${AP}/bcrypt/build/Release/bcrypt_lib.node`]: pe(PE_MACHINE.x64) }, (d) => { + assert.ok(checkAddonArch(d, 'ia32', ['bcrypt']).errors.some((e) => /PE machine 0x8664/.test(e))); + }); + withBundle({ [`${AP}/argon2/build/Release/argon2.node`]: ELF }, (d) => { + assert.ok(checkAddonArch(d, 'ia32', ['argon2']).errors.some((e) => /is ELF/.test(e))); + }); + withBundle({ [`${AP}/bcrypt/prebuilds/win32-ia32/bcrypt.node`]: pe(PE_MACHINE.x64) }, (d) => { + assert.ok(checkAddonArch(d, 'ia32', []).errors.some((e) => /in the ia32 prebuilds/.test(e))); + }); +}); + +test('a package missing from the bundle is reported, not passed', () => { + withBundle({ 'programs/server/x.txt': 'x' }, (d) => { + assert.deepStrictEqual(checkAddonArch(d, 'ia32', ['argon2']).errors, + ['no native addon of argon2 is in the bundle at all']); + }); +}); + +test("another platform's package is skipped, by npm's os/cpu rule", () => { + withBundle({ + 'programs/server/npm/node_modules/@img/sharp-linux-x64/package.json': + JSON.stringify({ name: '@img/sharp-linux-x64', os: ['linux'], cpu: ['x64'] }), + 'programs/server/npm/node_modules/@img/sharp-linux-x64/lib/sharp.node': ELF, + 'programs/server/npm/node_modules/@img/sharp-win32-x64/package.json': + JSON.stringify({ name: '@img/sharp-win32-x64', os: ['win32'], cpu: ['x64'] }), + 'programs/server/npm/node_modules/@img/sharp-win32-x64/lib/sharp.node': pe(PE_MACHINE.x64), + }, (d) => { + const r = checkAddonArch(d, 'ia32', []); + assert.deepStrictEqual(r.errors, []); + assert.strictEqual(r.skipped.length, 2); + }); + // ...but a package that claims this platform is checked like any other. + withBundle({ + 'programs/server/npm/node_modules/fake/package.json': JSON.stringify({ os: ['win32'], cpu: ['ia32'] }), + 'programs/server/npm/node_modules/fake/fake.node': pe(PE_MACHINE.x64), + }, (d) => assert.strictEqual(checkAddonArch(d, 'ia32', []).errors.length, 1)); + assert.strictEqual(listAllows(undefined, 'win32'), true); + assert.strictEqual(listAllows(['linux'], 'win32'), false); + assert.strictEqual(listAllows(['!linux'], 'win32'), true); + assert.strictEqual(listAllows(['!win32'], 'win32'), false); +}); + +console.log(`\nwin32BundleBuild: all ${passed} tests passed`); +})().catch((err) => { + console.error(err); + process.exit(1); +});