From aae01d9d2a99d18075e033e77420ba01683146fd Mon Sep 17 00:00:00 2001 From: Sam Bretz Date: Thu, 22 Oct 2026 17:38:59 -0700 Subject: [PATCH 1/7] Anchor local filesystem operations to retained directory handles --- README.md | 16 +- native/README.md | 55 +++++ native/anchored-fs.c | 233 ++++++++++++++++++ native/bin/anchored-fs-darwin-arm64 | Bin 0 -> 35304 bytes native/build.mjs | 13 + native/manifest.json | 6 + package.json | 6 + .../src/metergraph_skills/installer.py | 206 ++++++++++------ .../metergraph-skills/tests/test_anchored.py | 106 ++++++++ .../metergraph-skills/tests/test_installer.py | 13 + src/anchored-fs.js | 144 +++++++++++ src/auth-binding.js | 11 +- src/auth-store.js | 6 +- src/output.js | 2 + src/repository-identity.js | 4 +- src/setup-env-git.js | 2 +- src/setup-env.js | 22 +- src/setup-refusal.js | 4 +- src/setup-state.js | 6 +- src/skill.js | 31 ++- test/anchored-fs.test.js | 122 +++++++++ test/auth-session.test.js | 7 +- test/auth-store.test.js | 7 +- test/directory-containment.test.js | 137 ++++++++++ test/fixtures/fs-faults.js | 9 +- test/fixtures/setup-env-faults.js | 13 +- test/package/pack.test.js | 31 ++- 27 files changed, 1081 insertions(+), 131 deletions(-) create mode 100644 native/README.md create mode 100644 native/anchored-fs.c create mode 100755 native/bin/anchored-fs-darwin-arm64 create mode 100644 native/build.mjs create mode 100644 native/manifest.json create mode 100644 python/metergraph-skills/tests/test_anchored.py create mode 100644 src/anchored-fs.js create mode 100644 test/anchored-fs.test.js create mode 100644 test/directory-containment.test.js 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..fb40f19 --- /dev/null +++ b/native/README.md @@ -0,0 +1,55 @@ +# 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 | shipped in `bin/` | local Node 24 tests | +| macOS x64 | absent | refuses secure filesystem operations | +| Linux arm64/x64 | absent | refuses secure filesystem operations | +| 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. +Node 22, Linux, and Windows execution remain release verification gates. + +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/anchored-fs.c b/native/anchored-fs.c new file mode 100644 index 0000000..dbe565c --- /dev/null +++ b/native/anchored-fs.c @@ -0,0 +1,233 @@ +#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 +/* 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_dev,s->st_ino,s->st_mode,s->st_nlink,s->st_uid,s->st_gid,s->st_size,(uint64_t)s->st_mtime}; + for(int i=0;i<8;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[64];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=64;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=64;}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*Q4Ww(3w zoISheym!vc_ucQ${qFsJ_q*Ts-elgqed(`PlZgbvC4$mGCL__KWJQiB7gPdrI@c8c z!yWhBQM#H-$6iY3u|z)d7 zIybpSQMXLbJj~;Pj@a~wepT-%T=_95y4XSx&61LRiAM@%X&1 z=4t%s=1E*F^(x@J!L%?G~Tn^9&3K_y(=YLb#yuoJ#j zI|C((eO!&p2K!hJujkl{$6W~GI<|voHChOxxOs^bEHedxn<^-iVZV z0{TB;GRt9;Acwo9yig%|N@dVg&=U#NF(9b1HJ>xyh46=>2_|nDOB{a zM83hLlJ`sC1J$9T4@7#RMDqB}Mw+->BL8(pPw8@uS0Io#^ZG@dQ5g@R{RQ+@c$4UD z1wYg;`_H)Ka3XoqvJ72mFU_C=VEIlC^zMC_db)Q>1wCmLzA#VnJ_Wt7&N61ApNV9@ zWg;~eSCZq40`+2gN(ZG3-)Sk+cQ@(>u0{@)Z=l`|k@g-C>3C)&a$x9f*`I9=+%qI* zC0T@$n|jc9Ab}>%M|)2t^|EfCfG$eeJ|1Uc%s5A!{qFF;WNCod1%PF&^=Bzc1(b$kk4iVf89Mfe4<^2&EnVW?6L4*=^yjGqsgr%>;?GgLIRYf)#{ z=9<2T=0Sd{r&JX7<#8JUHn2^(XnUYdI>Gh(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OoBcLOoBcLOo zBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOo zBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLOoBcLPje+U69bm4dCzX`%S_LcYX zBT+8(d;e-){jPmXUdG!1WR>T?{0;&99vcbx(!Q_|bRTFlXa}er)B$=P)C+nQ^e*T$ z=-)x2fPNq=XfEhB&{05CL!HXN1-=y*1 z#S0vmcWJx{FLGeMMdRBwzD?tw!wVj`9>0yG==XcP=z;mCG`<}#d|>{0=J}-+9+mGN z;f+fDk2KzZH(hZ1gBowr_*bGlB`Ed3)c9nL|Fy=aYCOX}K~UdrfhywnR!l&Kf4_ox zelG=5&MMdS_#4X?#qlfRcwVou?bpTe&NyCiiJ0-W#MN($<9EjKkHqnh$MIO&WAu40 zj{ja9|3V!9QXK!YI6e@^|00e@C>b;U2XQ>Y%$WK=$MFb3W9l!*@sbMm$b2Qo@tJWv zem7~1Jbr%(`vAvKepd;$VA(Ze-4)o|_HTH&s0 zXm(cf-i0lss9a;YKa@$%m&^_ zu{T0M1A4n_xjve?^kH%Uo~|u#o^i@R8N#37CHzn-e#D1EVI!!FD{R-E8N>_8*Z#{*DolfdB1#k$_5(c362+LwSIGQ<)LX;FYS43^}Qc`^w+YE^RGO)zVMAbQ__lbY|z`obnI77rbBoX7%^;-0OF~>H5PR@4WcX4}MbSdgDxW!0_u6 zC+fu2WyZ+P-klFT`oYV4OZLqAe$Ed!e{I}dbv3bL-aEzWoE^ z=NEVGsQj<`|4-|OCr$k0YmfYK*KOJRZm8(bTlDPUfj>=t_Z#j@)kgx`O1pS+{sWw4 B8utJI literal 0 HcmV?d00001 diff --git a/native/build.mjs b/native/build.mjs new file mode 100644 index 0000000..26429ea --- /dev/null +++ b/native/build.mjs @@ -0,0 +1,13 @@ +// Development/release build only. Package consumers never run a compiler. +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +const root = path.dirname(fileURLToPath(import.meta.url)); +if (process.platform !== "darwin" || process.arch !== "arm64") throw new Error("target has not been verified"); +const name = `anchored-fs-${process.platform}-${process.arch}`; +const result = spawnSync("clang", ["-std=c11", "-Wall", "-Wextra", "-Werror", "-O2", path.join(root,"anchored-fs.c"), "-o", path.join(root,"bin",name)], {stdio:"inherit"}); +if (result.status !== 0) process.exit(1); +const digest = createHash("sha256").update(fs.readFileSync(path.join(root,"bin",name))).digest("hex"); +fs.writeFileSync(path.join(root,"manifest.json"),`${JSON.stringify({schema:1,artifacts:{[name]:digest}},null,2)}\n`); diff --git a/native/manifest.json b/native/manifest.json new file mode 100644 index 0000000..6b079f0 --- /dev/null +++ b/native/manifest.json @@ -0,0 +1,6 @@ +{ + "schema": 1, + "artifacts": { + "anchored-fs-darwin-arm64": "a6c503d2c0fadb39e0a611c0a7782c862dbb4406db58b697e2aaa985c1014d47" + } +} diff --git a/package.json b/package.json index 00d1a79..252ece6 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,11 @@ "files": [ "bin/metergraph.js", "src/*.js", + "native/anchored-fs.c", + "native/build.mjs", + "native/manifest.json", + "native/README.md", + "native/bin/*", "assets/skill/SKILL.md", "assets/skill/manifest.json", "assets/skills/manifest.json", @@ -20,6 +25,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..20ece46 100644 --- a/python/metergraph-skills/src/metergraph_skills/installer.py +++ b/python/metergraph-skills/src/metergraph_skills/installer.py @@ -53,8 +53,11 @@ # 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. +DIRECTORY_ACCESS = getattr(os, "O_SEARCH", getattr(os, "O_PATH", os.O_RDONLY)) 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 +143,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 +159,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 +173,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 +187,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 +213,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 +255,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 +277,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 +367,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 +481,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..91d58db --- /dev/null +++ b/python/metergraph-skills/tests/test_anchored.py @@ -0,0 +1,106 @@ +"""Deterministic ancestor replacement tests for retained directory handles.""" +import os +import shutil +import sys +import tempfile +import unittest +from pathlib import Path +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): + # 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..af07737 --- /dev/null +++ b/src/anchored-fs.js @@ -0,0 +1,144 @@ +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 start() { + if (service !== null) return service; + 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"); } + 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) { + const keys = ["dev", "ino", "mode", "nlink", "uid", "gid", "size", "mtimeMs"]; + const result = {}; + keys.forEach((key, index) => { let n = bytes.readBigUInt64BE(index*8); if (key === "mtimeMs") n *= 1000n; result[key] = options?.bigint ? n : Number(n); }); + 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..b908dc3 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"); @@ -83,7 +84,7 @@ 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. } @@ -119,7 +120,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 +147,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..0061a03 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"; @@ -189,7 +189,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 +389,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..fdcd08d 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"; @@ -193,12 +193,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 +352,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 +365,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 +577,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 +604,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 +612,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 +631,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. } 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..b24453b 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"; @@ -139,7 +139,7 @@ export function writeSetupState(root, next, previous) { 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..e2ec0b5 --- /dev/null +++ b/test/anchored-fs.test.js @@ -0,0 +1,122 @@ +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 } from "../src/anchored-fs.js"; +const supported = process.platform === "darwin" && process.arch === "arm64"; +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("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-darwin-arm64",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>=72){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),64); + } + 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/directory-containment.test.js b/test/directory-containment.test.js new file mode 100644 index 0000000..e863f23 --- /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 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 = process.platform === "darwin" && process.arch === "arm64"; +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/package/pack.test.js b/test/package/pack.test.js index 30e4cc5..1e2a1c5 100644 --- a/test/package/pack.test.js +++ b/test/package/pack.test.js @@ -32,9 +32,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/bin/anchored-fs-darwin-arm64", + "native/build.mjs", + "native/manifest.json", "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", @@ -243,7 +249,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 +265,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 }); From da9aa56f92906c17b56bd7665dbeea8c22ecef89 Mon Sep 17 00:00:00 2001 From: Sam Bretz Date: Thu, 22 Oct 2026 17:33:31 -0700 Subject: [PATCH 2/7] Preserve release fixture bytes across platforms --- .gitattributes | 2 ++ test/agent-key.test.js | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index 99c7673..8ef23fb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -5,3 +5,5 @@ assets/skill/manifest.json -text python/metergraph-skills/src/metergraph_skills/skill/SKILL.md -text python/metergraph-skills/src/metergraph_skills/skill/manifest.json -text assets/skills/** -text +test/fixtures/prior-*.md -text +python/metergraph-skills/tests/fixtures/prior-*.md -text diff --git a/test/agent-key.test.js b/test/agent-key.test.js index c269a1b..83e0059 100644 --- a/test/agent-key.test.js +++ b/test/agent-key.test.js @@ -516,7 +516,7 @@ test("experiment help and reference describe Debug reads and all workflow permis assert.equal(run.code, 0, run.stdout); assert.match(run.stdout, /For list, estimate and get: a key with the Metadata or Debug role/); const reference = fs.readFileSync(new URL("../docs/reference.md", import.meta.url), "utf8"); - assert.match(reference, /workflow requires the Debug role with all three permissions: Allow evaluation\n writes, Allow evaluation previews and Allow analysis starts/); + assert.match(reference, /workflow requires the Debug role with all three permissions: Allow evaluation\r?\n writes, Allow evaluation previews and Allow analysis starts/); assert.match(reference, /accept keys with the Metadata or Debug role and send only Metadata requests/); assert.ok(!reference.includes("refuse a key that holds more than Metadata access")); }); From 37a0d06212d70ac8b5eef2215cce289fc6b4c8fa Mon Sep 17 00:00:00 2001 From: Sam Bretz Date: Thu, 22 Oct 2026 17:46:39 -0700 Subject: [PATCH 3/7] Build and verify packaged filesystem helpers across POSIX targets --- .github/workflows/ci.yml | 21 +++- .github/workflows/native-helpers.yml | 137 +++++++++++++++++++++++++++ native/README.md | 25 +++++ native/aggregate.mjs | 66 +++++++++++++ native/build.mjs | 56 +++++++++-- native/install-artifact.mjs | 21 ++++ native/targets.mjs | 24 +++++ package.json | 1 + src/anchored-fs.js | 13 ++- src/auth-binding.js | 3 + src/auth-store.js | 5 + src/setup-env.js | 3 + src/setup-state.js | 3 + test/anchored-fs.test.js | 6 +- test/build-artifacts.test.js | 37 ++++++++ test/directory-containment.test.js | 4 +- test/native-artifact-install.test.js | 48 ++++++++++ test/package/pack.test.js | 14 ++- test/unsupported-filesystem.test.js | 91 ++++++++++++++++++ 19 files changed, 561 insertions(+), 17 deletions(-) create mode 100644 .github/workflows/native-helpers.yml create mode 100644 native/aggregate.mjs create mode 100644 native/install-artifact.mjs create mode 100644 native/targets.mjs create mode 100644 test/build-artifacts.test.js create mode 100644 test/native-artifact-install.test.js create mode 100644 test/unsupported-filesystem.test.js 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/native/README.md b/native/README.md index fb40f19..baff6ba 100644 --- a/native/README.md +++ b/native/README.md @@ -26,6 +26,31 @@ handle-relative implementation and restrictive DACL creation before token bytes are written; POSIX operations are not emulated through Windows pathname APIs. Node 22, Linux, and Windows execution remain release verification gates. +## 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 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/build.mjs b/native/build.mjs index 26429ea..5a885be 100644 --- a/native/build.mjs +++ b/native/build.mjs @@ -1,13 +1,55 @@ // Development/release build only. Package consumers never run a compiler. import { spawnSync } from "node:child_process"; -import { createHash } from "node:crypto"; +import { createHash, randomBytes } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { TARGETS, DIGEST, REVISION, binaryFor, exactKeys, argumentsFor } from "./targets.mjs"; const root = path.dirname(fileURLToPath(import.meta.url)); -if (process.platform !== "darwin" || process.arch !== "arm64") throw new Error("target has not been verified"); -const name = `anchored-fs-${process.platform}-${process.arch}`; -const result = spawnSync("clang", ["-std=c11", "-Wall", "-Wextra", "-Werror", "-O2", path.join(root,"anchored-fs.c"), "-o", path.join(root,"bin",name)], {stdio:"inherit"}); -if (result.status !== 0) process.exit(1); -const digest = createHash("sha256").update(fs.readFileSync(path.join(root,"bin",name))).digest("hex"); -fs.writeFileSync(path.join(root,"manifest.json"),`${JSON.stringify({schema:1,artifacts:{[name]:digest}},null,2)}\n`); +const sha256 = bytes => 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/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 252ece6..11a3064 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "src/*.js", "native/anchored-fs.c", "native/build.mjs", + "native/targets.mjs", "native/manifest.json", "native/README.md", "native/bin/*", diff --git a/src/anchored-fs.js b/src/anchored-fs.js index af07737..1aab1e1 100644 --- a/src/anchored-fs.js +++ b/src/anchored-fs.js @@ -15,8 +15,7 @@ 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 start() { - if (service !== null) return service; +function verifiedHelper() { const name = `anchored-fs-${process.platform}-${process.arch}`; let file; try { @@ -26,6 +25,16 @@ function start() { 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; diff --git a/src/auth-binding.js b/src/auth-binding.js index b908dc3..aa557ac 100644 --- a/src/auth-binding.js +++ b/src/auth-binding.js @@ -46,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"); } } @@ -90,6 +91,7 @@ export function writeBinding(root, binding, previous) { } } 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"); } } @@ -104,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"); } } diff --git a/src/auth-store.js b/src/auth-store.js index 0061a03..e06ec55 100644 --- a/src/auth-store.js +++ b/src/auth-store.js @@ -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); diff --git a/src/setup-env.js b/src/setup-env.js index fdcd08d..cfc9ee8 100644 --- a/src/setup-env.js +++ b/src/setup-env.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.", @@ -674,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-state.js b/src/setup-state.js index b24453b..014d5ce 100644 --- a/src/setup-state.js +++ b/src/setup-state.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,6 +138,7 @@ 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 { diff --git a/test/anchored-fs.test.js b/test/anchored-fs.test.js index e2ec0b5..13cc327 100644 --- a/test/anchored-fs.test.js +++ b/test/anchored-fs.test.js @@ -3,8 +3,8 @@ 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 } from "../src/anchored-fs.js"; -const supported = process.platform === "darwin" && process.arch === "arm64"; +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; } @@ -65,7 +65,7 @@ test("resolving a pinned root again cannot rebind it through a substituted symli 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-darwin-arm64",import.meta.url).pathname,[],{stdio:["pipe","pipe","ignore"]}); + 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)=>{ 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/directory-containment.test.js b/test/directory-containment.test.js index e863f23..1f21e46 100644 --- a/test/directory-containment.test.js +++ b/test/directory-containment.test.js @@ -4,7 +4,7 @@ import os from "node:os"; import path from "node:path"; import { after, test } from "node:test"; -import anchoredFs from "../src/anchored-fs.js"; +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"; @@ -12,7 +12,7 @@ import { newSetupState, readSetupState, writeSetupState } from "../src/setup-sta import { newSlot, openStore, writeCredential } from "../src/auth-store.js"; import { waiterRecord } from "../src/setup-refusal.js"; -const supported = process.platform === "darwin" && process.arch === "arm64"; +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; 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 1e2a1c5..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")); @@ -34,9 +35,9 @@ const EXPECTED_FILES = [ "bin/metergraph.js", "native/README.md", "native/anchored-fs.c", - "native/bin/anchored-fs-darwin-arm64", "native/build.mjs", "native/manifest.json", + "native/targets.mjs", "package.json", "src/action-help.js", "src/agent-key.js", @@ -170,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-")); }); 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 }); + } +}); From 0850f449d9c637217f60a9104fa43520fd792c22 Mon Sep 17 00:00:00 2001 From: Sam Bretz Date: Thu, 22 Oct 2026 17:58:23 -0700 Subject: [PATCH 4/7] Preserve precise filesystem timestamps and establish metadata test premises --- native/anchored-fs.c | 22 ++++++++---- native/bin/anchored-fs-darwin-arm64 | Bin 35304 -> 35312 bytes native/manifest.json | 2 +- src/anchored-fs.js | 14 ++++++-- test/anchored-fs.test.js | 22 ++++++++++-- test/deployment-credential.test.js | 51 ++++++++++++++++++++++------ 6 files changed, 90 insertions(+), 21 deletions(-) diff --git a/native/anchored-fs.c b/native/anchored-fs.c index dbe565c..14b5f7a 100644 --- a/native/anchored-fs.c +++ b/native/anchored-fs.c @@ -17,6 +17,7 @@ * 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) @@ -119,8 +120,16 @@ static int expected(int parent,const char *name,int use_owned) { errno=ESTALE;return -1; } static void statbytes(unsigned char *out,const struct stat *s) { - 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)s->st_mtime}; - for(int i=0;i<8;i++)put64(out+i*8,fields[i]); +#if defined(__APPLE__) + struct timespec modified=s->st_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) { @@ -144,7 +153,7 @@ int main(void) { 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[64];void *output=out;uint32_t outlen=0; + 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; @@ -159,7 +168,7 @@ int main(void) { 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=64;if(parent>=0 && !S_ISLNK(st.st_mode))remember(parent,name,&st); + 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 */ @@ -175,7 +184,7 @@ int main(void) { 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=64;}break; + 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; @@ -195,7 +204,8 @@ int main(void) { 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; + 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); diff --git a/native/bin/anchored-fs-darwin-arm64 b/native/bin/anchored-fs-darwin-arm64 index 3f804aa79087939108f6852535e269d73eae08f3..88fb6d2fb5659c3e72bf60b168e3be115041e84f 100755 GIT binary patch delta 4510 zcmZu!3vg3q7C!ghq)l21ZPGm2Qj_wMPpevA8bXvjLRs?QpA^V-=Mmy`4x!nK! z|9Su4Ip?NJ5qlJI$3?N<9{Oxf&a8Wg1R|>8|L`|UnJ7%R9Cjpkoryi71g#Vm6)0iB zY5GVzm9*239LjlNn&o3{d$+dDw8%n7WwBZidXxjwne4y=wSP1pnQCmrc~++{lScLqltDHjB?B%$g!qio?1eIDj81^p7m+e7!{K1byz#K{nc2* z?AtV9dPo@7R5hQ^)~oIt5;b=WmqI0cUZc9-eNR01xkx)2q(H=|r<|81!aGnk4>sos z6!KeKu6-#*OCa7j+7yUxmy?pisPK>?Fh7d9OoLoPcE+mB8QwY)%wnzl-= zLnexSXO==c;anO~t^_#)$q`2m`BttW?;?R(2xlEqZgZz(X?=-v2WwC zm`GGjhacY+KePS~DF&<-`vl98IH~EC__xPzyVE6VENl*35>w^*b;` z-%T4uM(fGjmq`&-8rpm+jeLK9X@CCTkkUsH&HZMiPqJOB$sljThPqY@9Iuls+oof$ z-ALYmSg=h1A4eR8qfR3o3nQ4%u$F&IYS=(6xBQ5v9*oSy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`$NPo4W4N>h{5j=g(|;zkFNM#)!L=& z-!XLj{d@1LQ@4aJ8X0H(;*CvTY?y1`F=<(>s_BWuo_|yy`sLa)EA~Zy(h_28{tL20 BB<}zK diff --git a/native/manifest.json b/native/manifest.json index 6b079f0..2bbd119 100644 --- a/native/manifest.json +++ b/native/manifest.json @@ -1,6 +1,6 @@ { "schema": 1, "artifacts": { - "anchored-fs-darwin-arm64": "a6c503d2c0fadb39e0a611c0a7782c862dbb4406db58b697e2aaa985c1014d47" + "anchored-fs-darwin-arm64": "8469cd676ba1c0a7ba6aea9fbec78c8ecda4b77eafc71f64cee34156bf9e8f27" } } diff --git a/src/anchored-fs.js b/src/anchored-fs.js index 1aab1e1..13a3256 100644 --- a/src/anchored-fs.js +++ b/src/anchored-fs.js @@ -75,9 +75,19 @@ function canonical(value) { } function descriptor(value) { if (!Number.isSafeInteger(value) || value > -1001) throw failure("EBADF"); return -value - 1001; } function statResult(bytes, options) { - const keys = ["dev", "ino", "mode", "nlink", "uid", "gid", "size", "mtimeMs"]; + if (bytes.length !== 88) throw failure("EIO"); + const keys = ["dev", "ino", "mode", "nlink", "uid", "gid", "size"]; const result = {}; - keys.forEach((key, index) => { let n = bytes.readBigUInt64BE(index*8); if (key === "mtimeMs") n *= 1000n; result[key] = options?.bigint ? n : Number(n); }); + 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, diff --git a/test/anchored-fs.test.js b/test/anchored-fs.test.js index 13cc327..c64aef4 100644 --- a/test/anchored-fs.test.js +++ b/test/anchored-fs.test.js @@ -19,6 +19,24 @@ test("prebuilt helper reads, replaces, syncs and cleans without a runtime compil 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"); @@ -70,10 +88,10 @@ test("helper survives deferred terminal signals and exits when owner pipe closes 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>=72){child.stdout.off("data",data);resolve(Buffer.concat(pieces));}} + 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),64); + child.stdin.write(frame);const reply=await answer;assert.equal(reply.readUInt32BE(),0);assert.equal(reply.readUInt32BE(4),88); } try { await query(); 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. From f0be64f269886845ff930cb7e5f430c20317ee12 Mon Sep 17 00:00:00 2001 From: Sam Bretz Date: Thu, 22 Oct 2026 18:01:47 -0700 Subject: [PATCH 5/7] Preserve search-only directories on older macOS Python builds --- .../src/metergraph_skills/installer.py | 16 +++++++++++++++- python/metergraph-skills/tests/test_anchored.py | 13 +++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/python/metergraph-skills/src/metergraph_skills/installer.py b/python/metergraph-skills/src/metergraph_skills/installer.py index 20ece46..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 @@ -54,7 +55,20 @@ NAME_SURROGATE_BIT = 0x20000000 BINARY = getattr(os, "O_BINARY", 0) # Search handles preserve access to writable directories without read permission. -DIRECTORY_ACCESS = getattr(os, "O_SEARCH", getattr(os, "O_PATH", os.O_RDONLY)) +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.", diff --git a/python/metergraph-skills/tests/test_anchored.py b/python/metergraph-skills/tests/test_anchored.py index 91d58db..9264e24 100644 --- a/python/metergraph-skills/tests/test_anchored.py +++ b/python/metergraph-skills/tests/test_anchored.py @@ -5,6 +5,7 @@ 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')) @@ -85,6 +86,18 @@ def test_unavailable_backend_writes_nothing(self): 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'): From 708547224f8ae3618c3e8017ec398b04569a5bbe Mon Sep 17 00:00:00 2001 From: Sam Bretz Date: Thu, 22 Oct 2026 18:09:05 -0700 Subject: [PATCH 6/7] Ship the verified macOS and Linux filesystem helpers --- native/bin/anchored-fs-darwin-arm64 | Bin 35312 -> 35312 bytes native/bin/anchored-fs-darwin-x64 | Bin 0 -> 18520 bytes native/bin/anchored-fs-linux-arm64 | Bin 0 -> 19280 bytes native/bin/anchored-fs-linux-x64 | Bin 0 -> 22080 bytes native/manifest.json | 5 ++++- native/provenance.json | 11 +++++++++++ 6 files changed, 15 insertions(+), 1 deletion(-) create mode 100755 native/bin/anchored-fs-darwin-x64 create mode 100755 native/bin/anchored-fs-linux-arm64 create mode 100755 native/bin/anchored-fs-linux-x64 create mode 100644 native/provenance.json diff --git a/native/bin/anchored-fs-darwin-arm64 b/native/bin/anchored-fs-darwin-arm64 index 88fb6d2fb5659c3e72bf60b168e3be115041e84f..9dd9c778f57a0b132f50989505aaef39e7557384 100755 GIT binary patch delta 4621 zcmZWt3viQF7C!&~r*EJnX`Tg>QU@E5RZ41Fp!D}K3n=Om!dqwy>K5v#QCUTHNh-_; z6j$P3)CE=oxNFHSyEtvNS=pt4k3wZf1;GbOf}mxqvmmd80@?5M{{!e|CcXEZdmi6C z=iGB|dP)&bDdL*Xgbkt3#~Y3hCK8CKj{o3ue6Ug~jMGnYsBC8+lW3CCAXMoe(YTVv zeMI>f+{ZQUs~Y$5mLhSycs(61xyZy2I+WQrjV%dqW>L{NmBfoFnXDs7I zo${(~v@l*dpnEegIg^@VLeN`8LGOK-J2CS79?W53J8iEF2}7E_%#%vR+QM3?o&NmTHC1~p}q9Chf) zfBQW0O%uojmJBF7|C#KJ(Yq~5NnrPd~q8rwwbGNn>&-5Ov;ys16Dt>GPIIt;KIdq&$x1O8=ZpV5Ld&dA5*Y5H4*jsjQKF`r zDsuN?gE5q8Tq=wV2_VE(I%*1!OL($z^17Fnte=R}=fdf8E~smFj6&^MHrmBn+Z0xK z06@4bY|uN0)bV=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%kO?^;oIRYr%b`M%MTRx zdj8qqsd{sO_pRe|53K1N|Fhs*hwkYe(lfUAsapN-E4S04P3>Qvytw{!+Uw@DMKxD+ xTjxEijNRZHG4}EMPM^M{o72~2Jux9CH|>MHF9fHRhQ1v)(vWNa;I0aG^*<<=;4=UK diff --git a/native/bin/anchored-fs-darwin-x64 b/native/bin/anchored-fs-darwin-x64 new file mode 100755 index 0000000000000000000000000000000000000000..1f19309ef8aabc65c6d21cf12a5d20ccba764114 GIT binary patch literal 18520 zcmeHPdw5jUwcisb7b?QzD;+qnZ*#5|7`n23k}LK#@+* z0c4{0`VV`ptLP zCx5W}oo8-%?xDE+#%$Z>QCFib4+$dSkuWJG@h)td{jc^bP%FkK+8LXP@ev)Gf2j}g zEkU9-8V6$w#Ec!51@hd!dX*ZepFMvzaHkl1A?h<+~gLw#piFzM@m@>!(tkL1Pj zx8y}~)$PjqV_PAlqGx}E@hLh}xTk+7so-T)Geernmpa1dkf`Sq%X+C^gwjznRU#ij9w3j29(5rOg*E z^?g&2dk2`t6Ue-L52(LN;G@X&Fp*O9jYTLtJpYIsbsw=O@Kkd3NRF4gk2qxRJCf_= zRY&rC;qIn0iG;k9Wm6 z$G|+ESBq!1G_4&nU=-dY|3!lTag+a$kAG@xFo_WV62X6uch>Go?Kt@Jr&Z8W^eseE z-ebR>$MZH=@$MBwgm3Ib zA+`5HoX}Uc&;ZQ7Q9;!XGP=k4VXC}JxZEDq+R#eYR$PP9gAWjvUOY{f-nc0|rATpo z0XbTTf@gg;`h*0 zPUG?>cKKXSlQ=%zl-C@zq}>NAo1%aVWZpzPA7a?;FgakU1+LvKWN;q5u!X9TtJ1D=^2y*fIy zU*ff+`w7Z7JxSI50^=#`6&O!b+m_A975;X|#%J&%cT?2#g|`r)__S308ZJmD{4qF= z{PDPY*~_G99~UmM7p>%y`=$0pX!qKZF7d8*P`yFshvE~BQ-~LW!Zm3WJ|?Gn@GOOi zg2FD#soqt>8jalRimEw2o-keq9YyaZy%{}t_vu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Ov8s+Sj_V?Vvqt8BL1xeM t$R<20e>JZ8JV%vX2+E&Lcj_-M#dTPfuj0+X%UJTMD|HSnP9Tn?{{puEi8}xQ literal 0 HcmV?d00001 diff --git a/native/bin/anchored-fs-linux-x64 b/native/bin/anchored-fs-linux-x64 new file mode 100755 index 0000000000000000000000000000000000000000..0446cde226b4c52a222ae44072b4089abcbb2d81 GIT binary patch literal 22080 zcmeHP4|r77mA?}b2nu-v0;Uvo3WE)rgp8n@D3MHI)=#vQu43Kj0Qi{ z;AAw!MJItbg7(M&q9XtH|u{+;{KGn`!3j ze*5jW-|qKu^SwFmoO|xM=bn4+xql{e@2>IH=GbgZrcvx##<7V8rAlOUEs-3IRk3n5 z9-o)6i`i(9bMaJ(>`Zt#$HGk@D7RGDF%xbw z#4`zHealde?DAht!kp}SQD3%xC=~uFp)fC--PE}Hs=2e9>Pwm$Tf&_so#j`RTs60} zqqX!3t^(;rb&yXjTyg`;>0-S^ljZ4s5*{)q<)=;-ZVC4d{^sEijx_E_tWxj#_-7AG z8B~UNC=tIV6L@%P<5<$|LUIr!IX}yJ zaX>iJkeGiZeXDe`WkxwkX97P=fdh$RwV^pj*?@&kabG6gLYJZ`Z^%LyOA}t?w1xgP zDFm=^sez0E5KZC)hlMVtc1|y{(D}N^D9*|(bZUc4}Cu7d<*?n3w@l0zScrVN1Lh5LN73>jCES*iiO@~q1!F=9t(Yfg}&KBzraF& z$U>)iU#6`V`eaE2+-9LqvCy|$=oeb(J1lgX6J_eP(7z&yfcq`~Y~}dXgwxcJ*v#=O2&X9_(Z%u0 z2&bta(Z=!Vgwqs|xRv8m38&DXSjzEeTdm2pt~s7pwXMY3p6z8yo*3(Y!-9% z>Q}?6(O#wJX843#+o#5#a@rwI>({BjDCb(_sDY9vD)U&p#-`feE}DZvD-YzWn&*IBncz84=!-w+ zq#oKuBg?0Kk^G8bNBx#FsZ^vqSBXB2Myb)k& zFId8V^u!+L(!9Ihad?$i-0^5Cbv#vRV*@GWp8LV;jo)e085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%7A_JJ8vb=;}BF9?Z+{afLMNXR~jTc!? z!qF&fEid<*r$u?GrxYX0Nu2HjBbwA-o`2=L4UV#|^nF{Vya}Ry(d|+!ljT>K6yt?- zrDTPs?;2VB^Hx#+c47F7K%I$4>M!Fjg(;~!FDO3jG_fEp%W!yEuaQf8*^$fFiGedU Jqd*4A{u8g{pkn|4 literal 0 HcmV?d00001 diff --git a/native/manifest.json b/native/manifest.json index 2bbd119..73a4750 100644 --- a/native/manifest.json +++ b/native/manifest.json @@ -1,6 +1,9 @@ { "schema": 1, "artifacts": { - "anchored-fs-darwin-arm64": "8469cd676ba1c0a7ba6aea9fbec78c8ecda4b77eafc71f64cee34156bf9e8f27" + "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" + ] +} From ff70b64367be75c325b34c2d584efaec01d4050a Mon Sep 17 00:00:00 2001 From: Sam Bretz Date: Thu, 22 Oct 2026 18:11:41 -0700 Subject: [PATCH 7/7] Record the verified helper platform matrix --- native/README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/native/README.md b/native/README.md index baff6ba..899c26a 100644 --- a/native/README.md +++ b/native/README.md @@ -16,15 +16,20 @@ runs a compiler. `node native/build.mjs` is a developer/release-only build. | Target | Artifact | Verification | | --- | --- | --- | -| macOS arm64 | shipped in `bin/` | local Node 24 tests | -| macOS x64 | absent | refuses secure filesystem operations | -| Linux arm64/x64 | absent | refuses secure filesystem operations | +| 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. -Node 22, Linux, and Windows execution remain release verification gates. +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