diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 57b0abc..75fdf7e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 @@ -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 }} diff --git a/.github/workflows/native-helpers.yml b/.github/workflows/native-helpers.yml new file mode 100644 index 0000000..236f293 --- /dev/null +++ b/.github/workflows/native-helpers.yml @@ -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 diff --git a/README.md b/README.md index fab22d7..5a426e3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/native/README.md b/native/README.md new file mode 100644 index 0000000..899c26a --- /dev/null +++ b/native/README.md @@ -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/`, +`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. diff --git a/native/aggregate.mjs b/native/aggregate.mjs new file mode 100644 index 0000000..bf177a1 --- /dev/null +++ b/native/aggregate.mjs @@ -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;} +} diff --git a/native/anchored-fs.c b/native/anchored-fs.c new file mode 100644 index 0000000..14b5f7a --- /dev/null +++ b/native/anchored-fs.c @@ -0,0 +1,243 @@ +#define _DARWIN_C_SOURCE +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Private, bounded pipe protocol. No paths or file contents are logged. All + * pathname lookups below the process root are relative to retained dirfds. + * This process has no network interface or arbitrary execution operation. */ +#define LIMIT (2 * 1024 * 1024) +#define MAX_HANDLES 8192 +#define STAT_BYTES (11 * 8) +/* Search permission is sufficient for *at traversal; acquiring a directory + * capability must not newly require directory-listing permission. */ +#if defined(O_SEARCH) +#define DIRECTORY_ACCESS O_SEARCH +#elif defined(O_PATH) +#define DIRECTORY_ACCESS O_PATH +#else +#error "No search-only directory capability API on this target" +#endif +struct directory { int fd, parent; char *path, *name; dev_t dev; ino_t ino; }; +static struct directory dirs[MAX_HANDLES]; +static int ndirs = 0, rollback_mode = 0; +struct entry { int parent; char *name; dev_t dev; ino_t ino; int owned; dev_t own_dev; ino_t own_ino; }; +static struct entry entries[MAX_HANDLES]; +static int nentries; +static int files[MAX_HANDLES]; +static int nfiles; +static int readall(int fd, void *data, size_t len) { + unsigned char *p=data; + while(len) { ssize_t n=read(fd,p,len); if(n<0 && errno==EINTR) continue; if(n<=0) return -1; p+=n; len-=n; } return 0; +} +static int writeall(int fd, const void *data, size_t len) { + const unsigned char *p=data; + while(len) { ssize_t n=write(fd,p,len); if(n<0 && errno==EINTR) continue; if(n<=0) return -1; p+=n; len-=n; } return 0; +} +static uint32_t get32(const unsigned char *p) { return (uint32_t)p[0]<<24 | (uint32_t)p[1]<<16 | (uint32_t)p[2]<<8 | p[3]; } +static void put32(unsigned char *p,uint32_t n) { p[0]=n>>24;p[1]=n>>16;p[2]=n>>8;p[3]=n; } +static void put64(unsigned char *p,uint64_t n) { for(int i=7;i>=0;i--) {p[i]=n&255;n>>=8;} } +static int reply(int error,const void *data,uint32_t len) { + unsigned char h[8]; put32(h,error);put32(h+4,len); + return writeall(1,h,8) || (len && writeall(1,data,len)); +} +static int basename_ok(const char *p) { return *p && strcmp(p,".") && strcmp(p,"..") && !strchr(p,'/'); } +static int current(int idx) { + if(idx==0) return 1; + struct directory *d=&dirs[idx]; struct stat s; + if(!current(d->parent)) return 0; + if(fstatat(dirs[d->parent].fd,d->name,&s,AT_SYMLINK_NOFOLLOW)<0) return 0; + return S_ISDIR(s.st_mode) && s.st_dev==d->dev && s.st_ino==d->ino; +} +static int remember(int parent,const char *name,const struct stat *s); +static int directory(const char *path) { + if(!path || path[0]!='/' || strlen(path)>=PATH_MAX) {errno=EINVAL;return -1;} + for(int i=0;i=0 && !strcmp(path,dirs[i].path)) return i; + if(!strcmp(path,"/")) return 0; + char *copy=strdup(path); if(!copy) return -1; + char *slash=strrchr(copy,'/'); char *name=strdup(slash+1); + if(!name || !basename_ok(name)) {free(copy);free(name);errno=EINVAL;return -1;} + if(slash==copy) slash[1]=0; else *slash=0; + int parent=directory(copy); free(copy); + if(parent<0) {free(name);return -1;} + int fd=openat(dirs[parent].fd,name,DIRECTORY_ACCESS|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC); + if(fd<0) {free(name);return -1;} + struct stat s; + if(fstat(fd,&s)<0 || !S_ISDIR(s.st_mode) || ndirs>=MAX_HANDLES) {close(fd);free(name);errno=EIO;return -1;} + /* A previous directory observation is a capability identity, not permission + * to adopt whatever object later occupies that spelling. */ + for(int i=0;i=PATH_MAX) {errno=EINVAL;return -1;} + char *copy=strdup(path); if(!copy) return -1; + char *slash=strrchr(copy,'/'); *name=strdup(slash+1); + if(!*name || !basename_ok(*name)) {free(copy);free(*name);*name=NULL;errno=EINVAL;return -1;} + if(slash==copy) slash[1]=0; else *slash=0; + int parent=directory(copy);free(copy);return parent; +} +static int mutable_parent(int idx) { if(idx<0)return 0; if(!rollback_mode && !current(idx)) {errno=ESTALE;return 0;} return 1; } +static int remember(int parent,const char *name,const struct stat *s) { + for(int i=0;ist_dev;entries[i].ino=s->st_ino;return 0; + } + if(nentries>=MAX_HANDLES) {errno=EMFILE;return -1;} + entries[nentries++]=(struct entry){parent,strdup(name),s->st_dev,s->st_ino,0,0,0};return 0; +} +static int own(int parent,const char *name,const struct stat *s) { + if(remember(parent,name,s)<0)return -1; + for(int i=0;ist_dev;entries[i].own_ino=s->st_ino;return 0;} + errno=EIO;return -1; +} +static int promote(int parent,const char *name,const struct stat *s) { + if(remember(parent,name,s)<0)return -1; + for(int i=0;ist_mtimespec, changed=s->st_ctimespec; +#else + struct timespec modified=s->st_mtim, changed=s->st_ctim; +#endif + /* Keep seconds and nanoseconds separate. Multiplying time_t by 1e9 here + * would overflow for timestamps which JavaScript BigInt can represent. */ + uint64_t fields[]={s->st_dev,s->st_ino,s->st_mode,s->st_nlink,s->st_uid,s->st_gid,s->st_size, + (uint64_t)modified.tv_sec,(uint64_t)modified.tv_nsec,(uint64_t)changed.tv_sec,(uint64_t)changed.tv_nsec}; + for(int i=0;i<11;i++)put64(out+i*8,fields[i]); +} +static int filefd(const char *s) { char *end;long n=strtol(s,&end,10); if(*end || n<0 || n>=nfiles || files[n]<0) {errno=EBADF;return -1;}return files[n]; } +int main(void) { + /* The JS owner defers termination until transaction cleanup completes. + * Group-delivered terminal signals must not revoke its live capabilities. + * Parent death closes stdin, so the loop exits without a signal handler. */ + signal(SIGINT,SIG_IGN);signal(SIGTERM,SIG_IGN);signal(SIGHUP,SIG_IGN); + int root=open("/",DIRECTORY_ACCESS|O_DIRECTORY|O_CLOEXEC);struct stat rs; + if(root<0 || fstat(root,&rs)<0)return 1; + dirs[ndirs++]=(struct directory){root,-1,strdup("/"),strdup(""),rs.st_dev,rs.st_ino}; + for(;;) { + unsigned char header[4]; if(readall(0,header,4))break; + uint32_t length=get32(header);if(length<2 || length>LIMIT) return 2; + unsigned char *request=malloc(length+1);if(!request)return 3; + if(readall(0,request,length)) {free(request);break;}request[length]=0; + int op=request[0],argc=request[1];char *args[8]={0};size_t pos=2;int malformed=argc>8; + for(int i=0;ilength) {malformed=1;break;} + uint32_t len=get32(request+pos);pos+=4; + if(pos+len>length || memchr(request+pos,0,len)) {malformed=1;break;} + args[i]=malloc(len+1);if(!args[i]) {malformed=1;break;} + memcpy(args[i],request+pos,len);args[i][len]=0;pos+=len; + } + int error=0; unsigned char out[STAT_BYTES];void *output=out;uint32_t outlen=0; + int parent=-1,fd=-1,result=-1;char *name=NULL;struct stat st; + errno=0; + if(malformed) error=EINVAL; + else switch(op) { + case 1: /* lstat: never follows the final entry */ + if(argc!=1) {error=EINVAL;break;} + if(!strcmp(args[0],"/")) result=fstat(root,&st); + else {parent=parent_for(args[0],&name);if(parent<0)break;result=fstatat(dirs[parent].fd,name,&st,AT_SYMLINK_NOFOLLOW);} + if(!result) { + if(S_ISDIR(st.st_mode)) { + int pinned=directory(args[0]);struct stat opened; + if(pinned<0) {result=-1;break;} + if(fstat(dirs[pinned].fd,&opened)<0 || opened.st_dev!=st.st_dev || opened.st_ino!=st.st_ino) {errno=ESTALE;result=-1;break;} + } + statbytes(out,&st);outlen=STAT_BYTES;if(parent>=0 && !S_ISLNK(st.st_mode))remember(parent,name,&st); + } + break; + case 2: /* open: protocol flags are independent of host constants */ + if(argc!=3) {error=EINVAL;break;} + parent=parent_for(args[0],&name);if(parent<0)break; + int kind=atoi(args[1]),flags=O_NOFOLLOW|O_CLOEXEC|O_NONBLOCK; + if(kind==0)flags|=O_RDONLY;else if(kind==1)flags|=O_RDWR;else if(kind==2)flags|=O_WRONLY|O_CREAT|O_EXCL;else {error=EINVAL;break;} + if(kind!=0 && !mutable_parent(parent))break; + fd=openat(dirs[parent].fd,name,flags,strtoul(args[2],NULL,10)&0777); + if(fd<0)break; + if(fstat(fd,&st)<0 || (!S_ISREG(st.st_mode) && !(kind==0 && S_ISDIR(st.st_mode))) || (S_ISREG(st.st_mode) && st.st_nlink!=1)) {close(fd);fd=-1;errno=ELOOP;break;} + if(nfiles>=MAX_HANDLES) {close(fd);errno=EMFILE;break;} + if((kind==2?own(parent,name,&st):remember(parent,name,&st))<0) {close(fd);break;} + put32(out,nfiles);outlen=4;files[nfiles++]=fd;result=0;break; + case 3: /* fstat */ + if(argc!=1) {error=EINVAL;break;}fd=filefd(args[0]);if(fd<0)break;result=fstat(fd,&st);if(!result){statbytes(out,&st);outlen=STAT_BYTES;}break; + case 4: /* bounded read from descriptor */ + if(argc!=1) {error=EINVAL;break;}fd=filefd(args[0]);if(fd<0)break; + if(fstat(fd,&st)<0)break; + if(!S_ISREG(st.st_mode) || st.st_size<0 || st.st_size>LIMIT) {errno=EFBIG;break;} + output=malloc(LIMIT+1);if(!output){errno=ENOMEM;break;} + size_t used=0;ssize_t got; + while(used0)used+=got; + if(got<0){break;}outlen=used;result=0;break; + case 5: /* write payload */ + if(argc!=1) {error=EINVAL;break;}fd=filefd(args[0]);if(fd<0)break;result=writeall(fd,request+pos,length-pos);break; + case 6: + if(argc!=2) {error=EINVAL;break;}fd=filefd(args[0]);if(fd<0)break;result=fchmod(fd,strtoul(args[1],NULL,10)&0777);break; + case 7: + if(argc!=1) {error=EINVAL;break;}fd=filefd(args[0]);if(fd<0)break;result=fsync(fd);break; + case 8: + if(argc!=1) {error=EINVAL;break;}fd=filefd(args[0]);if(fd<0)break;result=close(fd);files[atoi(args[0])]=-1;break; + case 9: /* mkdir one basename */ + if(argc!=2) {error=EINVAL;break;}parent=parent_for(args[0],&name);if(!mutable_parent(parent))break; + result=mkdirat(dirs[parent].fd,name,strtoul(args[1],NULL,10)&0777); + if(!result && !fstatat(dirs[parent].fd,name,&st,AT_SYMLINK_NOFOLLOW)) {own(parent,name,&st);} + break; + case 10: /* rename, anchored at both parents */ + if(argc!=2) {error=EINVAL;break;}parent=parent_for(args[0],&name);if(!mutable_parent(parent) || expected(parent,name,1)<0)break; + char *destname=NULL;int dest=parent_for(args[1],&destname); + if(mutable_parent(dest)) { + if(!fstatat(dirs[dest].fd,destname,&st,AT_SYMLINK_NOFOLLOW) && (S_ISLNK(st.st_mode) || !S_ISREG(st.st_mode) || st.st_nlink!=1 || expected(dest,destname,0)<0)) {errno=ESTALE;} + else { result=renameat(dirs[parent].fd,name,dirs[dest].fd,destname);if(!result && !fstatat(dirs[dest].fd,destname,&st,AT_SYMLINK_NOFOLLOW))promote(dest,destname,&st); } + }free(destname);break; + case 11: case 12: /* unlink/rmdir only an object previously observed */ + if(argc!=1) {error=EINVAL;break;}parent=parent_for(args[0],&name);if(!mutable_parent(parent) || expected(parent,name,1)<0)break; + result=unlinkat(dirs[parent].fd,name,op==12?AT_REMOVEDIR:0); + if(!result && op==12) for(int i=1;i=0) {close(dirs[i].fd);dirs[i].fd=-1;} + break; + case 13: /* validate existing directory ancestry */ + if(argc!=1) {error=EINVAL;break;}parent=directory(args[0]);if(parent<0)break; + if(current(parent))result=0;else errno=ESTALE;break; + case 15: /* exclusive hardlink promotion, never follows source */ + if(argc!=2) {error=EINVAL;break;}parent=parent_for(args[0],&name);if(!mutable_parent(parent) || expected(parent,name,1)<0)break; + char *linkname=NULL;int linkparent=parent_for(args[1],&linkname); + if(mutable_parent(linkparent)) {result=linkat(dirs[parent].fd,name,dirs[linkparent].fd,linkname,0);if(!result && !fstatat(dirs[linkparent].fd,linkname,&st,AT_SYMLINK_NOFOLLOW))promote(linkparent,linkname,&st);}free(linkname);break; + case 16: /* positional bounded read */ + if(argc!=3) {error=EINVAL;break;}fd=filefd(args[0]);if(fd<0)break; + size_t amount=strtoul(args[1],NULL,10);if(amount>LIMIT){error=EFBIG;break;} + output=malloc(amount?amount:1);if(!output){error=ENOMEM;break;} + ssize_t count=pread(fd,output,amount,strtoll(args[2],NULL,10));if(count>=0){outlen=count;result=0;}break; + case 14: + if(argc!=1 || (strcmp(args[0],"0") && strcmp(args[0],"1"))) {error=EINVAL;break;}rollback_mode=atoi(args[0]);result=0;break; + default:error=EINVAL; + } + if(!error && result<0)error=errno?errno:EIO; + if(reply(error,error?NULL:output,error?0:outlen))return 4; + if(output!=out)free(output); + free(name);for(int i=0;i createHash("sha256").update(bytes).digest("hex"); +function directory(dir) { + fs.mkdirSync(dir, {recursive:true}); + if (!fs.lstatSync(dir).isDirectory() || fs.lstatSync(dir).isSymbolicLink()) throw new Error("unsafe build output"); +} +export function build({output, revision, target = `${process.platform}-${process.arch}`} = {}) { + if (!TARGETS.includes(target) || target !== `${process.platform}-${process.arch}`) throw new Error("unsupported build host"); + if (revision === undefined) { + revision = process.env.GITHUB_SHA; + if (revision === undefined) { + const git = spawnSync("git", ["rev-parse", "HEAD"], {cwd:root, encoding:"utf8"}); + if (git.status !== 0) throw new Error("source revision unavailable"); + revision = git.stdout.trim(); + } + } + if (!REVISION.test(revision)) throw new Error("invalid source revision"); + const provenanceOutput = output !== undefined; + output = path.resolve(output ?? root); directory(output); directory(path.join(output,"bin")); + const manifestPath = path.join(output,"manifest.json"); + let artifacts = {}; + if (fs.existsSync(manifestPath)) { + if (!fs.lstatSync(manifestPath).isFile() || fs.lstatSync(manifestPath).isSymbolicLink()) throw new Error("unsafe build manifest"); + const previous = JSON.parse(fs.readFileSync(manifestPath,"utf8")); + if (!exactKeys(previous,["schema","artifacts"]) || previous.schema !== 1 || !exactKeys(previous.artifacts,Object.keys(previous.artifacts ?? {}))) throw new Error("invalid build manifest"); + for (const [name,digest] of Object.entries(previous.artifacts)) { + if (!TARGETS.some(value=>binaryFor(value)===name) || !DIGEST.test(digest)) throw new Error("unknown build artifact"); + const file=path.join(output,"bin",name);const stat=fs.lstatSync(file); + if (!stat.isFile() || stat.isSymbolicLink() || sha256(fs.readFileSync(file)) !== digest) throw new Error("existing artifact integrity failed"); + artifacts[name]=digest; + } + } + const name = binaryFor(target); const temporary = path.join(output,"bin",`.build-${randomBytes(12).toString("hex")}`); + try { + const result = spawnSync("clang", ["-std=c11", "-Wall", "-Wextra", "-Werror", "-O2", path.join(root,"anchored-fs.c"), "-o",temporary], {stdio:"inherit"}); + if (result.status !== 0) throw new Error("native compilation failed"); + fs.chmodSync(temporary,0o755); + const digest = sha256(fs.readFileSync(temporary)); fs.renameSync(temporary,path.join(output,"bin",name)); artifacts[name]=digest; + const ordered = Object.fromEntries(Object.entries(artifacts).sort(([a],[b])=>a.localeCompare(b))); + fs.writeFileSync(manifestPath,`${JSON.stringify({schema:1,artifacts:ordered},null,2)}\n`); + if (provenanceOutput) fs.writeFileSync(path.join(output,"provenance.json"),`${JSON.stringify({schema:1,source_revision:revision,source_sha256:sha256(fs.readFileSync(path.join(root,"anchored-fs.c"))),target,binary_sha256:digest},null,2)}\n`); + return {target,digest}; + } finally {try {fs.unlinkSync(temporary);} catch(error) {if(error.code!=="ENOENT")throw error;} } +} +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + try {const args=argumentsFor(process.argv.slice(2),[],["--output","--revision"]);build({output:args["--output"],revision:args["--revision"]});} + catch(error) {process.stderr.write(`${error.message}\n`);process.exitCode=1;} +} diff --git a/native/install-artifact.mjs b/native/install-artifact.mjs new file mode 100644 index 0000000..5a00f57 --- /dev/null +++ b/native/install-artifact.mjs @@ -0,0 +1,21 @@ +// CI-only: install one artifact from this workflow's reviewed source revision +// into an ephemeral checkout for source and packed-package execution tests. +import fs from "node:fs"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { fileURLToPath } from "node:url"; +import { readArtifact } from "./aggregate.mjs"; +import { argumentsFor } from "./targets.mjs"; + +const root = path.dirname(fileURLToPath(import.meta.url)); +const args = argumentsFor(process.argv.slice(2), ["--input", "--revision"]); +const sourceSha256 = createHash("sha256").update(fs.readFileSync(path.join(root, "anchored-fs.c"))).digest("hex"); +const artifact = readArtifact(args["--input"], { revision: args["--revision"], sourceSha256 }); +if (artifact.target !== `${process.platform}-${process.arch}`) throw new Error("artifact does not match the execution host"); +// Validation precedes mutation. Retain only the selected target in this +// disposable checkout so package allowlist checks see exactly these bytes. +fs.rmSync(path.join(root, "bin"), { recursive: true, force: true }); +fs.mkdirSync(path.join(root, "bin")); +fs.writeFileSync(path.join(root, "bin", artifact.name), artifact.binary, { flag: "wx", mode: 0o755 }); +fs.chmodSync(path.join(root, "bin", artifact.name), 0o755); +fs.writeFileSync(path.join(root, "manifest.json"), `${JSON.stringify(artifact.manifest, null, 2)}\n`); diff --git a/native/manifest.json b/native/manifest.json new file mode 100644 index 0000000..73a4750 --- /dev/null +++ b/native/manifest.json @@ -0,0 +1,9 @@ +{ + "schema": 1, + "artifacts": { + "anchored-fs-darwin-arm64": "787a6d122add60a261fc6c70717f270825af3be7512d7dea4104f608293370b6", + "anchored-fs-darwin-x64": "f569e48393b0650a93c8aaf2ef8984fd0dbf90e33f51d847db3c629a7c8fbd38", + "anchored-fs-linux-arm64": "6ac3eca79a8211a32dfd76eebeffe0b4b4e6d1540bacad739856b9c91094b308", + "anchored-fs-linux-x64": "401e2fd89ca15cd9d68c4e5077ca08a9caf0fe93434a0b243a361845b1284533" + } +} diff --git a/native/provenance.json b/native/provenance.json new file mode 100644 index 0000000..48de4d5 --- /dev/null +++ b/native/provenance.json @@ -0,0 +1,11 @@ +{ + "schema": 1, + "source_revision": "8605aa17f7a20d986e027775ab4f652c9b725b17", + "source_sha256": "44eb6d363823b63ab1090ff92970666d6c9e9c8d525ab4e1ddfa1a376c31c7f6", + "targets": [ + "darwin-arm64", + "darwin-x64", + "linux-arm64", + "linux-x64" + ] +} diff --git a/native/targets.mjs b/native/targets.mjs new file mode 100644 index 0000000..6bbfe62 --- /dev/null +++ b/native/targets.mjs @@ -0,0 +1,24 @@ +// Build and release allowlist. Presence here is not evidence of verification; +// CI must execute the compiled helper on each declared host before assembly. +export const TARGETS = Object.freeze(["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"]); +export const BINARY_PREFIX = "anchored-fs-"; +export const REVISION = /^[0-9a-f]{40}$/; +export const DIGEST = /^[0-9a-f]{64}$/; +export function binaryFor(target) { + if (!TARGETS.includes(target)) throw new Error("unsupported native target"); + return `${BINARY_PREFIX}${target}`; +} +export function exactKeys(value, keys) { + return value !== null && typeof value === "object" && !Array.isArray(value) && + Object.keys(value).sort().join() === [...keys].sort().join(); +} +export function argumentsFor(argv, required, optional = []) { + const allowed = new Set([...required, ...optional]); const result = {}; + for (let i = 0; i < argv.length; i += 2) { + const name = argv[i]; const value = argv[i + 1]; + if (!allowed.has(name) || Object.hasOwn(result, name) || typeof value !== "string" || value === "" || value.startsWith("--")) throw new Error("invalid build arguments"); + result[name] = value; + } + if (required.some(name => !Object.hasOwn(result, name))) throw new Error("missing build arguments"); + return result; +} diff --git a/package.json b/package.json index 00d1a79..11a3064 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,12 @@ "files": [ "bin/metergraph.js", "src/*.js", + "native/anchored-fs.c", + "native/build.mjs", + "native/targets.mjs", + "native/manifest.json", + "native/README.md", + "native/bin/*", "assets/skill/SKILL.md", "assets/skill/manifest.json", "assets/skills/manifest.json", @@ -20,6 +26,7 @@ "README.md" ], "scripts": { + "build:native": "node native/build.mjs", "test": "node --test test/*.test.js", "test:package": "node --test test/package/*.test.js" }, diff --git a/python/metergraph-skills/src/metergraph_skills/installer.py b/python/metergraph-skills/src/metergraph_skills/installer.py index 73be05f..9cbdf4e 100644 --- a/python/metergraph-skills/src/metergraph_skills/installer.py +++ b/python/metergraph-skills/src/metergraph_skills/installer.py @@ -18,6 +18,7 @@ import secrets import signal import stat +import sys import threading from contextlib import contextmanager from typing import Any, Dict, List, Optional @@ -53,8 +54,24 @@ # such as cloud placeholder files, are ordinary files and directories. NAME_SURROGATE_BIT = 0x20000000 BINARY = getattr(os, "O_BINARY", 0) +# Search handles preserve access to writable directories without read permission. +def _directory_access(flags=os, platform=sys.platform): + if hasattr(flags, "O_SEARCH"): + return flags.O_SEARCH + if hasattr(flags, "O_PATH"): + return flags.O_PATH + if platform == "darwin": + # Older CPython builds omit O_SEARCH although Darwin supports it. + # Darwin sys/fcntl.h defines O_EXEC=0x40000000 and + # O_SEARCH=(O_EXEC | O_DIRECTORY); callers always add O_DIRECTORY. + return 0x40000000 + return flags.O_RDONLY + + +DIRECTORY_ACCESS = _directory_access() MESSAGES = { + "secure_filesystem_unavailable": "Secure filesystem operations are unavailable on this platform. Nothing was written.", "invalid_project": "--project must name an existing directory.", "client_not_supported": ( "This client cannot load project skill files. Follow the connection guide instead. " @@ -140,6 +157,13 @@ def _execute(context: Context, project: Optional[str]) -> Dict[str, Any]: raise Stop("internal_error", "bundled_skill_invalid") context.target = _target_for(context.client, context.bundle.name) root = _resolve_project(project) + try: + return _execute_anchored(context, root) + finally: + root.close() + + +def _execute_anchored(context, root): # Decide from a read-only look first, so a matching rerun writes nothing. state = _inspect(root, context) @@ -149,7 +173,7 @@ def _execute(context: Context, project: Optional[str]) -> Dict[str, Any]: with _deferred_signals(): created_meta = _ensure_dirs(root, [RECEIPT_DIR]) - lock_path = os.path.join(root, RECEIPT_DIR, LOCK_FILE) + lock_path = root.file([RECEIPT_DIR], LOCK_FILE) done = False try: _acquire_lock(lock_path) @@ -163,7 +187,7 @@ def _execute(context: Context, project: Optional[str]) -> Dict[str, Any]: return _success(context, plan["status"]) finally: try: - os.unlink(lock_path) + _unlink(lock_path) except OSError: # A lock that cannot be removed is reported by the next run. pass @@ -177,24 +201,24 @@ def _target_for(client: str, name: str) -> Dict[str, Any]: return {"dirs": dirs, "relative": "/".join(dirs + ["SKILL.md"])} -def _resolve_project(project: Optional[str]) -> str: +def _resolve_project(project: Optional[str]) -> "AnchoredProject": if project is not None and (project == "" or "\0" in project): raise Stop("invalid_input", "invalid_project") try: real = os.path.realpath(os.path.abspath(project if project is not None else os.getcwd())) if os.path.isdir(real): - return real + return AnchoredProject(real) except (OSError, ValueError): pass raise Stop("invalid_input", "invalid_project") -def _inspect(root: str, context: Context) -> Dict[str, Any]: +def _inspect(root: "AnchoredProject", context: Context) -> Dict[str, Any]: """Reads the receipt and the target without writing. Any symbolic link or non-regular entry on either path stops the run.""" try: _check_dirs(root, [RECEIPT_DIR]) - receipt_file = _read_regular(os.path.join(root, RECEIPT_DIR, RECEIPT_FILE), MAX_RECEIPT_BYTES) + receipt_file = _read_regular(root.file([RECEIPT_DIR], RECEIPT_FILE), MAX_RECEIPT_BYTES) receipt = None if receipt_file is not None: if receipt_file["content"] is not None: @@ -203,7 +227,7 @@ def _inspect(root: str, context: Context) -> Dict[str, Any]: raise Stop("conflict", "receipt_invalid") skill_dir_exists = _check_dirs(root, context.target["dirs"]) file = ( - _read_regular(os.path.join(root, *context.target["dirs"], "SKILL.md"), MAX_SKILL_BYTES) + _read_regular(root.file(context.target["dirs"], "SKILL.md"), MAX_SKILL_BYTES) if skill_dir_exists else None ) @@ -245,19 +269,20 @@ def _decide(action: str, runtime: str, state: Dict[str, Any], bundle) -> Dict[st return {"status": "installed" if current else "updated", "noop": False, "write_skill": True} -def _commit(root: str, context: Context, state: Dict[str, Any], plan: Dict[str, Any]) -> None: +def _commit(root: "AnchoredProject", context: Context, state: Dict[str, Any], plan: Dict[str, Any]) -> None: """Writes the skill, then the receipt. If the receipt cannot be written the skill is restored to its previous state, so ownership is never recorded for a skill that was not written.""" bundle, target = context.bundle, context.target - skill_path = os.path.join(root, *target["dirs"], "SKILL.md") - receipt_path = os.path.join(root, RECEIPT_DIR, RECEIPT_FILE) + skill_path = None + receipt_path = root.file([RECEIPT_DIR], RECEIPT_FILE) receipt = _next_receipt(state["receipt"], context, target["relative"]) - created_dirs: List[str] = [] + created_dirs = [] skill_written = False try: if plan["write_skill"]: created_dirs = _ensure_dirs(root, target["dirs"]) + skill_path = root.file(target["dirs"], "SKILL.md") _replace_file(skill_path, bundle.content, state["file"]) skill_written = True if state["receipt_file"] is None or state["receipt_file"]["content"] != receipt: @@ -266,7 +291,7 @@ def _commit(root: str, context: Context, state: Dict[str, Any], plan: Dict[str, try: if skill_written: if state["file"] is None: - os.unlink(skill_path) + _unlink(skill_path) else: _replace_file( skill_path, @@ -356,66 +381,111 @@ def _is_name_surrogate(info) -> bool: return bool(getattr(info, "st_reparse_tag", 0) & NAME_SURROGATE_BIT) -def _lstat_or_none(file: str): - try: - return os.lstat(file) - except FileNotFoundError: - return None +class AnchoredProject: + """Retain every traversed directory until the transaction is finished. + All child operations are relative to these descriptors, even if an attacker + renames a directory or replaces its former pathname with a symlink. + """ + def __init__(self, path): + if os.name != "posix" or not NOFOLLOW or not getattr(os, "O_DIRECTORY", 0): + raise Stop("unsupported", "secure_filesystem_unavailable") + self.fds = {} + fd = os.open("/", DIRECTORY_ACCESS | os.O_DIRECTORY | NOFOLLOW) + try: + for component in path.split("/"): + if component: + child = os.open(component, DIRECTORY_ACCESS | os.O_DIRECTORY | NOFOLLOW, dir_fd=fd) + if not stat.S_ISDIR(os.fstat(child).st_mode): + os.close(child) + raise Stop("conflict", "unsafe_path") + os.close(fd) + fd = child + self.fds[()] = fd + except BaseException: + os.close(fd) + raise + + def close(self): + for fd in reversed(list(self.fds.values())): + os.close(fd) + self.fds.clear() + + def directory(self, dirs, create=False, created=None): + key = () + for name in dirs: + parent = self.fds[key] + key += (name,) + if key in self.fds: + continue + made = False + if create: + try: + os.mkdir(name, dir_fd=parent) + made = True + except FileExistsError: + pass + try: + fd = os.open(name, DIRECTORY_ACCESS | os.O_DIRECTORY | NOFOLLOW, dir_fd=parent) + except FileNotFoundError: + if not create: + return None + raise + except OSError as error: + if error.errno in (errno.ELOOP, errno.ENOTDIR): + raise Stop("conflict", "unsafe_path") + raise + # Linux O_PATH | O_NOFOLLOW opens a symlink itself. Verify the + # descriptor, never the pathname, before retaining it. + if not stat.S_ISDIR(os.fstat(fd).st_mode): + os.close(fd) + raise Stop("conflict", "unsafe_path") + self.fds[key] = fd + if made and created is not None: + created.append((parent, name, os.fstat(fd))) + return self.fds[key] + + def file(self, dirs, name): + return (self.directory(dirs), name) -def _check_dirs(root: str, dirs: List[str]) -> bool: - """Returns True when every directory exists, False at the first missing - one. Anything else, including a symbolic link to a directory, is unsafe.""" - current = root - for name in dirs: - current = os.path.join(current, name) - info = _lstat_or_none(current) - if info is None: - return False - if not _is_directory(info): - raise Stop("conflict", "unsafe_path") - return True +def _check_dirs(root, dirs): + return root.directory(dirs) is not None -def _ensure_dirs(root: str, dirs: List[str]) -> List[str]: - """Creates missing directories one level at a time and returns the ones it - created, deepest last, so a rollback can remove exactly those.""" - created: List[str] = [] - current = root + +def _ensure_dirs(root, dirs): + created = [] try: - for name in dirs: - current = os.path.join(current, name) - try: - os.mkdir(current) - created.append(current) - except FileExistsError: - if not _is_directory(os.lstat(current)): - raise Stop("conflict", "unsafe_path") + root.directory(dirs, create=True, created=created) except BaseException: _remove_dirs(created) raise return created -def _remove_dirs(created: List[str]) -> None: - for path in reversed(created): +def _remove_dirs(created): + for parent, name, expected in reversed(created): try: - os.rmdir(path) + now = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (now.st_dev, now.st_ino) == (expected.st_dev, expected.st_ino): + os.rmdir(name, dir_fd=parent) except OSError: - # Not empty or not removable. An empty directory is harmless. pass -def _read_regular(file: str, max_bytes: int) -> Optional[Dict[str, Any]]: - """Returns {content, mode} for a regular file, {content: None, mode} when - it is larger than max_bytes, or None when it does not exist.""" - info = _lstat_or_none(file) - if info is None: +def _unlink(file): + parent, name = file + os.unlink(name, dir_fd=parent) + + +def _read_regular(file, max_bytes): + parent, name = file + if parent is None: return None - if not _is_regular(info): - raise Stop("conflict", "unsafe_path") try: - fd = os.open(file, os.O_RDONLY | NOFOLLOW | BINARY) + fd = os.open(name, os.O_RDONLY | NOFOLLOW | getattr(os, "O_NONBLOCK", 0), dir_fd=parent) + except FileNotFoundError: + return None except OSError as error: if error.errno == errno.ELOOP: raise Stop("conflict", "unsafe_path") @@ -425,47 +495,39 @@ def _read_regular(file: str, max_bytes: int) -> Optional[Dict[str, Any]]: if not stat.S_ISREG(opened.st_mode): raise Stop("conflict", "unsafe_path") mode = stat.S_IMODE(opened.st_mode) & 0o777 - if opened.st_size > max_bytes: - return {"content": None, "mode": mode} - return {"content": handle.read(), "mode": mode} - - -def _replace_file(dest: str, content: bytes, previous: Optional[Dict[str, Any]]) -> None: - """Writes content to an exclusive temporary file next to dest, then renames - it into place. Right before the rename, dest must still be exactly what - inspect saw, so a file created or edited by someone else in the meantime - is never replaced. An existing file keeps its permission bits.""" - temp = os.path.join( - os.path.dirname(dest), ".{}.{}.tmp".format(os.path.basename(dest), secrets.token_hex(6)) - ) - fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | BINARY, 0o666 if previous is None else 0o600) + content = handle.read(max_bytes + 1) + return {"content": content if len(content) <= max_bytes else None, "mode": mode} + + +def _replace_file(dest, content, previous): + parent, name = dest + temp = ".{}.{}.tmp".format(name, secrets.token_hex(6)) + fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | NOFOLLOW, + 0o666 if previous is None else 0o600, dir_fd=parent) try: with os.fdopen(fd, "wb") as handle: handle.write(content) handle.flush() + if previous is not None: + os.fchmod(handle.fileno(), previous["mode"]) os.fsync(handle.fileno()) - if previous is not None: - os.chmod(temp, previous["mode"]) now = _read_regular(dest, MAX_SKILL_BYTES) - if previous is None: - unchanged = now is None - else: - unchanged = now is not None and now["content"] is not None and now["content"] == previous["content"] + unchanged = now is None if previous is None else (now is not None and now["content"] == previous["content"]) if not unchanged: raise Stop("conflict", "changed_during_install") - os.replace(temp, dest) + os.replace(temp, name, src_dir_fd=parent, dst_dir_fd=parent) except BaseException: try: - os.unlink(temp) + os.unlink(temp, dir_fd=parent) except OSError: - # Already renamed or never created. pass raise -def _acquire_lock(lock_path: str) -> None: +def _acquire_lock(lock_path): + parent, name = lock_path try: - os.close(os.open(lock_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | BINARY, 0o666)) + os.close(os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | NOFOLLOW, 0o666, dir_fd=parent)) except FileExistsError: raise Stop("conflict", "locked") diff --git a/python/metergraph-skills/tests/test_anchored.py b/python/metergraph-skills/tests/test_anchored.py new file mode 100644 index 0000000..9264e24 --- /dev/null +++ b/python/metergraph-skills/tests/test_anchored.py @@ -0,0 +1,119 @@ +"""Deterministic ancestor replacement tests for retained directory handles.""" +import os +import shutil +import sys +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'src')) +from metergraph_skills import installer as subject + + +@unittest.skipUnless(os.name == 'posix', 'POSIX descriptor backend') +class AnchoredTest(unittest.TestCase): + def setUp(self): + self.base = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.base, True) + self.project = self.base / 'project' + self.outside = self.base / 'outside' + self.project.mkdir() + self.outside.mkdir() + + def run_install(self): + return subject.run_skill('install', 'codex', 'local', str(self.project)) + + def test_directory_swapped_before_temp_creation(self): + original = subject._replace_file + def swap(dest, content, previous): + if dest[1] == 'SKILL.md': + (self.project / '.agents').rename(self.project / 'retained') + (self.project / '.agents').symlink_to(self.outside, target_is_directory=True) + return original(dest, content, previous) + with patch.object(subject, '_replace_file', side_effect=swap): + self.assertEqual(self.run_install()['outcome'], 'ok') + self.assertEqual(list(self.outside.iterdir()), []) + self.assertTrue((self.project / 'retained/skills/metergraph/SKILL.md').is_file()) + + def test_receipt_directory_swapped_before_lock(self): + original = subject._acquire_lock + def swap(dest): + (self.project / '.metergraph').rename(self.project / 'retained') + (self.project / '.metergraph').symlink_to(self.outside, target_is_directory=True) + original(dest) + with patch.object(subject, '_acquire_lock', side_effect=swap): + self.assertEqual(self.run_install()['outcome'], 'ok') + self.assertEqual(list(self.outside.iterdir()), []) + self.assertFalse((self.project / 'retained/skill-installations.lock').exists()) + self.assertTrue((self.project / 'retained/skill-installations.json').is_file()) + + def test_rollback_uses_retained_directory(self): + original = subject._replace_file + def fail_receipt(dest, content, previous): + if dest[1] == subject.RECEIPT_FILE: + (self.project / '.agents').rename(self.project / 'retained') + (self.project / '.agents').symlink_to(self.outside, target_is_directory=True) + (self.outside / 'SKILL.md').write_bytes(b'preserve') + raise OSError('injected failure') + return original(dest, content, previous) + with patch.object(subject, '_replace_file', side_effect=fail_receipt): + self.assertEqual(self.run_install()['reason'], 'write_failed') + self.assertEqual((self.outside / 'SKILL.md').read_bytes(), b'preserve') + self.assertFalse((self.project / 'retained/skills/metergraph/SKILL.md').exists()) + + def test_symlink_substitution_before_component_open(self): + original = os.mkdir + def swap(name, *args, **kwargs): + original(name, *args, **kwargs) + if name == '.agents': + (self.project / '.agents').rmdir() + (self.project / '.agents').symlink_to(self.outside, target_is_directory=True) + with patch.object(subject.os, 'mkdir', side_effect=swap): + self.assertEqual(self.run_install()['reason'], 'unsafe_path') + self.assertEqual(list(self.outside.iterdir()), []) + + def test_nonregular_read_does_not_block(self): + meta = self.project / '.metergraph' + meta.mkdir() + os.mkfifo(meta / subject.RECEIPT_FILE) + self.assertEqual(self.run_install()['reason'], 'unsafe_path') + + def test_unavailable_backend_writes_nothing(self): + with patch.object(subject.os, 'name', 'nt'): + self.assertEqual(self.run_install()['reason'], 'secure_filesystem_unavailable') + self.assertEqual(list(self.project.iterdir()), []) + + def test_search_only_directories_preserve_install(self): + self._assert_search_only_install() + + @unittest.skipUnless(sys.platform == 'darwin', 'Darwin legacy CPython compatibility') + def test_search_only_install_without_python_search_flag_symbols(self): + # CPython 3.9 on macOS does not export O_SEARCH or O_PATH. Exercise + # that selection independently of the interpreter running this test. + legacy_flags = SimpleNamespace(O_RDONLY=os.O_RDONLY) + access = subject._directory_access(legacy_flags, 'darwin') + with patch.object(subject, 'DIRECTORY_ACCESS', access): + self._assert_search_only_install() + + def _assert_search_only_install(self): + # Each case makes the project, a project ancestor, or the existing + # client directory writable/searchable without directory listing. + for restricted in ('project', 'ancestor', 'client'): + with self.subTest(restricted=restricted): + parent = self.base / ('restricted-' + restricted) + parent.mkdir() + project = parent / 'project' + project.mkdir() + client = project / '.agents' + client.mkdir() + directory = {'project': project, 'ancestor': parent, 'client': client}[restricted] + directory.chmod(0o333) + try: + result = subject.run_skill('install', 'codex', 'local', str(project)) + self.assertEqual(result['outcome'], 'ok', result) + self.assertEqual((project / '.agents/skills/metergraph/SKILL.md').read_bytes(), + subject.load_bundled_skill().content) + finally: + directory.chmod(0o755) diff --git a/python/metergraph-skills/tests/test_installer.py b/python/metergraph-skills/tests/test_installer.py index 16a95be..11592a5 100644 --- a/python/metergraph-skills/tests/test_installer.py +++ b/python/metergraph-skills/tests/test_installer.py @@ -84,6 +84,7 @@ def snapshot(root): return result +@unittest.skipIf(IS_WINDOWS, "secure directory backend unavailable on Windows") class InstallerTest(unittest.TestCase): def setUp(self): # The space checks that nothing splits or quotes paths. @@ -312,6 +313,7 @@ def test_usage_errors_match_npm(self): self.assertEqual(python, expected) @unittest.skipUnless(shutil.which("node") and NPM_BIN.is_file(), "node is not available") + @unittest.skipIf(IS_WINDOWS, "secure directory backend unavailable on Windows") def test_installers_share_files_and_receipt(self): node_project = Path(tempfile.mkdtemp(prefix="metergraph skills node ")) python_project = Path(tempfile.mkdtemp(prefix="metergraph skills python ")) @@ -337,6 +339,17 @@ def test_installers_share_files_and_receipt(self): self.assertEqual(json.loads(node.stdout)["data"]["status"], "reused") +@unittest.skipUnless(IS_WINDOWS, "Windows fail-closed contract") +class WindowsBackendTest(unittest.TestCase): + def test_installs_refuse_without_writing(self): + with tempfile.TemporaryDirectory() as directory: + for action in ("install", "update"): + for client in PATHS: + result = run(action, "--client", client, project=directory) + self.assertEqual(result["error"]["reason"], "secure_filesystem_unavailable") + self.assertEqual(list(Path(directory).iterdir()), []) + + def snapshot_bytes(root): return {key: value[0] for key, value in snapshot(root).items()} diff --git a/src/anchored-fs.js b/src/anchored-fs.js new file mode 100644 index 0000000..13a3256 --- /dev/null +++ b/src/anchored-fs.js @@ -0,0 +1,163 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { fileURLToPath } from "node:url"; + +// A process-local directory capability service. The shipped helper owns all +// descriptors; only its inherited anonymous pipes carry requests and contents. +// An absent or unverified backend is an error, never a pathname-write fallback. +const MAX = 2 * 1024 * 1024; +const base = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../native"); +const errnoNames = new Map(Object.entries(os.constants.errno).map(([name, number]) => [number, name])); +let service = null; +let rollbackDepth = 0; +const aliases = new Map(process.platform === "darwin" ? [["/var", "/private/var"], ["/tmp", "/private/tmp"]] : []); +function failure(code) { const error = new Error(`Secure filesystem operation failed (${code}).`); error.code = code; return error; } +function verifiedHelper() { + const name = `anchored-fs-${process.platform}-${process.arch}`; + let file; + try { + const manifest = JSON.parse(fs.readFileSync(path.join(base, "manifest.json"), "utf8")); + file = path.join(base, "bin", name); + const bytes = fs.readFileSync(file); + if (manifest.schema !== 1 || typeof manifest.artifacts[name] !== "string" || + createHash("sha256").update(bytes).digest("hex") !== manifest.artifacts[name]) throw failure("ENOTSUP"); + } catch { throw failure("ENOTSUP"); } + return file; +} +// Test and diagnostic capability discovery verifies the same packaged bytes as +// start(). It never enables a platform merely because its name is recognised. +export function hasVerifiedHelper() { + try { verifiedHelper(); return true; } catch { return false; } +} +function start() { + if (service !== null) return service; + const file = verifiedHelper(); + const child = spawn(file, [], { stdio: ["pipe", "pipe", "ignore"], windowsHide: true, env: {} }); + child.on("error", () => { /* synchronous pipe operations report backend loss */ }); + const input = child.stdin?._handle; + const output = child.stdout?._handle; + if (!input || !output || typeof input.setBlocking !== "function" || typeof output.setBlocking !== "function") { + child.kill("SIGKILL"); throw failure("ENOTSUP"); + } + input.setBlocking(true); output.setBlocking(true); + service = { child, input: input.fd, output: output.fd }; + child.unref(); child.stdin.unref(); child.stdout.unref(); + return service; +} +function writeAll(fd, bytes) { let offset = 0; while (offset < bytes.length) { const count = fs.writeSync(fd, bytes, offset, bytes.length - offset); if (count === 0) throw failure("EIO"); offset += count; } } +function readAll(fd, bytes) { let offset = 0; while (offset < bytes.length) { const count = fs.readSync(fd, bytes, offset, bytes.length - offset, null); if (count === 0) throw failure("EIO"); offset += count; } } +function request(operation, args = [], payload = Buffer.alloc(0)) { + const encoded = args.map(value => Buffer.from(String(value))); + if (encoded.some(value => value.includes(0))) throw failure("EINVAL"); + const size = 2 + encoded.reduce((n, value) => n + 4 + value.length, 0) + payload.length; + if (size > MAX) throw failure("EFBIG"); + const body = Buffer.alloc(4 + size); body.writeUInt32BE(size); body[4] = operation; body[5] = args.length; + let offset = 6; + for (const value of encoded) { body.writeUInt32BE(value.length, offset); offset += 4; value.copy(body, offset); offset += value.length; } + payload.copy(body, offset); + const pipe = start(); writeAll(pipe.input, body); + const header = Buffer.alloc(8); readAll(pipe.output, header); + const error = header.readUInt32BE(); const length = header.readUInt32BE(4); + if (length > MAX) throw failure("EIO"); + const result = Buffer.alloc(length); readAll(pipe.output, result); + if (error) throw failure(errnoNames.get(error) ?? "EIO"); + return result; +} +function canonical(value) { + if (typeof value !== "string" || value.includes("\0")) throw failure("EINVAL"); + let absolute = path.resolve(value); + const choices = [...aliases].sort((a,b) => b[0].length - a[0].length); + for (const [alias, target] of choices) if (absolute === alias || absolute.startsWith(`${alias}/`)) { absolute = target + absolute.slice(alias.length); break; } + return absolute; +} +function descriptor(value) { if (!Number.isSafeInteger(value) || value > -1001) throw failure("EBADF"); return -value - 1001; } +function statResult(bytes, options) { + if (bytes.length !== 88) throw failure("EIO"); + const keys = ["dev", "ino", "mode", "nlink", "uid", "gid", "size"]; + const result = {}; + keys.forEach((key, index) => { const n = bytes.readBigUInt64BE(index*8); result[key] = options?.bigint ? n : Number(n); }); + for (const [name, index] of [["mtime", 7], ["ctime", 9]]) { + const seconds = bytes.readBigInt64BE(index * 8); + const nanoseconds = bytes.readBigUInt64BE((index + 1) * 8); + if (nanoseconds >= 1000000000n) throw failure("EIO"); + const ns = seconds * 1000000000n + nanoseconds; + result[`${name}Ms`] = options?.bigint ? ns / 1000000n : Number(seconds) * 1000 + Number(nanoseconds) / 1000000; + if (options?.bigint) result[`${name}Ns`] = ns; + result[name] = new Date(Number(ns / 1000000n)); + } + const mode = Number(result.mode) & 0o170000; + return Object.assign(result, { isFile: () => mode === 0o100000, isDirectory: () => mode === 0o040000, + isSymbolicLink: () => mode === 0o120000, isFIFO: () => mode === 0o010000, + isSocket: () => mode === 0o140000, isBlockDevice: () => mode === 0o060000, isCharacterDevice: () => mode === 0o020000 }); +} +export function validatePath(value) { request(13, [canonical(value)]); return true; } +export function withRollback(callback) { + if (rollbackDepth++ === 0) request(14, [1]); + try { return callback(); } finally { if (--rollbackDepth === 0) request(14, [0]); } +} +export function closeAnchoredFs() { + if (service !== null) { service.child.stdin.destroy(); service.child.stdout.destroy(); service.child.kill("SIGKILL"); service = null; } +} +const anchored = { + constants: fs.constants, + lstatSync(value, options) { return statResult(request(1, [canonical(value)]), options); }, + statSync(value, options) { const result = this.lstatSync(value, options); if (result.isSymbolicLink()) throw failure("ELOOP"); return result; }, + realpathSync(value) { + // Root selection is read-only. Pin the resolved identity immediately; every + // subsequent operation uses the helper's retained directory descriptors. + const absolute = path.resolve(value); const real = fs.realpathSync(absolute); + const prior = aliases.get(absolute); + if (prior !== undefined && prior !== real) throw failure("ESTALE"); + // Freeze both the selected spelling and the capability spelling. A later + // root resolution cannot rebind an existing capability to another tree. + const pinned = aliases.get(real); + if (pinned !== undefined && pinned !== real) throw failure("ESTALE"); + validatePath(real); aliases.set(real, real); aliases.set(absolute, real); return real; + }, + existsSync(value) { try { this.lstatSync(value); return true; } catch (error) { if (["ENOENT", "ENOTDIR"].includes(error.code)) return false; throw error; } }, + openSync(value, flags, mode = 0o666) { + let kind; + const extras = (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0); + const stripped = typeof flags === "number" ? flags & ~extras : flags; + if (flags === "r" || stripped === fs.constants.O_RDONLY) kind = 0; + else if (flags === "r+" || stripped === fs.constants.O_RDWR) kind = 1; + else if (flags === "wx" || flags === "wx+" || stripped === (fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL)) kind = 2; + else throw failure("ENOTSUP"); + return -1001 - request(2, [canonical(value), kind, mode]).readUInt32BE(); + }, + fstatSync(fd, options) { return statResult(request(3, [descriptor(fd)]), options); }, + readFileSync(value, options) { + const own = typeof value !== "number"; const fd = own ? this.openSync(value, "r") : value; + try { const bytes = request(4, [descriptor(fd)]); const encoding = typeof options === "string" ? options : options?.encoding; return encoding ? bytes.toString(encoding) : bytes; } + finally { if (own) this.closeSync(fd); } + }, + readSync(fd, buffer, offset, length, position) { + const bytes = request(16, [descriptor(fd), length, position ?? 0]); bytes.copy(buffer, offset); return bytes.length; + }, + writeFileSync(fd, value, options) { + if (typeof fd !== "number") throw failure("ENOTSUP"); + const encoding = typeof options === "string" ? options : options?.encoding; + request(5, [descriptor(fd)], Buffer.isBuffer(value) ? value : Buffer.from(value, encoding)); + }, + fchmodSync(fd, mode) { request(6, [descriptor(fd), mode]); }, + chmodSync(value, mode) { const fd = this.openSync(value, "r"); try { this.fchmodSync(fd, mode); } finally { this.closeSync(fd); } }, + fsyncSync(fd) { request(7, [descriptor(fd)]); }, + closeSync(fd) { request(8, [descriptor(fd)]); }, + mkdirSync(value, options = {}) { + const absolute = canonical(value); const mode = typeof options === "number" ? options : options.mode ?? 0o777; + try { request(9, [absolute, mode]); } + catch (error) { + if (!options.recursive) throw error; + if (error.code === "ENOENT") { this.mkdirSync(path.dirname(absolute), {recursive:true, mode}); request(9, [absolute, mode]); } + else if (error.code !== "EEXIST" || !this.statSync(absolute).isDirectory()) throw error; + } + }, + renameSync(from, to) { request(10, [canonical(from), canonical(to)]); }, + unlinkSync(value) { request(11, [canonical(value)]); }, + rmdirSync(value) { request(12, [canonical(value)]); }, + linkSync(from, to) { request(15, [canonical(from), canonical(to)]); }, +}; +export default anchored; diff --git a/src/auth-binding.js b/src/auth-binding.js index 99e7156..aa557ac 100644 --- a/src/auth-binding.js +++ b/src/auth-binding.js @@ -1,5 +1,5 @@ import { randomBytes } from "node:crypto"; -import fs from "node:fs"; +import fs, { withRollback } from "./anchored-fs.js"; import path from "node:path"; import { Stop, isSlot } from "./auth-store.js"; @@ -26,7 +26,8 @@ export function resolveProject(project) { try { const real = fs.realpathSync(path.resolve(project ?? process.cwd())); if (fs.statSync(real).isDirectory()) return real; - } catch { + } catch (error) { + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); // Fall through to the fixed error. } throw new Stop("invalid_input", "invalid_project"); @@ -45,6 +46,7 @@ export function readBinding(root) { return { binding, content }; } catch (error) { if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); throw new Stop("filesystem_error", "read_failed"); } } @@ -83,12 +85,13 @@ export function writeBinding(root, binding, previous) { } catch (error) { if (created) { try { - fs.rmdirSync(dir); + withRollback(() => fs.rmdirSync(dir)); } catch { // Not empty. An empty directory is harmless. } } if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); throw new Stop("filesystem_error", "binding_write_failed"); } } @@ -103,6 +106,7 @@ export function removeBinding(root, previous) { }); } catch (error) { if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); throw new Stop("filesystem_error", "binding_write_failed"); } } @@ -119,7 +123,7 @@ function withProjectLock(dir, work) { return work(); } finally { try { - fs.unlinkSync(lock); + withRollback(() => fs.unlinkSync(lock)); } catch { // Reported by the next run as a held lock. } @@ -146,7 +150,7 @@ function replace(dir, content) { fs.renameSync(temp, dest); } catch (error) { try { - fs.unlinkSync(temp); + withRollback(() => fs.unlinkSync(temp)); } catch { // Already renamed or never created. } diff --git a/src/auth-store.js b/src/auth-store.js index 5abe706..e06ec55 100644 --- a/src/auth-store.js +++ b/src/auth-store.js @@ -1,6 +1,6 @@ import { spawnSync } from "node:child_process"; import { createHash, randomBytes } from "node:crypto"; -import fs from "node:fs"; +import fs, { withRollback } from "./anchored-fs.js"; import os from "node:os"; import path from "node:path"; @@ -90,6 +90,7 @@ export function openStore(dir, { create }) { return { dir, credentials }; } catch (error) { if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); throw new Stop("filesystem_error", "credential_store_unavailable"); } } @@ -111,6 +112,7 @@ export function readCredential(store, slot) { content = readPrivateFile(file); } catch (error) { if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); throw new Stop("filesystem_error", "credential_store_unavailable"); } if (content === null) return null; @@ -141,6 +143,7 @@ export function writeCredential(store, slot, record) { writePrivateFile(store.credentials, `${slot}.json`, content); } catch (error) { if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); throw new Stop("filesystem_error", "credential_write_failed"); } } @@ -157,6 +160,7 @@ export function deleteCredential(store, slot) { return true; } catch (error) { if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); throw new Stop("filesystem_error", "credential_write_failed"); } } @@ -179,6 +183,7 @@ export async function withSlotLock(store, slot, work, { waitMs, signal = null }) fs.closeSync(fd); break; } catch (error) { + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); if (error.code !== "EEXIST") throw new Stop("filesystem_error", "credential_store_unavailable"); if (Date.now() >= until) throw new Stop("conflict", "credential_locked"); await pause(50, signal); @@ -189,7 +194,7 @@ export async function withSlotLock(store, slot, work, { waitMs, signal = null }) return await work(); } finally { try { - fs.unlinkSync(lock); + withRollback(() => fs.unlinkSync(lock)); } catch { // Reported by the next run as a held lock. } @@ -389,7 +394,7 @@ function writePrivateFile(dir, name, content) { fs.renameSync(temp, dest); } catch (error) { try { - fs.unlinkSync(temp); + withRollback(() => fs.unlinkSync(temp)); } catch { // Already renamed or never created. } diff --git a/src/output.js b/src/output.js index 69785ba..96c0680 100644 --- a/src/output.js +++ b/src/output.js @@ -1238,6 +1238,8 @@ const AUTH_MESSAGES = { "The grant would allow content, replay or provider access, which login never accepts. It was not kept.", access_rejected: "The service refused the new grant. Nothing was saved.", invalid_project: "--project must name an existing directory.", + secure_writes_unavailable: + "Secure automatic file writes are unavailable on this platform or the bundled filesystem helper failed verification. Nothing was written.", invalid_config_dir: "METERGRAPH_CONFIG_DIR must be an absolute path.", unsafe_path: "A path in .metergraph is a symbolic link or is not a regular file or directory. Nothing was changed.", binding_invalid: "The project binding .metergraph/project.json is not valid. Nothing was changed.", diff --git a/src/repository-identity.js b/src/repository-identity.js index 48e0f41..b4ec38c 100644 --- a/src/repository-identity.js +++ b/src/repository-identity.js @@ -1,5 +1,5 @@ import { spawnSync } from "node:child_process"; -import fs from "node:fs"; +import fs, { withRollback } from "./anchored-fs.js"; import path from "node:path"; // Repository identity for the SDKs: `.metergraph/config.json` with @@ -157,7 +157,7 @@ function writeNewConfig(root, repository) { try { fs.writeFileSync(fd, content); fs.fsyncSync(fd); } finally { fs.closeSync(fd); } fs.linkSync(temp, dest); } finally { - try { fs.unlinkSync(temp); } catch { /* already gone */ } + try { withRollback(() => fs.unlinkSync(temp)); } catch { /* already gone */ } } } diff --git a/src/setup-env-git.js b/src/setup-env-git.js index 4c21dae..8f16558 100644 --- a/src/setup-env-git.js +++ b/src/setup-env-git.js @@ -1,5 +1,5 @@ import { spawnSync } from "node:child_process"; -import fs from "node:fs"; +import fs from "./anchored-fs.js"; import path from "node:path"; import { Stop } from "./auth-store.js"; diff --git a/src/setup-env.js b/src/setup-env.js index 0c10491..cfc9ee8 100644 --- a/src/setup-env.js +++ b/src/setup-env.js @@ -1,5 +1,5 @@ import { randomBytes } from "node:crypto"; -import fs from "node:fs"; +import fs, { validatePath, withRollback } from "./anchored-fs.js"; import path from "node:path"; import { resolveProject } from "./auth-binding.js"; @@ -62,6 +62,8 @@ const PLANS = new WeakMap(); const HANDLES = new WeakMap(); export const ENV_MESSAGES = Object.freeze({ + secure_writes_unavailable: + "Secure automatic file writes are unavailable on this platform or the bundled filesystem helper failed verification. Nothing was written.", invalid_project: "--project must name an existing directory.", env_path_invalid: "The env file path is not allowed. Use a project-relative path with forward slashes to a file named .env, .env. or .env.", @@ -193,12 +195,12 @@ export async function rollbackEnv(handle, { signal = null, waitMs = DEFAULT_WAIT if (state === undefined) throw new Stop("internal_error", "invalid_plan"); checkCancel(signal); if (state.journal.length > 0) { - const lock = await takeLock(state.lockDir, waitMs, signal); + const lock = await takeLock(state.lockDir, waitMs, signal, true); try { checkCancel(signal); deferSignals(() => { try { - undo(state.journal); + withRollback(() => undo(state.journal)); } catch (error) { if (error instanceof Stop && error.outcome === "conflict") throw new Stop("conflict", "rollback_conflict"); throw new Stop("filesystem_error", "rollback_incomplete"); @@ -352,6 +354,8 @@ function apply(state, updates) { } } + validatePath(target.dir); + if (ignore !== null) validatePath(state.root); const receipt = freeze({ path: target.rel, location: target.location, @@ -363,7 +367,7 @@ function apply(state, updates) { return { receipt, journal }; } catch (error) { try { - undo(journal); + withRollback(() => undo(journal)); } catch { throw new Stop("filesystem_error", "rollback_incomplete"); } @@ -575,7 +579,7 @@ function replaceFile(file, content, { before, mode, protect, reasons, changed }) } catch (error) { if (created) { try { - fs.unlinkSync(temp); + withRollback(() => fs.unlinkSync(temp)); } catch { // Reported by the caller's failure; nothing else to do. } @@ -602,7 +606,7 @@ function syncDir(dir) { // An exclusive lock file in the project (or, outside a project, in the env // file's directory). A held lock is waited on for at most waitMs, then // reported; it is never taken over or removed, even if it looks stale. -async function takeLock(dir, waitMs, signal) { +async function takeLock(dir, waitMs, signal, rollback = false) { const file = path.join(dir, LOCK); const wait = Number.isFinite(waitMs) ? Math.min(Math.max(waitMs, 0), MAX_WAIT_MS) : DEFAULT_WAIT_MS; const until = Date.now() + wait; @@ -610,7 +614,7 @@ async function takeLock(dir, waitMs, signal) { checkCancel(signal); let fd; try { - fd = fs.openSync(file, "wx", 0o600); + fd = rollback ? withRollback(() => fs.openSync(file, "wx", 0o600)) : fs.openSync(file, "wx", 0o600); } catch (error) { if (error.code !== "EEXIST") throw fixed(error, "env_write_failed"); if (Date.now() >= until) throw new Stop("conflict", "env_locked"); @@ -629,8 +633,10 @@ async function takeLock(dir, waitMs, signal) { // Removes the lock only if it is still the file this process created. function dropLock(lock) { try { - const stat = fs.lstatSync(lock.file); - if (IS_WINDOWS || (stat.dev === lock.dev && stat.ino === lock.ino)) fs.unlinkSync(lock.file); + withRollback(() => { + const stat = fs.lstatSync(lock.file); + if (stat.dev === lock.dev && stat.ino === lock.ino) fs.unlinkSync(lock.file); + }); } catch { // Reported by the next run as a held lock. } @@ -670,6 +676,7 @@ function deferSignals(work) { // error, which can hold a path, is never passed on. function fixed(error, reason) { if (error instanceof Stop) return error; + if (error?.code === "ENOTSUP") return new Stop("unsupported", "secure_writes_unavailable"); if (DENIED.has(error?.code)) { return new Stop("filesystem_error", reason === "env_read_failed" ? "env_read_denied" : "env_write_denied"); } diff --git a/src/setup-refusal.js b/src/setup-refusal.js index 8e35a0b..3afa0df 100644 --- a/src/setup-refusal.js +++ b/src/setup-refusal.js @@ -1,5 +1,5 @@ import { randomBytes, randomUUID } from "node:crypto"; -import fs from "node:fs"; +import fs, { withRollback } from "./anchored-fs.js"; import path from "node:path"; // What the --json --no-browser background waiter is doing with an approval @@ -80,7 +80,7 @@ function write(root, value) { fs.renameSync(temp, fileFor(root)); return true; } catch { - try { fs.unlinkSync(temp); } catch { /* no temp */ } + try { withRollback(() => fs.unlinkSync(temp)); } catch { /* no temp */ } return false; } } diff --git a/src/setup-state.js b/src/setup-state.js index 867e257..014d5ce 100644 --- a/src/setup-state.js +++ b/src/setup-state.js @@ -1,5 +1,5 @@ import { randomBytes, randomUUID } from "node:crypto"; -import fs from "node:fs"; +import fs, { withRollback } from "./anchored-fs.js"; import path from "node:path"; import { parseOrigin } from "./origin.js"; @@ -80,6 +80,7 @@ export function readSetupState(root) { let stat; try { stat = fs.lstatSync(file); } catch (error) { + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); if (error.code === "ENOENT") return null; throw new Stop("filesystem_error", "setup_state_read_failed"); } @@ -97,6 +98,7 @@ export function readSetupState(root) { selected_client: null, skill_status: "pending" }) : value, content }; } catch (error) { if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); throw new Stop("conflict", "setup_state_invalid"); } finally { if (fd !== undefined) fs.closeSync(fd); @@ -136,10 +138,11 @@ export function writeSetupState(root, next, previous) { fs.renameSync(temp, dest); } catch (error) { if (error instanceof Stop) throw error; + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); if (error.code === "EEXIST") throw new Stop("conflict", "setup_state_locked"); throw new Stop("filesystem_error", "setup_state_write_failed"); } finally { - try { fs.unlinkSync(temp); } catch { /* no temp */ } - if (locked) { try { fs.unlinkSync(lock); } catch { /* next run refuses */ } } + try { withRollback(() => fs.unlinkSync(temp)); } catch { /* no temp */ } + if (locked) { try { withRollback(() => fs.unlinkSync(lock)); } catch { /* next run refuses */ } } } } diff --git a/src/skill.js b/src/skill.js index 86996e4..77bb4f4 100644 --- a/src/skill.js +++ b/src/skill.js @@ -1,7 +1,7 @@ import { TRUSTED_SKILLS } from "./skill-trusted.js"; import { randomBytes } from "node:crypto"; -import fs from "node:fs"; +import fs, { validatePath, withRollback } from "./anchored-fs.js"; import path from "node:path"; import { @@ -33,6 +33,7 @@ const ENTRY_KEYS = ["client", "path", "revision", "runtimes", "sha256", "skill"] const NOFOLLOW = fs.constants.O_NOFOLLOW ?? 0; const MESSAGES = { + secure_writes_unavailable: "Secure automatic file writes are unavailable on this platform or the bundled filesystem helper failed verification. Nothing was written.", invalid_project: "--project must name an existing directory.", client_not_supported: "This client cannot load project skill files. Follow the connection guide instead. Nothing was written.", @@ -116,7 +117,7 @@ function apply(root, context) { return plan.status; } finally { try { - fs.unlinkSync(lockPath); + withRollback(() => fs.unlinkSync(lockPath)); } catch { // A lock that cannot be removed is reported by the next run. } @@ -136,7 +137,8 @@ function resolveProject(project) { try { const real = fs.realpathSync(path.resolve(project ?? process.cwd())); if (fs.statSync(real).isDirectory()) return real; - } catch { + } catch (error) { + if (error.code === "ENOTSUP") throw new Stop("unsupported", "secure_writes_unavailable"); // Fall through to the fixed error. } throw new Stop("invalid_input", "invalid_project"); @@ -206,6 +208,7 @@ function commit(root, context, state, plan) { const receipt = nextReceipt(state.receipt, context, target.relative); let createdDirs = []; let skillWritten = false; + let receiptWritten = false; try { if (plan.writeSkill) { createdDirs = ensureDirs(root, target.dirs); @@ -214,13 +217,23 @@ function commit(root, context, state, plan) { } if (state.receiptFile === null || !state.receiptFile.content.equals(receipt)) { replaceFile(receiptPath, receipt, state.receiptFile); + receiptWritten = true; } + validatePath(root); + validatePath(path.dirname(skillPath)); + validatePath(path.dirname(receiptPath)); } catch (error) { try { - if (skillWritten) { - if (state.file === null) fs.unlinkSync(skillPath); - else replaceFile(skillPath, state.file.content, { content: bundle.content, mode: state.file.mode }); - } + withRollback(() => { + if (receiptWritten) { + if (state.receiptFile === null) fs.unlinkSync(receiptPath); + else replaceFile(receiptPath, state.receiptFile.content, { content: receipt, mode: state.receiptFile.mode }); + } + if (skillWritten) { + if (state.file === null) fs.unlinkSync(skillPath); + else replaceFile(skillPath, state.file.content, { content: bundle.content, mode: state.file.mode }); + } + }); } catch { throw new Stop("filesystem_error", "rollback_failed"); } @@ -331,7 +344,7 @@ function ensureDirs(root, dirs) { function removeDirs(created) { for (const dir of [...created].reverse()) { try { - fs.rmdirSync(dir); + withRollback(() => fs.rmdirSync(dir)); } catch { // Not empty or not removable. An empty directory is harmless. } @@ -388,7 +401,7 @@ function replaceFile(dest, content, previous) { fs.renameSync(temp, dest); } catch (error) { try { - fs.unlinkSync(temp); + withRollback(() => fs.unlinkSync(temp)); } catch { // Already renamed or never created. } diff --git a/test/anchored-fs.test.js b/test/anchored-fs.test.js new file mode 100644 index 0000000..c64aef4 --- /dev/null +++ b/test/anchored-fs.test.js @@ -0,0 +1,140 @@ +import assert from "node:assert/strict"; +import { test, afterEach } from "node:test"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import anchored, { validatePath, withRollback, closeAnchoredFs, hasVerifiedHelper } from "../src/anchored-fs.js"; +const supported = hasVerifiedHelper(); +const roots = []; +afterEach(() => { closeAnchoredFs(); for (const root of roots.splice(0)) fs.rmSync(root,{recursive:true,force:true}); }); +function fixture() { const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),"anchored-fs-test-"))); roots.push(root); return root; } +function create(file, content) { const fd=anchored.openSync(file,"wx",0o600); try {anchored.writeFileSync(fd,content);anchored.fsyncSync(fd);} finally {anchored.closeSync(fd);} } +test("prebuilt helper reads, replaces, syncs and cleans without a runtime compiler", {skip:!supported}, () => { + const root=fixture(); anchored.realpathSync(root); + const dir=path.join(root,"nested");anchored.mkdirSync(dir,{mode:0o700}); + const file=path.join(dir,"file"),temp=path.join(dir,"temp");create(file,"before"); + assert.equal(anchored.readFileSync(file,"utf8"),"before");create(temp,"after");anchored.renameSync(temp,file); + assert.equal(anchored.readFileSync(file,"utf8"),"after");assert.equal(anchored.statSync(file).mode&0o777,0o600); + const fd=anchored.openSync(dir,"r");anchored.fsyncSync(fd);anchored.closeSync(fd); + anchored.unlinkSync(file);anchored.rmdirSync(dir); + anchored.mkdirSync(dir);create(path.join(dir,"new"),"new"); +}); +test("stat replies preserve mtime and ctime precision for normal and BigInt callers", {skip:!supported}, () => { + const root=fixture(),file=path.join(root,"timestamps");create(file,"synthetic"); + for(const timestamp of [1700000000.123456,-1234.875123]) { + fs.utimesSync(file,timestamp,timestamp); + const expected=fs.statSync(file,{bigint:true}); + const fromPath=anchored.lstatSync(file,{bigint:true}); + const fd=anchored.openSync(file,"r"); + let fromFd;try {fromFd=anchored.fstatSync(fd,{bigint:true});} finally {anchored.closeSync(fd);} + for(const actual of [fromPath,fromFd]) { + for(const field of ["mtimeNs","ctimeNs","mtimeMs","ctimeMs"]) assert.equal(actual[field],expected[field],field); + } + const expectedNumber=fs.statSync(file),actualNumber=anchored.statSync(file); + assert.equal(actualNumber.mtimeMs,expectedNumber.mtimeMs); + assert.equal(actualNumber.ctimeMs,expectedNumber.ctimeMs); + assert.equal(Object.hasOwn(actualNumber,"mtimeNs"),false); + assert.equal(Object.hasOwn(actualNumber,"ctimeNs"),false); + } +}); +test("substituted parent fails closed and rollback stays on retained directory", {skip:!supported}, () => { + const root=fixture(),outside=fixture(),dir=path.join(root,"target"),old=path.join(root,"old");fs.mkdirSync(dir); + anchored.realpathSync(root);const file=path.join(dir,"secret");create(file,"synthetic-token"); + fs.renameSync(dir,old);fs.symlinkSync(outside,dir); + assert.throws(()=>validatePath(dir),{code:"ESTALE"}); + assert.throws(()=>create(path.join(dir,"later"),"synthetic-token"),{code:"ESTALE"}); + withRollback(()=>anchored.unlinkSync(file)); + assert.deepEqual(fs.readdirSync(outside),[]);assert.deepEqual(fs.readdirSync(old),[]); +}); +test("cleanup refuses an attacker-substituted leaf", {skip:!supported}, () => { + const root=fixture(),file=path.join(root,"lock");anchored.realpathSync(root);create(file,""); + fs.renameSync(file,path.join(root,"original"));fs.writeFileSync(file,"keep"); + anchored.lstatSync(file); // Observation must not adopt the substituted identity. + assert.throws(()=>withRollback(()=>anchored.unlinkSync(file)),{code:"ESTALE"}); + assert.equal(fs.readFileSync(file,"utf8"),"keep"); +}); +test("symlink parents and hardlinked files are refused", {skip:!supported}, () => { + const root=fixture(),outside=fixture();anchored.realpathSync(root);fs.symlinkSync(outside,path.join(root,"link")); + assert.throws(()=>create(path.join(root,"link","file"),"synthetic-token")); + const file=path.join(root,"hard");fs.writeFileSync(file,"keep");fs.linkSync(file,path.join(outside,"alias")); + assert.throws(()=>anchored.openSync(file,"r+"),{code:"ELOOP"}); + assert.equal(fs.readFileSync(path.join(outside,"alias"),"utf8"),"keep"); +}); +test("exclusive hardlink promotion retains create-if-absent semantics", {skip:!supported}, () => { + const root=fixture();anchored.realpathSync(root);const temp=path.join(root,"temp"),dest=path.join(root,"dest");create(temp,"identity"); + anchored.linkSync(temp,dest);anchored.unlinkSync(temp); + assert.equal(anchored.readFileSync(dest,"utf8"),"identity"); +}); + +test("nonregular reads cannot block the helper on a FIFO", {skip:!supported}, async () => { + const {spawnSync}=await import("node:child_process");const root=fixture();anchored.realpathSync(root); + const file=path.join(root,"fifo");assert.equal(spawnSync("mkfifo",[file]).status,0); + assert.throws(()=>anchored.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NONBLOCK),{code:"ELOOP"}); +}); + +test("resolving a pinned root again cannot rebind it through a substituted symlink", {skip:!supported}, () => { + const parent=fixture(),outside=fixture(),root=path.join(parent,"project");fs.mkdirSync(root);anchored.realpathSync(root); + fs.renameSync(root,path.join(parent,"original"));fs.symlinkSync(outside,root); + assert.throws(()=>anchored.realpathSync(root),{code:"ESTALE"}); + assert.throws(()=>create(path.join(root,"file"),"synthetic-token"),{code:"ESTALE"}); + assert.deepEqual(fs.readdirSync(outside),[]); +}); + +test("helper survives deferred terminal signals and exits when owner pipe closes", {skip:!supported, timeout:5000}, async () => { + const {spawn}=await import("node:child_process"); + const {once}=await import("node:events"); + const child=spawn(new URL(`../native/bin/anchored-fs-${process.platform}-${process.arch}`,import.meta.url).pathname,[],{stdio:["pipe","pipe","ignore"]}); + const frame=Buffer.alloc(11);frame.writeUInt32BE(7);frame[4]=1;frame[5]=1;frame.writeUInt32BE(1,6);frame[10]=47; + async function query() { + const answer=new Promise((resolve,reject)=>{ + const pieces=[];let size=0; + function data(bytes) {pieces.push(bytes);size+=bytes.length;if(size>=96){child.stdout.off("data",data);resolve(Buffer.concat(pieces));}} + child.stdout.on("data",data);child.once("error",reject); + }); + child.stdin.write(frame);const reply=await answer;assert.equal(reply.readUInt32BE(),0);assert.equal(reply.readUInt32BE(4),88); + } + try { + await query(); + for(const signal of ["SIGINT","SIGTERM","SIGHUP"]) {child.kill(signal);await query();} + const exited=once(child,"exit");child.stdin.end();assert.deepEqual(await exited,[0,null]); + } finally {if(child.exitCode===null)child.kill("SIGKILL");} +}); + +test("fresh observation permits replacement of a final file updated by another process", {skip:!supported}, async () => { + const {spawnSync}=await import("node:child_process"); + const root=fixture(),dest=path.join(root,"grant"),temp=path.join(root,"first");anchored.realpathSync(root); + create(temp,"initial");anchored.renameSync(temp,dest);assert.equal(anchored.readFileSync(dest,"utf8"),"initial"); + const adapter=new URL("../src/anchored-fs.js",import.meta.url).href; + const script=`import f,{closeAnchoredFs} from ${JSON.stringify(adapter)};const d=${JSON.stringify(dest)},t=${JSON.stringify(path.join(root,"other"))};f.lstatSync(d);const fd=f.openSync(t,"wx",384);f.writeFileSync(fd,"refreshed");f.closeSync(fd);f.renameSync(t,d);closeAnchoredFs();`; + const child=spawnSync(process.execPath,["--input-type=module","-e",script],{encoding:"utf8"});assert.equal(child.status,0,child.stderr); + anchored.lstatSync(dest);assert.equal(anchored.readFileSync(dest,"utf8"),"refreshed"); + const next=path.join(root,"next");create(next,"latest");anchored.renameSync(next,dest); + assert.equal(anchored.readFileSync(dest,"utf8"),"latest"); +}); + +test("directory lstat pins identity before an ordinary-directory substitution", {skip:!supported}, () => { + const root=fixture(),outside=fixture(),dir=path.join(root,"credentials"),held=path.join(root,"held"); + fs.mkdirSync(dir);anchored.lstatSync(dir); + fs.renameSync(dir,held);fs.renameSync(outside,dir); + assert.throws(()=>create(path.join(dir,"grant"),"synthetic-token"),{code:"ESTALE"}); + assert.deepEqual(fs.readdirSync(dir),[]);assert.deepEqual(fs.readdirSync(held),[]); +}); + +test("openStore pins credentials before its first credential write", {skip:!supported}, async () => { + const {openStore,writeCredential,newSlot}=await import("../src/auth-store.js"); + const root=fixture(),outside=fixture(),config=path.join(root,"config"); + const store=openStore(config,{create:true});const held=path.join(root,"held"); + fs.renameSync(store.credentials,held);fs.renameSync(outside,store.credentials); + const record={schema_version:1,origin:"http://127.0.0.1:4000",issuer:"http://127.0.0.1:4000/v1/oauth",resource:"http://127.0.0.1:4000/v1/agent/mcp",deployment_profile:"local",workspace_id:"00000000-0000-0000-0000-000000000001",client_id:"synthetic-client",scope:"agent:metadata",access_token:"synthetic-access",refresh_token:"synthetic-refresh",expires_at:Date.now()+1000,refresh_pending:false}; + assert.throws(()=>writeCredential(store,newSlot(),record),error=>error.reason==="credential_write_failed"); + assert.deepEqual(fs.readdirSync(store.credentials),[]);assert.deepEqual(fs.readdirSync(held),[]); +}); + +test("skill install preserves writable searchable project support without directory read permission", {skip:!supported || process.getuid?.()===0}, async () => { + const {runSkill}=await import("../src/skill.js");const root=fixture();fs.chmodSync(root,0o333); + try { + const result=runSkill({action:"install",client:"codex",runtime:"local",project:root}); + assert.equal(result.outcome,"ok",JSON.stringify(result)); + assert.equal(anchored.readFileSync(path.join(root,".agents","skills","metergraph","SKILL.md"),"utf8").includes("Metergraph"),true); + } finally {fs.chmodSync(root,0o700);} +}); diff --git a/test/auth-session.test.js b/test/auth-session.test.js index 995d8ea..10a5c09 100644 --- a/test/auth-session.test.js +++ b/test/auth-session.test.js @@ -5,6 +5,7 @@ // is protocol and file proof only, not proof of the real service. import assert from "node:assert/strict"; import fs from "node:fs"; +import anchoredFs from "../src/anchored-fs.js"; import os from "node:os"; import path from "node:path"; import { after, test } from "node:test"; @@ -162,9 +163,9 @@ test("a refreshed grant that cannot be saved asks to reconnect instead of reusin const project = await signedIn(server); project.change({ expires_at: Date.now() - 1000 }); const credential = `${project.slot}.json`; - const renameSync = fs.renameSync; + const renameSync = anchoredFs.renameSync; let renames = 0; - fs.renameSync = (from, to) => { + anchoredFs.renameSync = (from, to) => { if (path.basename(String(to)) === credential) { renames += 1; // The first rename marks the refresh as pending; the second would @@ -177,7 +178,7 @@ test("a refreshed grant that cannot be saved asks to reconnect instead of reusin try { result = await project.session(); } finally { - fs.renameSync = renameSync; + anchoredFs.renameSync = renameSync; } assertStop(result, "login_required", "refresh_not_saved"); assert.equal(refreshRequests(server).length, 1); diff --git a/test/auth-store.test.js b/test/auth-store.test.js index f13b88b..e6332fc 100644 --- a/test/auth-store.test.js +++ b/test/auth-store.test.js @@ -2,6 +2,7 @@ // touches the user's real config directory. import assert from "node:assert/strict"; import fs from "node:fs"; +import anchoredFs from "../src/anchored-fs.js"; import os from "node:os"; import path from "node:path"; import { after, test } from "node:test"; @@ -183,8 +184,8 @@ test("a failed write keeps the previous grant and leaves no temporary file", () const store = openStore(freshDir(), { create: true }); const slot = newSlot(); writeCredential(store, slot, record()); - const renameSync = fs.renameSync; - fs.renameSync = () => { + const renameSync = anchoredFs.renameSync; + anchoredFs.renameSync = () => { throw Object.assign(new Error("SYNTHETIC_FAULT_MARKER"), { code: "EIO" }); }; try { @@ -193,7 +194,7 @@ test("a failed write keeps the previous grant and leaves no temporary file", () stopWith("filesystem_error", "credential_write_failed"), ); } finally { - fs.renameSync = renameSync; + anchoredFs.renameSync = renameSync; } assert.equal(readCredential(store, slot).access_token, ACCESS); assert.deepEqual(fs.readdirSync(store.credentials), [`${slot}.json`]); diff --git a/test/build-artifacts.test.js b/test/build-artifacts.test.js new file mode 100644 index 0000000..3406a8d --- /dev/null +++ b/test/build-artifacts.test.js @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import {afterEach,test} from "node:test"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import {createHash} from "node:crypto"; +import {aggregate} from "../native/aggregate.mjs"; +import {build} from "../native/build.mjs"; +import {TARGETS,binaryFor} from "../native/targets.mjs"; +const roots=[];const revision="a".repeat(40); +const source=createHash("sha256").update(fs.readFileSync(new URL("../native/anchored-fs.c",import.meta.url))).digest("hex"); +const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); +afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); +function fixture(){const root=fs.mkdtempSync(path.join(os.tmpdir(),"native-build-artifacts-"));roots.push(root);const input=path.join(root,"input"),output=path.join(root,"output");fs.mkdirSync(input);for(const target of [...TARGETS].reverse())artifact(input,target);return{root,input,output};} +function artifact(input,target,folder=target){const dir=path.join(input,folder),bin=path.join(dir,"bin"),name=binaryFor(target),bytes=Buffer.from(`synthetic ${target}`);fs.mkdirSync(bin,{recursive:true});fs.writeFileSync(path.join(bin,name),bytes,{mode:0o644});fs.writeFileSync(path.join(dir,"manifest.json"),JSON.stringify({schema:1,artifacts:{[name]:digest(bytes)}}));fs.writeFileSync(path.join(dir,"provenance.json"),JSON.stringify({schema:1,source_revision:revision,source_sha256:source,target,binary_sha256:digest(bytes)}));return dir;} +function edit(file,callback){const value=JSON.parse(fs.readFileSync(file));callback(value);fs.writeFileSync(file,JSON.stringify(value));} +function run(value){return aggregate({...value,revision});} +test("assembly emits exact target list, deterministic manifest and executable binaries",()=>{const f=fixture();const result=run(f);assert.deepEqual(Object.keys(result.artifacts),TARGETS.map(binaryFor));assert.deepEqual(fs.readdirSync(path.join(f.output,"bin")).sort(),TARGETS.map(binaryFor).sort());for(const name of TARGETS.map(binaryFor)){assert.equal(fs.statSync(path.join(f.output,"bin",name)).mode&0o777,0o755);assert.equal(digest(fs.readFileSync(path.join(f.output,"bin",name))),result.artifacts[name]);}const other=path.join(f.root,"other");aggregate({input:f.input,revision,output:other});assert.equal(fs.readFileSync(path.join(other,"manifest.json"),"utf8"),fs.readFileSync(path.join(f.output,"manifest.json"),"utf8"));}); +for(const [label,mutate] of [ + ["missing",f=>fs.rmSync(path.join(f.input,TARGETS[0]),{recursive:true})], + ["unknown",f=>edit(path.join(f.input,TARGETS[0],"provenance.json"),p=>{p.target="windows-x64";})], + ["duplicate",f=>{fs.rmSync(path.join(f.input,TARGETS[0]),{recursive:true});artifact(f.input,TARGETS[1],"duplicate");}], + ["source",f=>edit(path.join(f.input,TARGETS[0],"provenance.json"),p=>{p.source_sha256="b".repeat(64);})], + ["revision",f=>edit(path.join(f.input,TARGETS[0],"provenance.json"),p=>{p.source_revision="b".repeat(40);})], + ["provenance digest",f=>edit(path.join(f.input,TARGETS[0],"provenance.json"),p=>{p.binary_sha256="b".repeat(64);})], + ["manifest digest",f=>edit(path.join(f.input,TARGETS[0],"manifest.json"),p=>{p.artifacts[binaryFor(TARGETS[0])]="b".repeat(64);})], + ["duplicate metadata key",f=>{const file=path.join(f.input,TARGETS[0],"provenance.json");const text=fs.readFileSync(file,"utf8");fs.writeFileSync(file,text.replace('"schema":1','"schema":1,"schema":1'));}], + ["duplicate manifest key",f=>{const file=path.join(f.input,TARGETS[0],"manifest.json");const text=fs.readFileSync(file,"utf8");fs.writeFileSync(file,text.replace('"schema":1','"schema":1,"schema":1'));}], + ["duplicate binary key",f=>{const file=path.join(f.input,TARGETS[0],"manifest.json");const text=fs.readFileSync(file,"utf8"),name=binaryFor(TARGETS[0]);const value=JSON.parse(text).artifacts[name];fs.writeFileSync(file,text.replace(JSON.stringify(name)+":"+JSON.stringify(value),JSON.stringify(name)+":"+JSON.stringify(value)+","+JSON.stringify(name)+":"+JSON.stringify(value)));}], + ["unexpected file",f=>fs.writeFileSync(path.join(f.input,TARGETS[0],"extra"),"unexpected")], + ["unexpected binary",f=>fs.writeFileSync(path.join(f.input,TARGETS[0],"bin","extra"),"unexpected")], + ["symlink artifact",f=>{const dir=path.join(f.input,TARGETS[0]);fs.renameSync(dir,path.join(f.root,"held"));fs.symlinkSync(path.join(f.root,"held"),dir);}], + ["symlink binary",f=>{const file=path.join(f.input,TARGETS[0],"bin",binaryFor(TARGETS[0]));fs.renameSync(file,path.join(f.root,"held"));fs.symlinkSync(path.join(f.root,"held"),file);}], + ["symlink metadata",f=>{const file=path.join(f.input,TARGETS[0],"manifest.json");fs.renameSync(file,path.join(f.root,"held"));fs.symlinkSync(path.join(f.root,"held"),file);}], +])test(`assembly refuses ${label} before output`,()=>{const f=fixture();mutate(f);assert.throws(()=>run(f));assert.equal(fs.existsSync(f.output),false);}); +test("build refuses unsupported host targets and invalid revisions",()=>{const f=fixture();assert.throws(()=>build({output:f.output,revision,target:"win32-x64"}));assert.throws(()=>build({output:f.output,revision:"invalid"}));}); +test("local development build preserves other target artifacts and emits isolated provenance",{skip:!TARGETS.includes(`${process.platform}-${process.arch}`)},()=>{const f=fixture();const output=path.join(f.root,"build");fs.mkdirSync(path.join(output,"bin"),{recursive:true});const other=TARGETS.find(t=>t!==`${process.platform}-${process.arch}`),name=binaryFor(other),bytes=Buffer.from("previous independently verified synthetic artifact");fs.writeFileSync(path.join(output,"bin",name),bytes);fs.writeFileSync(path.join(output,"manifest.json"),JSON.stringify({schema:1,artifacts:{[name]:digest(bytes)}}));const result=build({output,revision});const manifest=JSON.parse(fs.readFileSync(path.join(output,"manifest.json")));assert.equal(manifest.artifacts[name],digest(bytes));assert.equal(manifest.artifacts[binaryFor(result.target)],result.digest);const provenance=JSON.parse(fs.readFileSync(path.join(output,"provenance.json")));assert.deepEqual(provenance,{schema:1,source_revision:revision,source_sha256:source,target:result.target,binary_sha256:result.digest});}); diff --git a/test/deployment-credential.test.js b/test/deployment-credential.test.js index 70f13c7..5e8a2b8 100644 --- a/test/deployment-credential.test.js +++ b/test/deployment-credential.test.js @@ -216,7 +216,7 @@ describe("deployment credential file", { skip: isWindows }, () => { assertFails(swapped, "credential_changed", { file: second, token }); }); - test("rechecks the file after the read and refuses any change made while it was read", () => { + test("rechecks the file after the read and refuses any change made while it was read", async (t) => { // Each case runs after the content was read and before it is checked // again. Replacement content has the same length as the original. const cases = [ @@ -228,9 +228,9 @@ describe("deployment credential file", { skip: isWindows }, () => { fs.chmodSync(file, 0o644); fs.chmodSync(file, 0o600); }, - "credential_changed", + "credential_changed", true, ], - ["rewritten in place", (file, token) => fs.writeFileSync(file, newToken().slice(0, token.length)), "credential_changed"], + ["rewritten in place", (file, token) => fs.writeFileSync(file, newToken().slice(0, token.length)), "credential_changed", true], [ "one byte overwritten without truncation", (file) => { @@ -241,7 +241,7 @@ describe("deployment credential file", { skip: isWindows }, () => { fs.closeSync(fd); } }, - "credential_changed", + "credential_changed", true, ], ["second link added", (file) => fs.linkSync(file, `${file}-late`), "credential_hardlinked"], ["replaced by rename", (file, token) => { @@ -250,12 +250,43 @@ describe("deployment credential file", { skip: isWindows }, () => { fs.renameSync(other, file); }, "credential_changed"], ]; - for (const [name, change, reason] of cases) { - const token = newToken(); - const file = writePrivate(privateDir(), token); - const result = readCredentialFile(file, { afterRead: () => change(file, token) }); - assert.equal(result.reason, reason, name); - assertFails(result, reason, { file, token }); + for (const [name, change, reason, needsTimestamp] of cases) { + await t.test(name, (subtest) => { + const token = newToken(); + const file = writePrivate(privateDir(), token); + let timestampChanged = !needsTimestamp; + let beforeChange = null; + let afterChange = null; + const result = readCredentialFile(file, { afterRead: () => { + const before = fs.statSync(file, { bigint: true }); + beforeChange = before; + // Some Linux filesystems coalesce consecutive metadata updates in + // one clock tick. Establish the timestamp-change premise here, + // inside the test seam; production reading never waits or retries. + const until = performance.now() + 1000; + do { + change(file, token); + if (!needsTimestamp) break; + const after = fs.statSync(file, { bigint: true }); + timestampChanged = after.ctimeNs !== before.ctimeNs || after.mtimeNs !== before.mtimeNs; + if (timestampChanged || performance.now() >= until) break; + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5); + } while (!timestampChanged); + afterChange = fs.statSync(file, { bigint: true }); + } }); + assert.notEqual(beforeChange, null, "read reached the mutation seam"); + assert.notEqual(afterChange, null, "mutation finished"); + if (name === "mode widened and restored") { + for (const field of ["mode", "uid", "gid", "size", "mtimeNs"]) assert.equal(afterChange[field], beforeChange[field], field); + } + if (!timestampChanged) { + subtest.skip("filesystem did not advance metadata timestamps within one second"); + return; + } + if (name === "mode widened and restored") assert.notEqual(afterChange.ctimeNs, beforeChange.ctimeNs, "ctime-change premise"); + assert.equal(result.reason, reason, name); + assertFails(result, reason, { file, token }); + }); } // The seam itself does not disturb an unchanged file. diff --git a/test/directory-containment.test.js b/test/directory-containment.test.js new file mode 100644 index 0000000..1f21e46 --- /dev/null +++ b/test/directory-containment.test.js @@ -0,0 +1,137 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; + +import anchoredFs, { hasVerifiedHelper } from "../src/anchored-fs.js"; +import { runSkill } from "../src/skill.js"; +import { commitEnv, preflightEnv, rollbackEnv } from "../src/setup-env.js"; +import { bindingFor, readBinding, resolveProject, writeBinding } from "../src/auth-binding.js"; +import { newSetupState, readSetupState, writeSetupState } from "../src/setup-state.js"; +import { newSlot, openStore, writeCredential } from "../src/auth-store.js"; +import { waiterRecord } from "../src/setup-refusal.js"; + +const supported = hasVerifiedHelper(); +const work = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "directory containment "))); +after(() => fs.rmSync(work, { recursive: true, force: true })); +let counter = 0; +function box() { + const base = path.join(work, String(++counter)); + const root = path.join(base, "project"); + const outside = path.join(base, "outside"); + fs.mkdirSync(root, { recursive: true }); + fs.mkdirSync(outside); + fs.writeFileSync(path.join(outside, "sentinel"), "unchanged"); + return { root, outside, base }; +} +function swap(dir, outside) { + fs.renameSync(dir, `${dir}.held`); + fs.symlinkSync(outside, dir, "dir"); +} +function assertOutside(outside) { + assert.deepEqual(fs.readdirSync(outside), ["sentinel"]); + assert.equal(fs.readFileSync(path.join(outside, "sentinel"), "utf8"), "unchanged"); +} + +for (const phase of ["before-lock", "before-temp", "after-skill", "after-receipt"]) { + test(`skill ancestor substitution ${phase} cannot redirect writes or rollback`, { skip: !supported }, () => { + const { root, outside } = box(); + fs.mkdirSync(path.join(root, ".metergraph")); + fs.mkdirSync(path.join(root, ".agents")); + const originalOpen = anchoredFs.openSync; + const originalRename = anchoredFs.renameSync; + let swapped = false; + const maybeSwap = () => { if (!swapped) { swapped = true; swap(root, outside); } }; + anchoredFs.openSync = (file, flags, mode) => { + if (phase === "before-lock" && String(file).endsWith("skill-installations.lock")) maybeSwap(); + if (phase === "before-temp" && String(file).endsWith(".tmp")) maybeSwap(); + return originalOpen(file, flags, mode); + }; + anchoredFs.renameSync = (from, to) => { + const result = originalRename(from, to); + if (phase === "after-skill" && String(to).endsWith("SKILL.md")) maybeSwap(); + if (phase === "after-receipt" && String(to).endsWith("skill-installations.json")) maybeSwap(); + return result; + }; + let result; + try { result = runSkill({ action: "install", client: "codex", runtime: "local", project: root }); } + finally { anchoredFs.openSync = originalOpen; anchoredFs.renameSync = originalRename; } + assert.equal(swapped, true); + assert.notEqual(result.outcome, "ok"); + assertOutside(outside); + assert.equal(fs.existsSync(path.join(`${root}.held`, ".agents/skills/metergraph/SKILL.md")), false); + assert.equal(fs.existsSync(path.join(`${root}.held`, ".metergraph/skill-installations.json")), false); + }); +} + +test("env parent substitution after preflight refuses token creation", { skip: !supported }, async () => { + const { root, outside } = box(); + const plan = preflightEnv({ project: root }); + swap(root, outside); + await assert.rejects(commitEnv(plan, { token: "mg_fixture_synthetic_app_token_0123456789abcdef" })); + assertOutside(outside); + assert.equal(fs.existsSync(path.join(`${root}.held`, ".env")), false); +}); + +test("rollback stays on pinned directory when project is substituted after commit", { skip: !supported }, async () => { + const { root, outside } = box(); + const result = await commitEnv(preflightEnv({ project: root }), { + token: "mg_fixture_synthetic_app_token_0123456789abcdef", + }); + swap(root, outside); + await rollbackEnv(result.rollback); + assertOutside(outside); + assert.deepEqual(fs.readdirSync(`${root}.held`), []); +}); + +test("legitimate install remains idempotent", { skip: !supported }, () => { + const { root, outside } = box(); + const options = { action: "install", client: "codex", runtime: "local", project: root }; + assert.equal(runSkill(options).outcome, "ok"); + const file = path.join(root, ".agents/skills/metergraph/SKILL.md"); + const before = fs.statSync(file, { bigint: true }); + assert.equal(runSkill(options).outcome, "ok"); + assert.equal(fs.statSync(file, { bigint: true }).ino, before.ino); + assertOutside(outside); +}); + +for (const boundary of ["binding", "setup-state", "refusal"]) { + test(`${boundary} cannot write through a substituted metadata directory`, { skip: !supported }, () => { + const { root, outside } = box(); + const meta = path.join(root, ".metergraph"); + fs.mkdirSync(meta); + resolveProject(root); + readBinding(root); + readSetupState(root); + const waiter = waiterRecord(root, "11111111-1111-4111-8111-111111111111"); + swap(meta, outside); + if (boundary === "binding") { + const binding = bindingFor({ origin: "https://api.example.com", workspaceId: "11111111-1111-4111-8111-111111111111", profile: "managed", slot: "a".repeat(32) }); + assert.throws(() => writeBinding(root, binding, null)); + } else if (boundary === "setup-state") { + const state = newSetupState("https://api.example.com", "11111111-1111-4111-8111-111111111111", "managed", "codex"); + assert.throws(() => writeSetupState(root, state, null)); + } else assert.equal(waiter.redeeming(), false); + assertOutside(outside); + assert.deepEqual(fs.readdirSync(`${meta}.held`), []); + }); +} + +for (const replacement of ["symlink", "directory"]) test(`private store ${replacement} substitution cannot redirect credential bytes`, { skip: !supported }, () => { + const { root, outside } = box(); + const store = openStore(path.join(root, "private"), { create: true }); + if (replacement === "symlink") swap(store.credentials, outside); + else { + fs.renameSync(store.credentials, `${store.credentials}.held`); + fs.renameSync(outside, store.credentials); + } + const origin = "https://api.example.com"; + const credential = { schema_version: 1, origin, issuer: `${origin}/v1/oauth`, resource: `${origin}/v1/agent/mcp`, + deployment_profile: "managed", workspace_id: "11111111-1111-4111-8111-111111111111", client_id: "synthetic-client", + scope: "agent:metadata", access_token: "synthetic-access-token", refresh_token: "synthetic-refresh-token", + expires_at: Date.now() + 3600000, refresh_pending: false }; + assert.throws(() => writeCredential(store, newSlot(), credential)); + assertOutside(replacement === "symlink" ? outside : store.credentials); + assert.deepEqual(fs.readdirSync(`${store.credentials}.held`), []); +}); diff --git a/test/fixtures/fs-faults.js b/test/fixtures/fs-faults.js index 11bfdd2..fd86a19 100644 --- a/test/fixtures/fs-faults.js +++ b/test/fixtures/fs-faults.js @@ -8,11 +8,12 @@ // binding-partial as binding-rename, and removing the saved grant fails too // binding-unlink removing .metergraph/project.json fails import fs from "node:fs"; +import anchoredFs from "../../src/anchored-fs.js"; import { syncBuiltinESMExports } from "node:module"; const fault = process.env.METERGRAPH_TEST_FAULT; -const renameSync = fs.renameSync; -const unlinkSync = fs.unlinkSync; +const renameSync = anchoredFs.renameSync; +const unlinkSync = anchoredFs.unlinkSync; const CREDENTIAL = /credentials[\\/][0-9a-f]{32}\.json$/; function failure() { @@ -21,7 +22,7 @@ function failure() { return error; } -fs.renameSync = (from, to) => { +anchoredFs.renameSync = (from, to) => { const dest = String(to); if (fault === "receipt-rename" && dest.endsWith("skill-installations.json")) throw failure(); if (fault === "credential-rename" && CREDENTIAL.test(dest)) throw failure(); @@ -33,7 +34,7 @@ fs.renameSync = (from, to) => { } }; -fs.unlinkSync = (file) => { +anchoredFs.unlinkSync = (file) => { if (fault === "binding-partial" && CREDENTIAL.test(String(file))) throw failure(); if (fault === "binding-unlink" && String(file).endsWith("project.json")) throw failure(); unlinkSync(file); diff --git a/test/fixtures/setup-env-faults.js b/test/fixtures/setup-env-faults.js index a357243..b015234 100644 --- a/test/fixtures/setup-env-faults.js +++ b/test/fixtures/setup-env-faults.js @@ -9,6 +9,7 @@ // edit-during-commit another writer appends to options.file as soon as the // first temporary file is created import fs from "node:fs"; +import anchoredFs from "../../src/anchored-fs.js"; import { syncBuiltinESMExports } from "node:module"; import path from "node:path"; @@ -28,9 +29,9 @@ export function clearFault() { setFault(null); } -const renameSync = fs.renameSync; -const unlinkSync = fs.unlinkSync; -const openSync = fs.openSync; +const renameSync = anchoredFs.renameSync; +const unlinkSync = anchoredFs.unlinkSync; +const openSync = anchoredFs.openSync; const TEMP = /[\\/]\.metergraph-[0-9a-f]{12}\.tmp$/; function failure(code) { @@ -41,7 +42,7 @@ function failure(code) { const isIgnoreFile = (file) => path.basename(String(file)) === ".gitignore"; -fs.renameSync = (from, to) => { +anchoredFs.renameSync = (from, to) => { if (TEMP.test(String(from))) { if (isIgnoreFile(to)) { ignoreRenames += 1; @@ -55,12 +56,12 @@ fs.renameSync = (from, to) => { return renameSync(from, to); }; -fs.unlinkSync = (file) => { +anchoredFs.unlinkSync = (file) => { if (fault === "rollback-blocked" && isIgnoreFile(file)) throw failure("EIO"); return unlinkSync(file); }; -fs.openSync = (file, flags, mode) => { +anchoredFs.openSync = (file, flags, mode) => { if (fault === "edit-during-commit" && !edited && flags === "wx" && TEMP.test(String(file))) { edited = true; fs.appendFileSync(options.file, "SYNTHETIC_CONCURRENT_EDIT=1\n"); diff --git a/test/native-artifact-install.test.js b/test/native-artifact-install.test.js new file mode 100644 index 0000000..7159533 --- /dev/null +++ b/test/native-artifact-install.test.js @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { test } from "node:test"; +import { TARGETS } from "../native/targets.mjs"; + +const source = fileURLToPath(new URL("../native/", import.meta.url)); +const revision = "1".repeat(40); +const hash = bytes => createHash("sha256").update(bytes).digest("hex"); + +test("CI installation verifies the host before replacing checkout artifacts", { skip: process.platform === "win32" }, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "native-artifact-install-")); + try { + const checkout = path.join(root, "native"); + fs.cpSync(source, checkout, { recursive: true }); + const bin = path.join(checkout, "bin"); + const before = new Map(fs.readdirSync(bin).map(name => [name, fs.readFileSync(path.join(bin, name))])); + const artifact = path.join(root, "artifact"); + fs.mkdirSync(path.join(artifact, "bin"), { recursive: true }); + const current = `${process.platform}-${process.arch}`; + const foreign = TARGETS.find(value => value !== current); + const bytes = Buffer.from("synthetic-artifact-bytes"); + function write(target) { + for (const name of fs.readdirSync(path.join(artifact, "bin"))) fs.unlinkSync(path.join(artifact, "bin", name)); + const name = `anchored-fs-${target}`; + fs.writeFileSync(path.join(artifact, "bin", name), bytes); + fs.writeFileSync(path.join(artifact, "manifest.json"), JSON.stringify({ schema: 1, artifacts: { [name]: hash(bytes) } })); + fs.writeFileSync(path.join(artifact, "provenance.json"), JSON.stringify({ schema: 1, source_revision: revision, + source_sha256: hash(fs.readFileSync(path.join(checkout, "anchored-fs.c"))), target, binary_sha256: hash(bytes) })); + } + const run = () => spawnSync(process.execPath, [path.join(checkout, "install-artifact.mjs"), "--input", artifact, "--revision", revision], { encoding: "utf8" }); + write(foreign); + assert.notEqual(run().status, 0); + assert.deepEqual(fs.readdirSync(bin).sort(), [...before.keys()].sort()); + for (const [name, original] of before) assert.deepEqual(fs.readFileSync(path.join(bin, name)), original); + write(current); + const accepted = run(); + assert.equal(accepted.status, 0, accepted.stderr); + const name = `anchored-fs-${current}`; + assert.deepEqual(fs.readdirSync(bin), [name]); + assert.deepEqual(fs.readFileSync(path.join(bin, name)), bytes); + assert.equal(fs.statSync(path.join(bin, name)).mode & 0o777, 0o755); + } finally { fs.rmSync(root, { recursive: true, force: true }); } +}); diff --git a/test/package/pack.test.js b/test/package/pack.test.js index 30e4cc5..71fd931 100644 --- a/test/package/pack.test.js +++ b/test/package/pack.test.js @@ -10,6 +10,7 @@ import { after, before, test } from "node:test"; import { fileURLToPath, pathToFileURL } from "node:url"; import { healthyRoutes, parseJsonLine, startServer } from "../helpers.js"; +import { TARGETS, binaryFor } from "../../native/targets.mjs"; const PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url)); const sourcePackage = JSON.parse(readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf8")); @@ -32,9 +33,15 @@ const EXPECTED_FILES = [ "assets/skills/metergraph-report/SKILL.md", "assets/skills/metergraph-workloads/SKILL.md", "bin/metergraph.js", + "native/README.md", + "native/anchored-fs.c", + "native/build.mjs", + "native/manifest.json", + "native/targets.mjs", "package.json", "src/action-help.js", "src/agent-key.js", + "src/anchored-fs.js", "src/approval-handoff.js", "src/args.js", "src/auth-binding.js", @@ -164,7 +171,16 @@ after(() => { }); test("the tarball contains exactly the allowlisted files", () => { - assert.deepEqual(packedFiles, EXPECTED_FILES); + const manifest = JSON.parse(readFileSync(path.join(PACKAGE_ROOT, "native", "manifest.json"), "utf8")); + assert.equal(manifest.schema, 1); + const artifacts = Object.entries(manifest.artifacts); + assert.ok(artifacts.length > 0); + for (const [name, digest] of artifacts) { + assert.ok(TARGETS.some(target => binaryFor(target) === name), "unrecognised native artifact"); + const bytes = readFileSync(path.join(PACKAGE_ROOT, "native", "bin", name)); + assert.equal(createHash("sha256").update(bytes).digest("hex"), digest); + } + assert.deepEqual(packedFiles, [...EXPECTED_FILES, ...artifacts.map(([name]) => `native/bin/${name}`)].sort()); assert.ok(path.basename(tarball).startsWith("metergraph-cli-")); }); @@ -243,7 +259,9 @@ test("the installed CLI installs the skill offline into a project with spaces", target, "--json", ]; - const result = check(await run(process.execPath, args, { cwd: workDir }), "packed skill install"); + const noTools = path.join(workDir, "no compilers or download tools"); + mkdirSync(noTools); + const result = check(await run(process.execPath, args, { cwd: workDir, env: { ...npmEnv, PATH: noTools } }), "packed skill install without compiler or download tools"); const parsed = parseJsonLine(result.stdout); assert.equal(parsed.data.status, "installed"); assert.equal(parsed.data.discovery, "pending"); @@ -257,6 +275,27 @@ test("the installed CLI installs the skill offline into a project with spaces", assert.equal(parseJsonLine(rerun.stdout).data.status, "reused"); }); +test("missing or altered helper artifacts refuse without writing the project", async () => { + const installedRoot = path.join(projectDir, "node_modules", "metergraph-cli"); + const manifestFile = path.join(installedRoot, "native", "manifest.json"); + const original = readFileSync(manifestFile); + const bin = path.join(installedRoot, "bin", "metergraph.js"); + for (const artifacts of [{}, { [`anchored-fs-${process.platform}-${process.arch}`]: "0".repeat(64) }]) { + const target = path.join(workDir, `helper refusal ${Object.keys(artifacts).length}`); + mkdirSync(target); + try { + writeFileSync(manifestFile, JSON.stringify({ schema: 1, artifacts })); + const result = await run(process.execPath, [bin, "skill", "install", "--client", "codex", "--project", target, "--json"], { cwd: workDir }); + assert.notEqual(result.code, 0); + assert.equal(parseJsonLine(result.stdout).error.reason, "secure_writes_unavailable"); + assert.equal(existsSync(path.join(target, ".agents")), false); + assert.equal(existsSync(path.join(target, ".metergraph")), false); + } finally { + writeFileSync(manifestFile, original); + } + } +}); + test("the installed CLI installs the workflow skills offline from the packed pack", async () => { const target = path.join(workDir, "skills project"); mkdirSync(target, { recursive: true }); diff --git a/test/unsupported-filesystem.test.js b/test/unsupported-filesystem.test.js new file mode 100644 index 0000000..d0a8f1a --- /dev/null +++ b/test/unsupported-filesystem.test.js @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +import anchored, { hasVerifiedHelper } from "../src/anchored-fs.js"; +import { resolveProject, writeBinding } from "../src/auth-binding.js"; +import { openStore } from "../src/auth-store.js"; +import { preflightEnv } from "../src/setup-env.js"; +import { newSetupState, writeSetupState } from "../src/setup-state.js"; +import { runSkill, runSkillPack } from "../src/skill.js"; +import { waiterRecord } from "../src/setup-refusal.js"; + +const unsupported = !hasVerifiedHelper(); +const root = fs.mkdtempSync(path.join(os.tmpdir(), "unsupported-filesystem-")); +after(() => fs.rmSync(root, { recursive: true, force: true })); +const workspace = "11111111-1111-4111-8111-111111111111"; + +test("an unavailable helper refuses filesystem operations without a pathname fallback", { skip: !unsupported }, () => { + for (const operation of [ + () => anchored.mkdirSync(path.join(root, "created")), + () => anchored.openSync(path.join(root, "token"), "wx", 0o600), + () => anchored.unlinkSync(path.join(root, "existing")), + () => anchored.renameSync(path.join(root, "existing"), path.join(root, "renamed")), + ]) assert.throws(operation, { code: "ENOTSUP" }); + assert.deepEqual(fs.readdirSync(root), []); +}); + +test("unsupported platforms refuse install, env, state, binding and credential-store writes", { skip: !unsupported }, () => { + const options = { action: "install", client: "codex", runtime: "local", project: root }; + for (const install of [runSkill, runSkillPack]) { + const result = install(options); + assert.equal(result.outcome, "unsupported"); + assert.equal(result.reason, "secure_writes_unavailable"); + } + assert.throws(() => resolveProject(root), error => error.reason === "secure_writes_unavailable"); + const unavailable = error => error.outcome === "unsupported" && error.reason === "secure_writes_unavailable"; + assert.throws(() => preflightEnv({ project: root }), unavailable); + assert.throws(() => openStore(path.join(root, "private"), { create: true }), unavailable); + assert.throws(() => writeSetupState(root, newSetupState("https://api.example.com", workspace, "managed", "codex"), null), unavailable); + assert.throws(() => writeBinding(root, { schema_version: 1, origin: "https://api.example.com", + workspace_id: workspace, deployment_profile: "managed", credential_slot: "a".repeat(32) }, null), unavailable); + assert.equal(waiterRecord(root, workspace).redeeming(), false); + assert.deepEqual(fs.readdirSync(root), []); +}); + +test("public CLI JSON names unavailable secure writes before setup or login side effects", { skip: !unsupported }, () => { + const env = { ...process.env }; + for (const name of ["NODE_TEST_CONTEXT", "CI", "SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "CODESPACES", "GITPOD_WORKSPACE_ID", "CLOUD_SHELL"]) delete env[name]; + env.METERGRAPH_CONFIG_DIR = path.join(root, "private"); + env.METERGRAPH_AGENT_TOKEN = ""; + env.METERGRAPH_URL = ""; + const bin = fileURLToPath(new URL("../bin/metergraph.js", import.meta.url)); + for (const command of [ + ["skill", "install", "--client", "codex"], + ["skills", "install", "--client", "codex"], + ["setup", "--client", "codex"], + ["login"], + ]) { + const child = spawnSync(process.execPath, [bin, ...command, "--runtime", "local", "--project", root, "--json"], { env, encoding: "utf8", timeout: 10000 }); + assert.notEqual(child.status, 0, child.stdout + child.stderr); + const result = JSON.parse(child.stdout); + assert.equal(result.outcome, "unsupported", child.stdout); + assert.equal(result.error.reason, "secure_writes_unavailable", child.stdout); + assert.equal(fs.readdirSync(root).length, 0); + } +}); + +test("the no-helper contract also runs in an isolated package on a supported host", { skip: unsupported }, () => { + const source = fileURLToPath(new URL("../", import.meta.url)); + const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "missing-helper-package-")); + try { + for (const name of ["src", "assets", "bin", "package.json"]) { + fs.cpSync(path.join(source, name), path.join(fixture, name), { recursive: true }); + } + fs.mkdirSync(path.join(fixture, "test")); + fs.copyFileSync(fileURLToPath(import.meta.url), path.join(fixture, "test", "unsupported-filesystem.test.js")); + const env = { ...process.env }; + delete env.NODE_TEST_CONTEXT; + const child = spawnSync(process.execPath, ["--test", "test/unsupported-filesystem.test.js"], { + cwd: fixture, encoding: "utf8", timeout: 15000, env, + }); + assert.equal(child.status, 0, child.stdout + child.stderr); + assert.match(child.stdout, /pass 3/); + } finally { + fs.rmSync(fixture, { recursive: true, force: true }); + } +});