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
21 changes: 20 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
os: [ubuntu-22.04, ubuntu-22.04-arm, macos-15, macos-15-intel]
node: [22, 24]
steps:
- name: Check out
Expand All @@ -58,6 +58,25 @@ jobs:
- name: Packed install smoke test
run: npm run test:package

windows-refusal:
name: Windows unsupported writes and pure logic on Node ${{ matrix.node }}
runs-on: windows-2022
timeout-minutes: 10
strategy:
matrix:
node: [22, 24]
steps:
- name: Check out
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- name: Set up Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: ${{ matrix.node }}
- name: Verify no-write refusal and platform-independent behavior
run: node --test test/unsupported-filesystem.test.js test/args.test.js test/origin.test.js test/action-help.test.js test/style.test.js test/trace-contract.test.js

python:
name: Python ${{ matrix.python }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
Expand Down
137 changes: 137 additions & 0 deletions .github/workflows/native-helpers.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
name: Verify native helpers

on:
workflow_dispatch:
pull_request:
paths:
- native/**
- src/**
- test/**
- package.json
- .github/workflows/native-helpers.yml

permissions:
contents: read

jobs:
build:
name: Build and verify ${{ matrix.target }}
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
include:
- { os: macos-15, target: darwin-arm64 }
- { os: macos-15-intel, target: darwin-x64 }
- { os: ubuntu-22.04, target: linux-x64 }
- { os: ubuntu-22.04-arm, target: linux-arm64 }
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
- name: Compile first-party helper for this host
env:
TARGET: ${{ matrix.target }}
run: |
node -e 'if (`${process.platform}-${process.arch}` !== process.env.TARGET) process.exit(1)'
node native/build.mjs --output "$RUNNER_TEMP/helper" --revision "$GITHUB_SHA"
node native/install-artifact.mjs --input "$RUNNER_TEMP/helper" --revision "$GITHUB_SHA"
- name: Verify source and packaged behavior
run: |
npm test
npm run test:package
- name: Upload only verified executable and identity metadata
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: native-helper-${{ matrix.target }}
path: |
${{ runner.temp }}/helper/bin/*
${{ runner.temp }}/helper/manifest.json
${{ runner.temp }}/helper/provenance.json
if-no-files-found: error
retention-days: 14

runtime:
name: Prebuilt ${{ matrix.target }} on Node ${{ matrix.node }}
needs: build
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
include:
- { os: macos-15, target: darwin-arm64, node: 22 }
- { os: macos-15, target: darwin-arm64, node: 24 }
- { os: macos-15-intel, target: darwin-x64, node: 22 }
- { os: macos-15-intel, target: darwin-x64, node: 24 }
- { os: ubuntu-22.04, target: linux-x64, node: 22 }
- { os: ubuntu-22.04, target: linux-x64, node: 24 }
- { os: ubuntu-22.04-arm, target: linux-arm64, node: 22 }
- { os: ubuntu-22.04-arm, target: linux-arm64, node: 24 }
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: ${{ matrix.node }}
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: native-helper-${{ matrix.target }}
path: ${{ runner.temp }}/helper
- name: Verify and install the prebuilt artifact
run: node native/install-artifact.mjs --input "$RUNNER_TEMP/helper" --revision "$GITHUB_SHA"
- name: Exercise the prebuilt helper on the target runtime
run: |
npm test
npm run test:package

windows-refusal:
name: Windows refusal and pure logic on Node ${{ matrix.node }}
runs-on: windows-2022
timeout-minutes: 10
strategy:
matrix:
node: [22, 24]
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: ${{ matrix.node }}
- name: Verify unsupported writes and platform-independent behavior
run: node --test test/unsupported-filesystem.test.js test/args.test.js test/origin.test.js test/action-help.test.js test/style.test.js test/trace-contract.test.js

assemble:
name: Assemble the verified platform bundle
needs: [build, runtime, windows-refusal]
runs-on: ubuntu-22.04
timeout-minutes: 10
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
pattern: native-helper-*
path: ${{ runner.temp }}/inputs
- name: Enforce exact target, source revision and byte digests
run: node native/aggregate.mjs --input "$RUNNER_TEMP/inputs" --revision "$GITHUB_SHA" --output "$RUNNER_TEMP/verified"
- name: Upload only the complete tested bundle
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: native-helper-bundle
path: |
${{ runner.temp }}/verified/bin/*
${{ runner.temp }}/verified/manifest.json
${{ runner.temp }}/verified/provenance.json
if-no-files-found: error
retention-days: 14
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,24 @@ script must not change with the `latest` tag. Previews use the `next` tag.
| | Supported |
| --- | --- |
| Node.js | 22 and 24 |
| Operating systems | Linux, macOS and Windows, each tested in CI |
| Automatic file writes | macOS arm64, using the bundled filesystem helper |
| Other operating systems and architectures | Automatic writes refuse until a verified helper is bundled |
| Runtime dependencies | None |
| Service | Hosted Metergraph, or a self-hosted deployment (see [Deployments](#deployments)) |

Automatic writes use a first-party helper shipped in the npm package. Installation
does not download a helper or invoke a compiler. The CLI verifies its packaged
SHA-256 digest before starting it and refuses filesystem access if it is missing,
altered, or unavailable for the current platform. The helper retains directory
handles for reads, locks, replacement, rollback, and cleanup, so renaming a project
directory cannot redirect writes into a substituted directory.

This candidate includes a macOS arm64 build only. Linux and Windows automatic
writes are unavailable; Windows needs a native handle and ACL backend before it
can be enabled. Platform and runtime validation must pass before a release adds
another binary. Existing read-only commands that do not need the local store
remain available.

Sign in needs a service that offers Metadata-only CLI grants and grant revocation; a
service without them is reported as unsupported, and the CLI never falls back to
broader access. `setup` also needs the deployment's ingest bootstrap API and approval by
Expand Down
85 changes: 85 additions & 0 deletions native/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Directory capability helper

`anchored-fs.c` is a first-party filesystem helper used only through inherited
anonymous pipes. It retains directory descriptors and traverses each basename
with `openat(O_DIRECTORY | O_NOFOLLOW)`. Mutation uses `mkdirat`, `renameat`,
`linkat`, and `unlinkat` relative to retained parents. Reads and permission
changes use opened descriptors. Requests and responses are limited to 2 MiB;
paths, contents, and errors are not logged. Secrets never appear in arguments.

`src/anchored-fs.js` verifies the selected shipped binary against `manifest.json`
before starting it. Missing artifacts, altered bytes, unsupported open modes,
and unavailable synchronous pipes fail closed. It never downloads a helper or
runs a compiler. `node native/build.mjs` is a developer/release-only build.

## Current verification matrix

| Target | Artifact | Verification |
| --- | --- | --- |
| macOS arm64/x64 | shipped in `bin/` | source and prebuilt package tests on Node 22/24 |
| Linux arm64/x64 | shipped in `bin/` | source and prebuilt package tests on Node 22/24, Ubuntu 22.04 |
| Windows arm64/x64 | absent | refuses secure filesystem operations |

This is not a completed multi-platform release. Windows requires a separate
handle-relative implementation and restrictive DACL creation before token bytes
are written; POSIX operations are not emulated through Windows pathname APIs.
Windows refusal tests cover Node 22/24; functional Windows installation remains
unavailable. The final package head must still pass its complete CI matrix.

The shipped POSIX artifacts come from successful workflow run
[`39881339298`](https://github.com/metergraph/cli/actions/runs/39881339298).
Their exact reviewed merge revision and C source digest are recorded in
`provenance.json`; `manifest.json` binds each executable's bytes.

## Producing the platform bundle

The `Verify native helpers` workflow builds macOS arm64/x64 and Linux arm64/x64
on their own hosted runners. Each executable runs the source and packed-package
tests before upload. Separate jobs download the same executable and run both
suites on Node 22 and 24. The packed-package test runs installation with an empty
tool search path, proving consumers need no compiler or download tool. Windows
jobs run platform-independent tests and explicit no-write refusals; they do not
claim functional Windows installation support.

Each single-target artifact contains only `bin/<allowlisted-name>`,
`manifest.json`, and `provenance.json`. Provenance names the exact source commit,
the C source hash, target, and executable hash. Assembly waits for every platform
and runtime test to pass, verifies an exact four-target allowlist and all hashes,
and refuses unknown files, links, duplicate JSON keys, missing/duplicate targets,
or another source revision before writing output. Only the completed
`native-helper-bundle` artifact is eligible for a release import.

Maintainers import artifacts from the reviewed workflow run and exact commit;
building alone does not establish platform support. After importing the verified
executables and manifest, rerun the ordinary CI and packed-package matrix against
the final release commit. Neither npm installation nor the runtime invokes these
development scripts. Linux artifacts are built on Ubuntu 22.04; compatibility
with older libc versions is not claimed.

The helper checks retained ancestry before pathname mutations. A stale ancestry
fails with `ESTALE`; explicit rollback mode still addresses retained parents.
Removal of an exclusively created temporary file, lock, or directory checks
its original owned identity; subsequent read-only observations cannot adopt an
attacker's replacement for cleanup. Final promoted files use the latest observed
identity so application compare-and-swap can accept a legitimate cross-process
refresh on its next transaction.
This protects descriptor containment across directory substitution. Existing
application locks and compare-and-swap checks remain necessary for transaction
semantics. POSIX `renameat` does not provide an atomic content-compare-and-replace
primitive, so concurrent same-user leaf changes between comparison and replacement
remain a separate limitation; this helper must not be described as providing
kernel-enforced compare-and-swap.

The protocol uses an operation byte, argument count, and big-endian length-prefixed
UTF-8 arguments, followed by an optional raw file-content payload. Replies carry
an errno and length-prefixed payload. Helper errors expose only fixed errno
names. The adapter deliberately permits only read, existing read/write, and
exclusive create opens. Every open includes `O_NOFOLLOW | O_NONBLOCK`; FIFOs and
other nonregular entries are refused without blocking. Numeric descriptor IDs
are private to this helper, represented as negative values in JavaScript.

The helper ignores SIGINT, SIGTERM, and SIGHUP so terminal process-group signals
cannot interrupt JavaScript transaction cleanup. Closing its inherited stdin
ends the helper; explicit adapter shutdown uses SIGKILL. Each helper is bounded
to 8,192 directory handles, file IDs, and observed entries; exhaustion refuses
operations instead of releasing or reopening pinned capabilities.
66 changes: 66 additions & 0 deletions native/aggregate.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Assemble already tested CI artifacts; this tool never builds or downloads.
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { TARGETS, DIGEST, REVISION, binaryFor, exactKeys, argumentsFor } from "./targets.mjs";
const root=path.dirname(fileURLToPath(import.meta.url));
const sha256=bytes=>createHash("sha256").update(bytes).digest("hex");
function stat(file,kind) {const value=fs.lstatSync(file);if(value.isSymbolicLink() || !(kind==="directory"?value.isDirectory():value.isFile()) || (kind!=="directory" && value.nlink!==1)) throw new Error("unsafe artifact entry");return value;}
function listing(dir,expected) {stat(dir,"directory");const names=fs.readdirSync(dir).sort();if(names.join("\0")!==[...expected].sort().join("\0"))throw new Error("unexpected artifact files");}
function json(file) {
stat(file,"file");const text=fs.readFileSync(file,"utf8");const value=JSON.parse(text);
// JSON.parse silently accepts repeated object keys. Reject them before
// trusting an artifact manifest or provenance record.
const frames=[];
for(const token of text.match(/"(?:[^"\\]|\\.)*"|[{}\[\],:]/gs) ?? []) {
if(token==="{")frames.push({object:true,keys:new Set(),key:true});
else if(token==="[")frames.push({object:false});
else if(token==="}" || token==="]")frames.pop();
else if(token==="," && frames.at(-1)?.object)frames.at(-1).key=true;
else if(token.startsWith('"') && frames.at(-1)?.object && frames.at(-1).key) {
const frame=frames.at(-1),key=JSON.parse(token);
if(frame.keys.has(key))throw new Error("duplicate artifact metadata key");
frame.keys.add(key);frame.key=false;
}
}
return value;
}
export function readArtifact(directory,{revision,sourceSha256}) {
if(!REVISION.test(revision) || !DIGEST.test(sourceSha256))throw new Error("invalid artifact source identity");
const dir=path.resolve(directory);listing(dir,["bin","manifest.json","provenance.json"]);
const provenance=json(path.join(dir,"provenance.json"));
if(!exactKeys(provenance,["schema","source_revision","source_sha256","target","binary_sha256"]) || provenance.schema!==1 || !TARGETS.includes(provenance.target))throw new Error("invalid artifact provenance");
const {target}=provenance;const name=binaryFor(target);
if(provenance.source_revision!==revision || provenance.source_sha256!==sourceSha256 || !DIGEST.test(provenance.binary_sha256))throw new Error("artifact source identity mismatch");
listing(path.join(dir,"bin"),[name]);const file=path.join(dir,"bin",name);stat(file,"file");
const bytes=fs.readFileSync(file);const digest=sha256(bytes);
const manifest=json(path.join(dir,"manifest.json"));
if(!exactKeys(manifest,["schema","artifacts"]) || manifest.schema!==1 || !exactKeys(manifest.artifacts,[name]) || manifest.artifacts[name]!==digest || provenance.binary_sha256!==digest)throw new Error("artifact digest mismatch");
return {target,name,binary:bytes,manifest,provenance,digest};
}
export function aggregate({input,revision,output}) {
if(!REVISION.test(revision))throw new Error("invalid reviewed revision");
input=path.resolve(input);output=path.resolve(output);stat(input,"directory");
const source=sha256(fs.readFileSync(path.join(root,"anchored-fs.c")));
const artifacts=new Map();const folders=fs.readdirSync(input);
if(folders.length!==TARGETS.length)throw new Error("missing or duplicate native targets");
for(const folder of folders) {
const artifact=readArtifact(path.join(input,folder),{revision,sourceSha256:source});
if(artifacts.has(artifact.target))throw new Error("duplicate native target");
artifacts.set(artifact.target,{name:artifact.name,bytes:artifact.binary,digest:artifact.digest});
}
if(TARGETS.some(target=>!artifacts.has(target)))throw new Error("missing native target");
// Validate every input before writing any assembled output.
if(fs.existsSync(output)) {stat(output,"directory");if(fs.readdirSync(output).length)throw new Error("assembly output must be empty");}
else fs.mkdirSync(output,{recursive:true});
fs.mkdirSync(path.join(output,"bin"));const manifest={schema:1,artifacts:{}};
for(const target of TARGETS) {const {name,bytes,digest}=artifacts.get(target);fs.writeFileSync(path.join(output,"bin",name),bytes,{flag:"wx",mode:0o755});fs.chmodSync(path.join(output,"bin",name),0o755);manifest.artifacts[name]=digest;}
fs.writeFileSync(path.join(output,"manifest.json"),`${JSON.stringify(manifest,null,2)}\n`,{flag:"wx"});
fs.writeFileSync(path.join(output,"provenance.json"),`${JSON.stringify({schema:1,source_revision:revision,source_sha256:source,targets:[...TARGETS]},null,2)}\n`,{flag:"wx"});
return manifest;
}
if(process.argv[1] && path.resolve(process.argv[1])===fileURLToPath(import.meta.url)) {
try {const args=argumentsFor(process.argv.slice(2),["--input","--revision","--output"]);aggregate({input:args["--input"],revision:args["--revision"],output:args["--output"]});}
catch(error) {process.stderr.write(`${error.message}\n`);process.exitCode=1;}
}
Loading
Loading