omnet
aien-dev/omnet
Brought by drakestapleton
GitHub aien-dev/omnet#14 (code only)
Apply it
git checkout -b patch-d92e9138907212fc b4becd4cdd3efdaa3ed8a04a9de186008daa0e6f curl -fsSL https://interplane.io/drakestapleton/omnet/patches/d92e9138907212fc.patch | git am
Provenance
github-import 1
aien-dev/omnet
14
70d8c82c7b184506a31a1ca755180aa15e93a1c2
{"kind":"github-import","owner":"aien-dev","repo":"omnet","number":14,"url":"https://github.com/aien-dev/omnet/pull/14","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:42Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/README.md b/README.md index 40ebf14..eaffcf0 100644 --- a/README.md +++ b/README.md @@ -62,9 +62,11 @@ denial-of-service bug. |---|---| | `om/<unit>/<unit>.om` | Omega library: functions only, no globals, no `main` | | `om/<unit>/test/` | Program-mode test driver, vectors, `run.sh` | +| `cmd/tkad/` | Native Omega local daemon, RPC handlers, recovery and real-socket tests | +| `tools/build-tkad.sh` | Builds the daemon with the pinned compiler | | `docs/design/` | Design documents | | `tools/omc.sh` | Builds the pinned seed-born Omega compiler and verifies its digest | -| `tools/test.sh` | Runs every unit's tests | +| `tools/test.sh` | Runs library and daemon suites | ## Build and test @@ -77,9 +79,14 @@ tools/test.sh # builds the pinned compiler on first use, then runs every un ## Status -Pre-alpha. Crypto and encoding units, typed TKA models, node-key signature verification, and a -bounded in-memory authority are implemented in Omega. There is no daemon, durable authority store, -or headscale integration yet; this code does not currently protect a tailnet. +Pre-alpha. The Omega daemon implements all eight TKA RPCs, node registry/map operations, durable +snapshots, and validated restart recovery over a private Unix socket. Its local adapter is trusted +and must run as the same UID; the daemon does not authenticate remote Tailscale clients. + +The current profile supports one tailnet, 64 nodes, 128 authority updates and 64-KiB JSON messages. +Headscale integration and stock-client end-to-end qualification remain pending. This is not yet +deployed tailnet protection. Build with `tools/build-tkad.sh`; see +[`cmd/tkad/README.md`](cmd/tkad/README.md) before running it. See [`docs/design/tailnet-lock.md`](docs/design/tailnet-lock.md) for the implementation limits, verification plan, and remaining stages. diff --git a/cmd/tkad/README.md b/cmd/tkad/README.md new file mode 100644 index 0000000..fe05290 --- /dev/null +++ b/cmd/tkad/README.md @@ -0,0 +1,184 @@ +# tkad: bounded local Tailnet Lock service + +Production code is Omega, compiled by `tools/build-tkad.sh` with `tools/omc.sh`. +Go and Python under `test/` are test-only. Protocol types are pinned to Tailscale +v1.102.0 `tailcfg/tka.go` and `ipn/ipnlocal/tailnet-lock.go`. + +## Invocation and trust boundary + +Provision an empty directory owned by the effective UID, mode0700, under a trusted +ancestor chain. Run `build/tkad /absolute/state/directory --init` exactly once. +Subsequent starts use `build/tkad /absolute/state/directory`. Missing or corrupt +snapshots refuse startup; initialization refuses an existing snapshot. + +The service creates `tkad.sock` inside its opened directory, mode0600. The +0700directory and0600socket enforce a same-UID/root **trusted local adapter** +boundary. There is no SO_PEERCRED operation in the pinned native ABI and no claim +of peer-credential inspection. Same-UID/root processes can act as the adapter, +read secrets and change storage. This is not Noise authentication, HTTP serving, +a deployed Headscale integration, or a distinct-UID privilege boundary. The +adapter must authenticate remote clients and derive node IDs/admin assertions +from its trusted identity model, never from remote JSON. + +A descriptor-held abstract AF_UNIX bind lock, derived from directory device and +inode, admits one writer. All writers must use the same network namespace. Only +a lock holder removes the reserved stale socket pathname. No PID-file or +connect-failure lock inference is used. A process crash leaves a pathname that a +new lock holder can remove safely. + +## IPC version1 + +One request and one response per AF_UNIX stream connection. Integers are unsigned +little endian. Header fields must be complete; there is no implicit terminator. + +Request header,20bytes: + +| Offset | Size | Meaning | +|---|---|---| +|0|4|Bytes `54 4b 41 01` (`TKA` and version1)| +|4|1|Route ID below| +|5|1|Trusted adapter admin assertion, exactly0 or1| +|6|2|Reserved, zero| +|8|8|Authenticated NodeID; RPCs require a registered positive signed64-bit ID| +|16|4|Raw JSON byte length,0..65536| + +The body is the unmodified upstream JSON request. Response header,12bytes, has +the same magic at0, HTTP-style status as u16at4, reserved zero u16at6, and JSON +length u32at8. A200body follows the exact upstream response field shapes. Errors +have a short fixed JSON body, never request details or secrets. Bad/truncated +headers and oversized payload declarations close that connection without a reply. +Each receive/send phase has an absolute3second deadline, nonblocking descriptors +and kernel polling. A slow client can occupy one serial dispatch for that bounded +period; this is not a high-throughput concurrent server. + +| ID | Route | +|---|---| +|1|`/machine/tka/init/begin`| +|2|`/machine/tka/init/finish`| +|3|`/machine/tka/bootstrap`| +|4|`/machine/tka/sync/offer`| +|5|`/machine/tka/sync/send`| +|6|`/machine/tka/disable`| +|7|`/machine/tka/sign`| +|8|`/machine/tka/affected-sigs`| +|9|Trusted registry upsert| +|10|Trusted registry remove| +|11|Trusted map/list read| + +RPCs1,2,6 require admin. All eight bind JSON `NodeKey` to the registered key of +the header NodeID. `/sign` authenticates that caller but resolves the signed +target from the signature's embedded node public key; it need not be the caller. +Registry and map commands require admin and may use header NodeID0. + +Registry upsert takes `{NodeID,NodeKey,RotationPubkey,Signature?}`. `NodeKey` is +`nodekey:`hex and `RotationPubkey` is a32byte base64 Ed25519 public key. IDs and +node keys are unique. Optional `Signature` is a base64/byte-array upstream NKS; +nonempty signatures require an active authority and valid authorization. A key +change clears the old signature. Omitting Signature preserves it only when the +key is unchanged. Unsigned nodes may be registered and signed later; this does +not itself authorize them to peers. Remove takes `{NodeID}`. Map/list takes `{}` +and returns `{TKAInfo,Revision,Nodes:[{NodeID,NodePublic,KeySignature}]}`. Inactive +and pending authority produce `TKAInfo:null`; active produces `{Head}`; disabled +produces `{Disabled:true}`. Unsigned nodes have `KeySignature:null`. +Revision advances after each durable mutation. A future adapter must propagate +these full values to initial/delta map responses and arrange notifications. +No notification transport or Headscale integration is claimed here. + +## State transitions and durable publication + +Initialization binds a signed pending genesis to the initiating NodeID and the +frozen registry. Every registry update invalidates pending initialization. Finish +requires exactly one valid direct signature for every frozen node, including its +registered wrapping public key. A different initiator, partial roster, stale +roster, invalid signature or invalid support-disablement secret rejects. Optional +SupportDisablement is retained separately and never disables the authority. +Pending genesis is not visible in map or bootstrap responses. + +Sync uses the authority unit's fork choice, offer sampling and intersection. +Interactive sync additionally requires the supplied Head to equal the resulting +chosen head; mismatch rejects the candidate. Noninteractive sync validates the +head encoding but permits a divergent remote head. Disable requires admin, the +current head and a valid bounded secret. A disabled authority remains available +for bootstrap's disablement secret and cannot be reinitialized in this profile. + +Each mutating request operates on an inactive candidate slot, including registry, +signatures, pending state, support/disablement secrets and authority. The complete +response is encoded and checked against capacity **before** persistence. Only +then is a complete snapshot streamed to storage, synced, atomically renamed and +the directory synced. A successful commit is followed by an infallible live-slot +switch. Pre-rename errors discard the candidate and return503. Post-rename fsync +uncertainty exits74 immediately, without rollback or further serving. Exit74 also +denotes failed storage cleanup, including during initialization; it means a +storage fail-stop, not a definite successful commit. A transport +failure after publication remains an inherently ambiguous client outcome; the +adapter must reconcile through state reads. + +The semantic snapshot is version1: one128byte little-endian metadata frame, +then each node's88byte record and optional signature frame, optional support and +disablement secret frames, then each retained typed AUM frame in insertion order. +Metadata holds status, node count, pending initiator, secret lengths, revision, +authority count and a version marker. Node records contain ID, signature length, +authorization-state index, raw node key and raw rotation key. Storage adds its +own framing, version, ordered BLAKE2s integrity chain and strict permission/type +checks; see `om/store/README.md`. + +AUMs retain typed reconstruction (`tkamodel keep=1`), not merely canonical wire +serialization: an empty-but-present update metadata map must survive restart. +Recovery reboots/replays and verifies every AUM, registry uniqueness, structural +bounds, state status and every stored node signature against the historical +state at which it was accepted. This permits retaining a now-revoked signature +for affected-sigs/map propagation without treating it as currently authorized. +Recovery rechecks support secrets against genesis and disablement secrets against +the current authority. Corruption never +falls back to a temporary snapshot or an empty installation. + +## Native loop lifecycle + +Every Omega loop has a finite safety bound. To avoid an eventual request-count +trap, a quiescent epoch of100000dispatch iterations ends in a controlled exec of +`/proc/self/exe --resume`. The running inode, not an installation pathname or +argv0, is used. FD64holds the directory,65the writer lock and66the listener across +exec; first-epoch handoff refuses occupied targets. Resume validates inherited +descriptors, exact lock/listener addresses, directory/socket ownership and modes, +then reloads the committed snapshot. It never binds, initializes or unlinks. +Queued connections stay on the same listener and the PID is unchanged. Every +accepted connection is closed before rollover. Exec failure exits76 and never +retries or unlinks. The native exec operation supplies an empty environment; +this service does not depend on environment configuration. Linux procfs and an +unchanging effective UID are prerequisites. + +## Limits and tests + +Single tailnet;64registered nodes;128AUMs per authority;65536bytes per raw JSON +request/response, with a4095token/depth32JSON parser and256members per object; individual crypto/model +objects at most65536bytes, further constrained by JSON/base64 envelope capacity; +secrets at most1024bytes. Response overflow is413before mutation. Resource limits +are explicit rejections, not silent truncation or history eviction. Known-field +matching follows Go's ASCII case folding plus the Kelvin-sign and long-s Unicode +aliases; duplicate aliases are rejected. Exact decoded JSON key duplicates are +rejected globally. Signature-map NodeID keys follow Go signed-decimal parsing, +including leading plus/zeros, with duplicate decoded IDs rejected and registry +IDs restricted to positive int64 values. Unknown fields are ignored. The +32byte rotation-key registry requirement and disabled-state reinitialization +restriction are explicit local profile limits, not general upstream limits. + +Run `GO=/path/to/go1.26.8 REGEN=1 sh cmd/tkad/test/run.sh` to regenerate fixtures +through real pinned `tailscale.com/tka`, build the native binary, and exercise +all eight RPCs plus registry/map, authorization errors, malformed frames, +initialization races, restart, historical revocation and disk-write failure. +Test-only syscall-boundary variants prove one-shot begin/commit failure recovery +without process restart and fatal handling of post-rename directory-fsync failure. +A two-dispatch epoch variant checks queued connections, stable PID/listener, +retained writer exclusion and missing/swapped resume-descriptor refusal. +A completed-response admin-bypass mutant must be detected; a trapping mutant +must be rejected as an invalid test completion. Tests use isolated temporary +state directories and no live services. These are host/socket regression tests, +not stock-client end-to-end or constant-time qualification. + +### Third-party material + +The service composes Omega units adapted from Tailscale; their BSD-3-Clause +notices remain in `om/tka/tailscale.LICENSE` and +`om/tkasig/test/tailscale.LICENSE`. The Go fixture generator imports the pinned +upstream module and contains no copied upstream source. Its deterministic +private test keys are public fixtures, never deployment keys. diff --git a/cmd/tkad/adapter.om b/cmd/tkad/adapter.om new file mode 100644 index 0000000..3a95480 --- /dev/null +++ b/cmd/tkad/adapter.om @@ -0,0 +1,228 @@ +note SPDX-License-Identifier: Apache-2.0 +fn dsunpend to void +if eq dsget 0 1 +dsset 0 0 +dsset 2 0 +tkareset +end +end +fn dskeyput k view uchar 32 i ulong to void +if eq dsnodematch k i 0 +put ds_slen dsrow i 0 +put ds_auth dsrow i 0 +end +p = mul dsrow i 32 +for j ulong 32 +put ds_key add p j get k j +end +end +fn dsrotput b view uchar 65536 i ulong to void +p = mul dsrow i 32 +for j ulong 32 +put ds_rot add p j get b j +end +end +fn dsregister t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +id = dsnumber t d dsfield t d 12 +if or eq id 0 gt id 9223372036854775807 +ret 400 +end +i = dsfind id +if eq i 64 +if eq dsget 1 64 +ret 409 +end +i = dsget 1 +dsset 1 add i 1 +put ds_slen dsrow i 0 +put ds_auth dsrow i 0 +end +k = new uchar 32 0 +if eq dsnode t d dsfield t d 1 k 0 +ret 400 +end +for j ulong dsget 1 +if ne j i +if ne dsnodematch k j 0 +ret 409 +end +end +end +dskeyput k i +b = new uchar 65536 0 +n = dsbytes t d dsfield t d 13 b +if ne n 32 +ret 400 +end +dsrotput b i +put ds_ids dsrow i id +r = dsfield t d 10 +if ne r 0 +n = dsbytes t d r b +if gt n 65536 +ret 400 +end +if ne n 0 +if ne dsget 0 2 +ret 409 +end +if eq dsauthsig b n i tkacget 1 0 +ret 403 +end +end +dssetsig i b n tkacget 1 +end +dsunpend +put ds_ctl 6 dslit out 0 0 +put ds_ctl 5 1 +ret 200 +end +fn dsremove t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +i = dsfind dsnumber t d dsfield t d 12 +if eq i 64 +ret 404 +end +last = sub dsget 1 1 +if ne i last +dsclonenode dsrow last dsrow i +end +put ds_slen dsrow last 0 +dsset 1 last +dsunpend +put ds_ctl 6 dslit out 0 0 +put ds_ctl 5 1 +ret 200 +end +fn dsmap out edit uchar 65536 to int +p = dslit out 0 14 +if lt dsget 0 2 +p = dslit out p 15 +else +if eq dsget 0 3 +p = dslit out p 16 +else +p = dslit out p 10 +p = dsputhead out p +p = dslit out p 5 +end +end +p = dslit out p 19 +p = jsonu64 out p dsget 6 +p = dslit out p 17 +b = new uchar 65536 0 +for i ulong dsget 1 +if ne i 0 +p = dslit out p 6 +end +p = dslit out p 2 +p = jsonu64 out p dsid i +p = dslit out p 3 +p = dsputnode out p i +p = dslit out p 18 +n = dssig i b +if eq n 0 +p = dslit out p 15 +else +p = dsput64 out p b n +end +p = dslit out p 5 +end +put ds_ctl 6 dslit out p 7 +ret 200 +end +fn dsroute t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +r = get ds_ctl 4 +if eq r 1 +ret dsbegin t d out +end +if eq r 2 +ret dsfinish t d out +end +if eq r 3 +ret dsbootstrap t d out +end +if eq r 4 +ret dsoffer t d out +end +if eq r 5 +ret dssend t d out +end +if eq r 6 +ret dsdisable t d out +end +if eq r 7 +ret dssign t d out +end +if eq r 8 +ret dsaffected t d out +end +if eq r 9 +ret dsregister t d out +end +if eq r 10 +ret dsremove t d out +end +if eq r 11 +ret dsmap out +end +ret 404 +end +fn dsmutating to ulong +r = get ds_ctl 4 +if or eq r 1 eq r 2 +ret 1 +end +if or eq r 5 eq r 6 +ret 1 +end +if or eq r 7 eq r 9 +ret 1 +end +if eq r 10 +ret 1 +end +ret 0 +end +fn dsrequest raw view uchar 65536 n ulong out edit uchar 65536 to int +t = new ulong 32768 0 +d = new uchar 65536 0 +if ne jsonparse raw n t d 0 +put ds_ctl 6 dslit out 0 20 +ret 400 +end +dsselect get ds_ctl 0 +z = dscommon t d +if ne z 200 +put ds_ctl 6 dslit out 0 20 +ret z +end +put ds_ctl 5 0 +if ne dsmutating 0 +dsclone +end +z = dsroute t d out +if and eq z 200 gt get ds_ctl 6 65536 +z = 413 +end +if and eq z 200 ne get ds_ctl 5 0 +if eq dsget 6 18446744073709551615 +z = 409 +else +dsset 6 add dsget 6 1 +s = dssave +if eq s 2 +exit 74 +end +if ne s 0 +z = 503 +else +put ds_ctl 0 get ds_ctl 1 +end +end +end +dsselect get ds_ctl 0 +if ne z 200 +put ds_ctl 6 dslit out 0 20 +end +ret z +end diff --git a/cmd/tkad/helpers.om b/cmd/tkad/helpers.om new file mode 100644 index 0000000..14e0517 --- /dev/null +++ b/cmd/tkad/helpers.om @@ -0,0 +1,280 @@ +note SPDX-License-Identifier: Apache-2.0 +text ds_names "Version|NodeKey|GenesisAUM|Signatures|SupportDisablement|Head|Ancestors|MissingAUMs|Interactive|DisablementSecret|Signature|KeyID|NodeID|RotationPubkey|Remove|" +text ds_text "{}|{\"NeedSignatures\":[|{\"NodeID\":|,\"NodePublic\":|,\"RotationPubkey\":|}|,|]}|{\"GenesisAUM\":|{\"DisablementSecret\":|{\"Head\":|,\"Ancestors\":[|],\"MissingAUMs\":[|{\"Signatures\":[|{\"TKAInfo\":|null|{\"Disabled\":true}|,\"Nodes\":[|,\"KeySignature\":|,\"Revision\":|{\"Error\":\"request rejected\"}|" +fn dslower c uchar to uchar +if and ge c 65 le c 90 +ret add c 32 +end +ret c +end +fn dsfold d view uchar 65536 p ulong n ulong to ulong +if eq n 0 +ret 0 +end +c = get d p +if and eq c 197 ge n 2 +if eq get d add p 1 191 +ret 627 +end +end +if and eq c 226 ge n 3 +if and eq get d add p 1 132 eq get d add p 2 170 +ret 875 +end +end +ret add ulong dslower c 256 +end +fn dsnamematch d view uchar 65536 p ulong start ulong n ulong count ulong to ulong +for i ulong n +v = dsfold d p count +if ne and v 255 ulong dslower get ds_names add start i +ret 0 +end +v = shr v 8 +if gt v count +ret 0 +end +p = add p v +count = sub count v +end +if ne count 0 +ret 0 +end +ret 1 +end +fn dsfieldmatch t view ulong 32768 d view uchar 65536 j ulong start ulong n ulong to ulong +p = get t add mul j 8 1 +count = get t add mul j 8 2 +ret dsnamematch d p start n count +end +fn dsfield t view ulong 32768 d view uchar 65536 f ulong to ulong +start = ulong 0 +for i ulong f +while ne get ds_names start 124 bound 128 +start = add start 1 +end +start = add start 1 +end +n = ulong 0 +while ne get ds_names add start n 124 bound 128 +n = add n 1 +end +found = ulong 0 +j = ulong 2 +while lt j get t 11 bound 4095 +if ne dsfieldmatch t d j start n 0 +if ne found 0 +ret 65537 +end +found = add j 1 +end +j = get t add mul add j 1 8 3 +end +ret found +end +fn dslit out edit uchar 65536 p ulong f ulong to ulong +start = ulong 0 +for i ulong f +while ne get ds_text start 124 bound 256 +start = add start 1 +end +start = add start 1 +end +n = ulong 0 +while ne get ds_text add start n 124 bound 256 +n = add n 1 +end +if gt p sub ulong 65536 n +ret 65537 +end +for i ulong n +put out add p i get ds_text add start i +end +ret add p n +end +fn dskind t view ulong 32768 id ulong to ulong +if or eq id 0 ge id 4096 +ret 0 +end +ret get t mul id 8 +end +fn dsbytes t view ulong 32768 d view uchar 65536 id ulong out edit uchar 65536 to ulong +b = new uchar 65536 0 +if or eq id 0 eq dskind t id 7 +ret 0 +end +if eq dskind t id 3 +n = jsoncopy t d id b +if gt n 65536 +ret 65537 +end +ret cdb64dec b n out +end +if eq dskind t id 2 +j = add id 1 +n = ulong 0 +while lt j get t add mul id 8 3 bound 4095 +if eq dskind t j 7 +put out n 0 +else +v = dsnumber t d j +if gt v 255 +ret 65537 +end +put out n uchar v +end +n = add n 1 +j = add j 1 +end +ret n +end +ret 65537 +end +fn dsnumber t view ulong 32768 d view uchar 65536 id ulong to ulong +v = new ulong 1 0 +if ne dskind t id 4 +ret 18446744073709551615 +end +if ne jsonuint d get t add mul id 8 1 get t add mul id 8 2 v 0 +ret 18446744073709551615 +end +ret get v 0 +end +fn dsnode t view ulong 32768 d view uchar 65536 id ulong k edit uchar 32 to ulong +b = new uchar 65536 0 +if ne dskind t id 3 +ret 0 +end +n = jsoncopy t d id b +ret cdnkdec b n k +end +fn dshash t view ulong 32768 d view uchar 65536 id ulong k edit uchar 32 to ulong +b = new uchar 65536 0 +if ne dskind t id 3 +ret 0 +end +n = jsoncopy t d id b +ret cdaumdec b n k +end +fn dsheadmatch t view ulong 32768 d view uchar 65536 to ulong +a = new uchar 32 0 +b = new uchar 32 0 +if eq dshash t d dsfield t d 5 a 0 +ret 0 +end +z = tkahead b +for i ulong 32 +if ne get a i get b i +ret 0 +end +end +ret 1 +end +fn dsput64 out edit uchar 65536 p ulong src view uchar 65536 n ulong to ulong +b = new uchar 65536 0 +if gt n 49152 +ret 65537 +end +z = cdb64enc src n b +ret jsonstr out p b z +end +fn dsputnode out edit uchar 65536 p ulong i ulong to ulong +k = new uchar 32 0 +b = new uchar 65536 0 +dskey i k 0 +n = cdnkenc k b +ret jsonstr out p b n +end +fn dsputhead out edit uchar 65536 p ulong to ulong +k = new uchar 32 0 +b = new uchar 65536 0 +z = tkahead k +if ne z 0 +ret 65537 +end +n = cdaumenc k b +ret jsonstr out p b n +end +fn dscommon t view ulong 32768 d view uchar 65536 to int +if ne dskind t 1 1 +ret 400 +end +for i ulong 15 +if eq dsfield t d i 65537 +ret 400 +end +end +if ge get ds_ctl 4 9 +if eq get ds_ctl 3 0 +ret 403 +end +ret 200 +end +v = new long 1 0 +id = dsfield t d 0 +if ne id 0 +if ne dskind t id 4 +ret 400 +end +if ne jsonint d get t add mul id 8 1 get t add mul id 8 2 v 0 +ret 400 +end +end +id = dsfind get ds_ctl 2 +if eq id 64 +ret 403 +end +k = new uchar 32 0 +if eq dsnode t d dsfield t d 1 k 0 +ret 400 +end +for i ulong 32 +if ne get k i get ds_key add mul dsrow id 32 i +ret 403 +end +end +ret 200 +end +fn dseqhash s view uchar 65536 p ulong h view uchar 32 to ulong +for k ulong 32 +if ne get h k get s add p k +ret 0 +end +end +ret 1 +end +fn dssecretmatch s view uchar 65536 sn ulong h view uchar 32 to ulong +t = new ulong 131074 0 +z = cbrdec s sn t +r = cbrmfind t 0 2 +j = add r 1 +for i ulong cbrval t r +if eq cbrval t j 32 +if ne dseqhash s cbrpoff t j h 0 +ret 1 +end +end +j = cbrnext t j +end +ret 0 +end +fn dsvalidsecretat b view uchar 65536 n ulong idx ulong to ulong +if gt n 1024 +ret 0 +end +h = new uchar 32 0 +s = new uchar 65536 0 +sec = new uchar 1024 0 +for i ulong n +put sec i get b i +end +a2tka sec n h +sn = tkaget idx 1 s +if gt sn 65536 +ret 0 +end +ret dssecretmatch s sn h +end +fn dsvalidsecret b view uchar 65536 n ulong to ulong +ret dsvalidsecretat b n tkacget 1 +end diff --git a/cmd/tkad/main.om b/cmd/tkad/main.om new file mode 100644 index 0000000..cd31598 --- /dev/null +++ b/cmd/tkad/main.om @@ -0,0 +1,151 @@ +note SPDX-License-Identifier: Apache-2.0 +text ds_init "--init" +text ds_resum "--resume" +text ds_exe "/proc/self/exe" +fn dslistenercheck fd int to int +b = new uchar 65536 0 +if ne sockname fd b 0 128 add long len ds_sock 3 +ret 1 +end +if or ne get b 0 1 ne get b 1 0 +ret 1 +end +for i ulong len ds_sock +if ne get b add i 2 get ds_sock i +ret 1 +end +end +if ne get b add len ds_sock 2 0 +ret 1 +end +if ne fstat fd b 0 128 0 +ret 1 +end +if ne and dsleget b 16 61440 49152 +ret 1 +end +if ne lstat ds_sock 0 len ds_sock b 0 128 0 +ret 1 +end +if ne and dsleget b 16 4294967295 49536 +ret 1 +end +if ne and dsleget b 24 4294967295 ulong geteuid +ret 1 +end +if ne listen fd int 32 0 +ret 1 +end +ret 0 +end +fn dsroll fd int to void +b = new uchar 65536 0 +if ne fd 66 +if ne fstat int 66 b 0 128 -9 +exit 76 +end +if ne dupfd fd int 66 int 0 66 +exit 76 +end +if ne stpass int 64 int 65 0 +exit 76 +end +end +put b 0 2 +put b 1 0 +put b 2 uchar len ds_exe +put b 3 0 +for i ulong len ds_exe +put b add i 4 get ds_exe i +end +p = add len ds_exe 4 +put b p uchar len ds_resum +put b add p 1 0 +for i ulong len ds_resum +put b add add p 2 i get ds_resum i +end +z = execprog b 0 add add p 2 len ds_resum +exit 76 +end +fn dsstartup to int +b = new uchar 65536 0 +a = new uchar 65536 0 +args = argcnt +if and ne args 2 ne args 3 +ret -1 +end +n = argread 1 b 0 65536 +if or le n 0 gt n 4095 +ret -1 +end +resume = ulong 0 +if eq n long len ds_resum +resume = 1 +for i ulong len ds_resum +if ne get b i get ds_resum i +resume = 0 +end +end +end +if ne resume 0 +if ne args 2 +ret -1 +end +if ne stresume int 64 int 65 0 +ret -1 +end +if ne dslistenercheck int 66 0 +ret -1 +end +if ne dsload 0 +ret -1 +end +ret 66 +end +for i ulong ulong n +if eq get b i 0 +ret -1 +end +end +init = int 0 +if eq args 3 +m = argread 2 a 0 65536 +if ne m long len ds_init +ret -1 +end +for i ulong len ds_init +if ne get a i get ds_init i +ret -1 +end +end +init = 1 +end +if ne stopen b ulong n init 0 +ret -1 +end +if ne init 0 +dsselect 0 +s = dssave +if eq s 2 +exit 74 +end +if ne s 0 +ret -1 +end +else +if ne dsload 0 +ret -1 +end +end +ret dslisten +end +fn main to int +z = umask int 127 +fd = dsstartup +if lt fd 0 +ret 73 +end +dsbatch fd +dsroll fd +ret 76 +end diff --git a/cmd/tkad/rpc.om b/cmd/tkad/rpc.om new file mode 100644 index 0000000..567964b --- /dev/null +++ b/cmd/tkad/rpc.om @@ -0,0 +1,466 @@ +note SPDX-License-Identifier: Apache-2.0 +fn dssecretput b view uchar 65536 n ulong f ulong to void +dsset f n +p = mul get ds_ctl 1 1024 +for i ulong n +if eq f 3 +put ds_sup add p i get b i +else +put ds_dis add p i get b i +end +end +end +fn dsputrot out edit uchar 65536 p ulong i ulong to ulong +b = new uchar 65536 0 +for j ulong 32 +put b j get ds_rot add mul dsrow i 32 j +end +ret dsput64 out p b 32 +end +fn dsbegin t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +if eq get ds_ctl 3 0 +ret 403 +end +if ne dsget 0 0 +ret 409 +end +b = new uchar 65536 0 +n = dsbytes t d dsfield t d 2 b +if or eq n 0 gt n 65536 +ret 400 +end +tkareset +if ne tkaboot b n 0 +ret 400 +end +dsset 0 1 +dsset 2 get ds_ctl 2 +p = dslit out 0 1 +for i ulong dsget 1 +if ne i 0 +p = dslit out p 6 +end +p = dslit out p 2 +p = jsonu64 out p dsid i +p = dslit out p 3 +p = dsputnode out p i +p = dslit out p 4 +p = dsputrot out p i +p = dslit out p 5 +end +p = dslit out p 7 +put ds_ctl 6 p +put ds_ctl 5 1 +ret 200 +end +fn dsinitwrap sig view uchar 65536 n ulong i ulong to ulong +t = new ulong 131074 0 +m = new ulong 132 0 +if ne nksdec sig n t m 0 +ret 0 +end +if or ne get m 0 1 ne nkslen t get m 5 32 +ret 0 +end +for j ulong 32 +if ne nksbyte sig t get m 5 j get ds_rot add mul dsrow i 32 j +ret 0 +end +end +ret 1 +end +fn dsmapid d view uchar 65536 p ulong n ulong out edit ulong 1 to int +if eq n 0 +ret 1 +end +negative = ulong 0 +if or eq get d p 43 eq get d p 45 +if eq get d p 45 +negative = 1 +end +p = add p 1 +n = sub n 1 +end +if eq n 0 +ret 1 +end +v = ulong 0 +limit = add ulong 9223372036854775807 negative +for i ulong n +c = get d add p i +if or lt c 48 gt c 57 +ret 1 +end +digit = ulong sub c 48 +if gt v div sub limit digit 10 +ret 1 +end +v = add mul v 10 digit +end +if ne negative 0 +v = neg v +end +put out 0 v +ret 0 +end +fn dsfinishone t view ulong 32768 d view uchar 65536 j ulong seen edit uchar 64 to int +id = new ulong 1 0 +if ne dsmapid d get t add mul j 8 1 get t add mul j 8 2 id 0 +ret 400 +end +i = dsfind get id 0 +if eq i 64 +ret 409 +end +if ne get seen i 0 +ret 400 +end +put seen i 1 +b = new uchar 65536 0 +n = dsbytes t d add j 1 b +if or eq n 0 gt n 65536 +ret 400 +end +if eq dsauthsig b n i 0 0 +ret 400 +end +if eq dsinitwrap b n i 0 +ret 400 +end +dssetsig i b n 0 +ret 200 +end +fn dsfinish t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +if eq get ds_ctl 3 0 +ret 403 +end +if or ne dsget 0 1 ne dsget 2 get ds_ctl 2 +ret 409 +end +r = dsfield t d 3 +if ne dskind t r 1 +ret 400 +end +if ne get t add mul r 8 5 mul dsget 1 2 +ret 409 +end +seen = new uchar 64 0 +j = add r 1 +while lt j get t add mul r 8 3 bound 4095 +z = dsfinishone t d j seen +if ne z 200 +ret z +end +j = get t add mul add j 1 8 3 +end +b = new uchar 65536 0 +n = dsbytes t d dsfield t d 4 b +if gt n 1024 +ret 400 +end +if ne n 0 +if eq dsvalidsecret b n 0 +ret 400 +end +end +dssecretput b n 3 +dsset 0 2 +dsset 2 0 +put ds_ctl 6 dslit out 0 0 +put ds_ctl 5 1 +ret 200 +end +fn dsputsecret out edit uchar 65536 p ulong to ulong +b = new uchar 65536 0 +q = mul get ds_ctl 1 1024 +for i ulong dsget 4 +put b i get ds_dis add q i +end +ret dsput64 out p b dsget 4 +end +fn dsbootstrap t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +b = new uchar 65536 0 +c = new uchar 65536 0 +p = ulong 0 +r = dsfield t d 5 +if and ne r 0 and ne dskind t r 3 ne dskind t r 7 +ret 400 +end +if lt dsget 0 2 +ret 409 +end +if eq dsget 0 3 +if eq dsget 4 0 +put ds_ctl 6 dslit out 0 0 +ret 200 +end +p = dslit out 0 9 +p = dsputsecret out p +else +n = tkaget 0 0 b +n = tkamodel b n 1 c 0 +if gt n 65536 +ret 500 +end +p = dslit out 0 8 +p = dsput64 out p c n +end +put ds_ctl 6 dslit out p 5 +ret 200 +end +fn dsofferparse t view ulong 32768 d view uchar 65536 offer edit uchar 65536 to ulong +h = new uchar 32 0 +if eq dshash t d dsfield t d 5 h 0 +ret 65537 +end +for i ulong 32 +put offer i get h i +end +r = dsfield t d 6 +if or eq r 0 eq dskind t r 7 +ret 1 +end +if ne dskind t r 2 +ret 65537 +end +cnt = ulong 1 +j = add r 1 +while lt j get t add mul r 8 3 bound 4095 +if ge cnt 2048 +ret 65537 +end +if eq dshash t d j h 0 +ret 65537 +end +for i ulong 32 +put offer add mul cnt 32 i get h i +end +cnt = add cnt 1 +j = get t add mul j 8 3 +end +ret cnt +end +fn dsputhash out edit uchar 65536 p ulong a view uchar 65536 off ulong to ulong +h = new uchar 32 0 +b = new uchar 65536 0 +for j ulong 32 +put h j get a add off j +end +n = cdaumenc h b +ret jsonstr out p b n +end +fn dsputaum out edit uchar 65536 p ulong idx ulong to ulong +b = new uchar 65536 0 +c = new uchar 65536 0 +n = tkaget idx 0 b +n = tkamodel b n 1 c 0 +if gt n 65536 +ret 65537 +end +ret dsput64 out p c n +end +fn dsoffer t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +if ne dsget 0 2 +ret 409 +end +a = new uchar 65536 0 +nodes = new ulong 128 0 +n = dsofferparse t d a +if gt n 2048 +ret 400 +end +cnt = tkamissing a n nodes +if gt cnt 128 +ret 409 +end +n = tkaoffer a +p = dslit out 0 10 +p = dsputhead out p +p = dslit out p 11 +for i ulong sub n 1 +if ne i 0 +p = dslit out p 6 +end +p = dsputhash out p a mul add i 1 32 +end +p = dslit out p 12 +for i ulong cnt +if ne i 0 +p = dslit out p 6 +end +p = dsputaum out p get nodes i +end +put ds_ctl 6 dslit out p 7 +ret 200 +end +fn dssend t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +if ne dsget 0 2 +ret 409 +end +h = new uchar 32 0 +if eq dshash t d dsfield t d 5 h 0 +ret 400 +end +r = dsfield t d 8 +if and ne r 0 and ne dskind t r 5 and ne dskind t r 6 ne dskind t r 7 +ret 400 +end +r = dsfield t d 7 +if and ne r 0 and ne dskind t r 2 ne dskind t r 7 +ret 400 +end +if ne tkabegin 0 +ret 500 +end +b = new uchar 65536 0 +if eq dskind t r 2 +j = add r 1 +while lt j get t add mul r 8 3 bound 4095 +n = dsbytes t d j b +if or eq n 0 gt n 65536 +tkaabort +ret 400 +end +if ne tkastage b n 0 +ret 400 +end +j = get t add mul j 8 3 +end +end +if ne tkacommit 0 +ret 400 +end +if eq dskind t dsfield t d 8 5 +if eq dsheadmatch t d 0 +ret 409 +end +end +p = dslit out 0 10 +p = dsputhead out p +put ds_ctl 6 dslit out p 5 +put ds_ctl 5 1 +ret 200 +end +fn dsdisable t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +if eq get ds_ctl 3 0 +ret 403 +end +if ne dsget 0 2 +ret 409 +end +if eq dsheadmatch t d 0 +ret 409 +end +b = new uchar 65536 0 +n = dsbytes t d dsfield t d 9 b +if gt n 1024 +ret 400 +end +if eq dsvalidsecret b n 0 +ret 403 +end +dssecretput b n 4 +dsset 0 3 +put ds_ctl 6 dslit out 0 0 +put ds_ctl 5 1 +ret 200 +end +fn dsnodematch key view uchar 32 i ulong to ulong +p = mul dsrow i 32 +for j ulong 32 +if ne get key j get ds_key add p j +ret 0 +end +end +ret 1 +end +fn dstarget sig view uchar 65536 n ulong to ulong +t = new ulong 131074 0 +m = new ulong 132 0 +key = new uchar 32 0 +if ne nksdec sig n t m 0 +ret 64 +end +r = get m 1 +if eq nksnode sig t r 0 +ret 64 +end +for j ulong 32 +put key j nksbyte sig t r add j 2 +end +for i ulong dsget 1 +if ne dsnodematch key i 0 +ret i +end +end +ret 64 +end +fn dssign t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +if ne dsget 0 2 +ret 409 +end +b = new uchar 65536 0 +n = dsbytes t d dsfield t d 10 b +if or eq n 0 gt n 65536 +ret 400 +end +i = dstarget b n +if eq i 64 +ret 404 +end +if eq dsauthsig b n i tkacget 1 0 +ret 403 +end +dssetsig i b n tkacget 1 +put ds_ctl 6 dslit out 0 0 +put ds_ctl 5 1 +ret 200 +end +fn dsuses sig view uchar 65536 n ulong key view uchar 65536 to ulong +t = new ulong 131074 0 +m = new ulong 132 0 +if ne nksdec sig n t m 0 +ret 0 +end +for i ulong get m 128 +r = get m add mul i 8 2 +if eq nkslen t r 32 +same = ulong 1 +for j ulong 32 +if ne nksbyte sig t r j get key j +same = 0 +end +end +if eq same 1 +ret 1 +end +end +end +ret 0 +end +fn dsaffected t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int +if ne dsget 0 2 +ret 409 +end +key = new uchar 65536 0 +b = new uchar 65536 0 +if ne dsbytes t d dsfield t d 11 key 32 +ret 400 +end +p = dslit out 0 13 +cnt = ulong 0 +for i ulong dsget 1 +n = dssig i b +if ne n 0 +if ne dsuses b n key 0 +if ne cnt 0 +p = dslit out p 6 +end +p = dsput64 out p b n +cnt = add cnt 1 +end +end +end +put ds_ctl 6 dslit out p 7 +ret 200 +end diff --git a/cmd/tkad/socket.om b/cmd/tkad/socket.om new file mode 100644 index 0000000..f8cd323 --- /dev/null +++ b/cmd/tkad/socket.om @@ -0,0 +1,134 @@ +note SPDX-License-Identifier: Apache-2.0 +text ds_sock "tkad.sock" +fn dsio fd int b edit uchar 65536 n ulong output ulong to int +p = ulong 0 +deadline = add monons 3000000000 +r = long 0 +while lt p n bound 65537 +left = sub deadline monons +if le left 0 +ret 1 +end +if eq output 0 +r = waitio fd 1 left +else +r = waitio fd 4 left +end +if lt r 0 +if eq r -4 +continue +end +ret 1 +end +if eq r 0 +ret 1 +end +if eq output 0 +r = recv fd b p sub n p int 0 +else +r = send fd b p sub n p int 0 +end +if or eq r -11 eq r -4 +continue +end +if le r 0 +ret 1 +end +p = add p ulong r +end +ret 0 +end +fn dsclient fd int to void +h = new uchar 65536 0 +b = new uchar 65536 0 +o = new uchar 65536 0 +if ne dsio fd h 20 0 0 +ret +end +if or ne get h 0 84 ne get h 1 75 +ret +end +if or ne get h 2 65 ne get h 3 1 +ret +end +if gt get h 5 1 +ret +end +if or ne get h 6 0 ne get h 7 0 +ret +end +n = ulong 0 +for i ulong 4 +n = or n shl ulong get h add i 16 mul i 8 +end +if gt n 65536 +ret +end +put ds_ctl 4 ulong get h 4 +put ds_ctl 3 ulong get h 5 +put ds_ctl 2 dsleget h 8 +if ne dsio fd b n 0 0 +ret +end +z = dsrequest b n o +put h 4 uchar and z 255 +put h 5 uchar shr z 8 +put h 6 0 +put h 7 0 +n = get ds_ctl 6 +for i ulong 4 +put h add i 8 uchar and shr n mul i 8 255 +end +if ne dsio fd h 12 1 0 +ret +end +z = dsio fd o n 1 +end +fn dslisten to int +z = unlink ds_sock 0 len ds_sock +if and ne z 0 ne z -2 +ret -1 +end +addr = new uchar 128 0 +put addr 0 1 +for i ulong len ds_sock +put addr add i 2 get ds_sock i +end +fd = socknew int 1 int 526337 int 0 +if lt fd 0 +ret -1 +end +if ne bind int fd addr 0 add len ds_sock 3 0 +z = fclose int fd +ret -1 +end +if ne chmod ds_sock 0 len ds_sock int 384 0 +z = fclose int fd +ret -1 +end +if ne listen int fd int 32 0 +z = fclose int fd +ret -1 +end +ret int fd +end +fn dsbatch fd int to void +for i ulong 100000 +r = waitio fd int 1 long -1 +if lt r 0 +if eq r -4 +continue +end +exit 75 +end +client = accept fd int 526336 +if lt client 0 +if or eq client -11 eq client -4 +continue +end +exit 75 +end +dsclient int client +z = fclose int client +end +end diff --git a/cmd/tkad/state.om b/cmd/tkad/state.om new file mode 100644 index 0000000..068a4ac --- /dev/null +++ b/cmd/tkad/state.om @@ -0,0 +1,400 @@ +note SPDX-License-Identifier: Apache-2.0 +note Service candidates use the inactive authority slot. No live mutation precedes durability. +global ds_ctl ulong 8 +global ds_meta ulong 32 +global ds_ids ulong 128 +global ds_slen ulong 128 +global ds_auth ulong 128 +global ds_key uchar 4096 +global ds_rot uchar 4096 +global ds_sig uchar 8388608 +global ds_sup uchar 2048 +global ds_dis uchar 2048 + +fn dsget f ulong to ulong +ret get ds_meta add mul get ds_ctl 1 16 f +end +fn dsset f ulong v ulong to void +put ds_meta add mul get ds_ctl 1 16 f v +end +fn dsrow i ulong to ulong +ret add mul get ds_ctl 1 64 i +end +fn dsselect lane ulong to void +put ds_ctl 1 lane +z = tkaselect lane +end +fn dsid i ulong to ulong +ret get ds_ids dsrow i +end +fn dsfind id ulong to ulong +for i ulong dsget 1 +if eq dsid i id +ret i +end +end +ret 64 +end +fn dskey i ulong out edit uchar 32 rot ulong to void +for j ulong 32 +if eq rot 0 +put out j get ds_key add mul dsrow i 32 j +else +put out j get ds_rot add mul dsrow i 32 j +end +end +end +fn dssig i ulong out edit uchar 65536 to ulong +n = get ds_slen dsrow i +for j ulong n +put out j get ds_sig add mul dsrow i 65536 j +end +ret n +end +fn dssetsig i ulong src view uchar 65536 n ulong auth ulong to void +put ds_slen dsrow i n +put ds_auth dsrow i auth +for j ulong n +put ds_sig add mul dsrow i 65536 j get src j +end +end +fn dsclonenode a ulong b ulong to void +put ds_ids b get ds_ids a +put ds_slen b get ds_slen a +put ds_auth b get ds_auth a +for j ulong 32 +put ds_key add mul b 32 j get ds_key add mul a 32 j +put ds_rot add mul b 32 j get ds_rot add mul a 32 j +end +for j ulong get ds_slen a +v = get ds_sig add mul a 65536 j +put ds_sig add mul b 65536 j v +end +end +fn dscloneaum a ulong b ulong to void +for j ulong 6 +put tkap_m add mul b 6 j get tkap_m add mul a 6 j +end +for j ulong get tkap_m mul a 6 +v = get tkap_a add mul a 65536 j +put tkap_a add mul b 65536 j v +end +for j ulong get tkap_m add mul a 6 1 +v = get tkap_s add mul a 65536 j +put tkap_s add mul b 65536 j v +end +for j ulong 32 +put tkap_h add mul b 32 j get tkap_h add mul a 32 j +end +end +fn dsclone to void +old = get ds_ctl 0 +next = xor old 1 +for i ulong 16 +put ds_meta add mul next 16 i get ds_meta add mul old 16 i +end +for i ulong 64 +dsclonenode add mul old 64 i add mul next 64 i +end +for i ulong 1024 +put ds_sup add mul next 1024 i get ds_sup add mul old 1024 i +put ds_dis add mul next 1024 i get ds_dis add mul old 1024 i +end +for i ulong 8 +put tkap_c add mul next 8 i get tkap_c add mul old 8 i +end +for i ulong get tkap_c mul old 8 +dscloneaum add mul old 128 i add mul next 128 i +end +dsselect next +put ds_ctl 5 0 +end +fn dsleput out edit uchar 65536 p ulong v ulong to void +for j ulong 8 +put out add p j uchar and shr v mul j 8 255 +end +end +fn dsleget src view uchar 65536 p ulong to ulong +v = ulong 0 +for j ulong 8 +v = or v shl ulong get src add p j mul j 8 +end +ret v +end +fn dsabort to void +if ne stabort 0 +exit 74 +end +end +fn dssave to int +b = new uchar 65536 0 +dsset 7 tkacget 0 +dsset 15 1 +for i ulong 16 +dsleput b mul i 8 dsget i +end +if ne stbegin 0 +dsabort +ret 1 +end +if ne stwrite b 128 0 +dsabort +ret 1 +end +for i ulong dsget 1 +dsleput b 0 dsid i +dsleput b 8 get ds_slen dsrow i +dsleput b 16 get ds_auth dsrow i +for j ulong 32 +put b add 24 j get ds_key add mul dsrow i 32 j +put b add 56 j get ds_rot add mul dsrow i 32 j +end +if ne stwrite b 88 0 +dsabort +ret 1 +end +n = dssig i b +if ne stwrite b n 0 +dsabort +ret 1 +end +end +for i ulong dsget 3 +put b i get ds_sup add mul get ds_ctl 1 1024 i +end +if ne stwrite b dsget 3 0 +dsabort +ret 1 +end +for i ulong dsget 4 +put b i get ds_dis add mul get ds_ctl 1 1024 i +end +if ne stwrite b dsget 4 0 +dsabort +ret 1 +end +for i ulong tkacget 0 +n = tkaget i 0 b +if ne stwrite b n 0 +dsabort +ret 1 +end +end +s = stcommit +if eq s 1 +dsabort +end +ret s +end +fn dsstatekeys idx ulong keys edit uchar 16384 to ulong +b = new uchar 65536 0 +t = new ulong 131074 0 +n = tkaget idx 1 b +if gt n 65536 +ret 65537 +end +n = cbrdec b n t +r = cbrmfind t 0 3 +j = add r 1 +cnt = ulong 0 +for i ulong cbrval t r +p = cbrmfind t j 3 +if eq cbrval t p 32 +tkaexport b cbrpoff t p keys mul cnt 32 +cnt = add cnt 1 +end +j = cbrnext t j +end +ret cnt +end +fn dsauthsig sig view uchar 65536 n ulong i ulong idx ulong to ulong +keys = new uchar 16384 0 +node = new uchar 32 0 +t = new ulong 131074 0 +m = new ulong 132 0 +cnt = dsstatekeys idx keys +if gt cnt 512 +ret 0 +end +if ne nksdec sig n t m 0 +ret 0 +end +dskey i node 0 +ret nksauth sig t m node keys cnt +end +fn dssamekey i ulong j ulong to ulong +a = mul dsrow i 32 +b = mul dsrow j 32 +for k ulong 32 +v = get ds_key add a k +if ne v get ds_key add b k +ret 0 +end +end +ret 1 +end +fn dsloadnode i ulong to int +b = new uchar 65536 0 +if ne stread b 88 +ret 1 +end +id = dsleget b 0 +n = dsleget b 8 +if or eq id 0 gt id 9223372036854775807 +ret 1 +end +if or gt n 65536 ge dsleget b 16 128 +ret 1 +end +put ds_ids dsrow i id +put ds_slen dsrow i n +put ds_auth dsrow i dsleget b 16 +for j ulong 32 +put ds_key add mul dsrow i 32 j get b add 24 j +put ds_rot add mul dsrow i 32 j get b add 56 j +end +for j ulong i +if eq dsid j id +ret 1 +end +if ne dssamekey i j 0 +ret 1 +end +end +if ne n 0 +if ne stread b long n +ret 1 +end +dssetsig i b n get ds_auth dsrow i +end +ret 0 +end +fn dsload to int +b = new uchar 65536 0 +dsselect 0 +tkareset +if ne stread b 128 +ret 1 +end +for i ulong 16 +dsset i dsleget b mul i 8 +end +if or ne dsget 15 1 gt dsget 0 3 +ret 1 +end +if or gt dsget 1 64 gt dsget 7 128 +ret 1 +end +if or gt dsget 3 1024 gt dsget 4 1024 +ret 1 +end +if ne dsget 5 0 +ret 1 +end +if lt dsget 0 2 +if ne dsget 3 0 +ret 1 +end +else +if ne dsget 2 0 +ret 1 +end +end +for i ulong 7 +if ne dsget add i 8 0 +ret 1 +end +end +if eq dsget 0 0 +if or ne dsget 7 0 ne dsget 2 0 +ret 1 +end +else +if eq dsget 7 0 +ret 1 +end +end +for i ulong dsget 1 +if ne dsloadnode i 0 +ret 1 +end +end +if ne dsget 3 0 +if ne stread b long dsget 3 +ret 1 +end +for j ulong dsget 3 +put ds_sup j get b j +end +end +if ne dsget 4 0 +if ne stread b long dsget 4 +ret 1 +end +for j ulong dsget 4 +put ds_dis j get b j +end +end +for i ulong dsget 7 +n = stread b +if le n 0 +ret 1 +end +if eq i 0 +if ne tkaboot b ulong n 0 +ret 1 +end +else +if ne tkabegin 0 +ret 1 +end +if ne tkastage b ulong n 0 +ret 1 +end +if ne tkacommit 0 +ret 1 +end +end +end +if ne stread b 0 +ret 1 +end +if eq dsget 0 1 +if or ne dsget 7 1 eq dsfind dsget 2 64 +ret 1 +end +end +for i ulong dsget 1 +n = dssig i b +if ne n 0 +if lt dsget 0 2 +ret 1 +end +if eq dsauthsig b n i get ds_auth dsrow i 0 +ret 1 +end +end +end +if ne dsget 3 0 +for i ulong dsget 3 +put b i get ds_sup i +end +if eq dsvalidsecretat b dsget 3 0 0 +ret 1 +end +end +if eq dsget 0 3 +for i ulong dsget 4 +put b i get ds_dis i +end +if eq dsvalidsecret b dsget 4 0 +ret 1 +end +else +if ne dsget 4 0 +ret 1 +end +end +put ds_ctl 0 0 +ret 0 +end diff --git a/cmd/tkad/test/faults.py b/cmd/tkad/test/faults.py new file mode 100755 index 0000000..d0b22e9 --- /dev/null +++ b/cmd/tkad/test/faults.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Compile test-only syscall-boundary fault variants; never production switches.""" +import hashlib +import json +import pathlib +import socket +import struct +import subprocess +import sys +import tempfile +import time + +root, binary = map(pathlib.Path, sys.argv[1:]) +source = pathlib.Path(str(binary) + ".om").read_text() +omc = subprocess.check_output(["sh",str(root/"tools/omc.sh")],text=True).strip() +fixture = json.loads((root/"cmd/tkad/test/fixture.json").read_text()) +write_needle = "fn stwr fd int b view uchar 65536 off ulong n ulong to long\nret write fd b off n\nend" +sync_needle = "fn stsync fd int to long\nret fsync fd\nend" +assert source.count(write_needle)==1 and source.count(sync_needle)==1 + + +def build(label, needle, replacement): + p = subprocess.run([omc],input=source.replace(needle,replacement).encode(),capture_output=True) + assert p.returncode==0,p.stderr.decode() + path=root/"build"/("tkad-fault-"+label);path.write_bytes(p.stdout);path.chmod(0o700) + return path + + +def start(binary, state, init=False): + p=subprocess.Popen([str(binary),str(state)]+(["--init"] if init else []),stdout=subprocess.PIPE,stderr=subprocess.PIPE) + deadline=time.monotonic()+10 + while time.monotonic()<deadline: + assert p.poll() is None,(p.returncode,p.communicate()) + try: + with socket.socket(socket.AF_UNIX) as s:s.connect(str(state/"tkad.sock")) + return p + except (FileNotFoundError,ConnectionRefusedError):time.sleep(.01) + raise AssertionError("startup timeout") + + +def rpc(state, route, body, node=0): + data=json.dumps(body).encode() + with socket.socket(socket.AF_UNIX) as s: + s.settimeout(10);s.connect(str(state/"tkad.sock")) + s.sendall(struct.pack("<4sBBHQI",b"TKA\x01",route,1,0,node,len(data))+data) + def exact(n): + b=b"" + while len(b)<n: + x=s.recv(n-len(b)) + if not x:return None + b+=x + return b + head=exact(12) + if head is None:return None,None + magic,status,zero,n=struct.unpack("<4sHHI",head) + assert magic==b"TKA\x01" and zero==0 + return status,json.loads(exact(n)) + + +register=dict(NodeID=1,NodeKey=fixture["nodes"][0],RotationPubkey=fixture["rotations"][0]) +for size,label in [(56,"terminator"),(16,"begin-header")]: + replacement=f"""global ds_fault ulong 1 +fn stwr fd int b view uchar 65536 off ulong n ulong to long +if eq n {size} +put ds_fault 0 add get ds_fault 0 1 +if eq get ds_fault 0 2 +ret -28 +end +end +ret write fd b off n +end""" + mutant=build(label,write_needle,replacement) + with tempfile.TemporaryDirectory(prefix="tkad-precommit-") as name: + state=pathlib.Path(name);p=start(mutant,state,True) + try: + before=rpc(state,11,{}) + assert rpc(state,9,register)[0]==503 + assert rpc(state,11,{})==before,"failed candidate became visible" + assert rpc(state,9,register)[0]==200,"transient failure poisoned future mutation" + status,after=rpc(state,11,{}) + assert status==200 and after["Revision"]==1 and len(after["Nodes"])==1 + assert p.poll() is None + finally:p.kill();p.communicate(timeout=10) + print(f"PASS tkad one-shot {label} ENOSPC: 503, unchanged live state, next mutation succeeds") + +replacement="""global ds_fault ulong 1 +fn stsync fd int to long +put ds_fault 0 add get ds_fault 0 1 +if eq get ds_fault 0 4 +ret -5 +end +ret fsync fd +end""" +mutant=build("uncertain",sync_needle,replacement) +with tempfile.TemporaryDirectory(prefix="tkad-uncertain-") as name: + state=pathlib.Path(name);p=start(mutant,state,True) + assert rpc(state,9,register)==(None,None),"uncertain commit sent a normal response" + p.communicate(timeout=10);assert p.returncode==74,p.returncode + p=start(binary,state) + try: + status,after=rpc(state,11,{}) + assert status==200 and after["Revision"]==1 and len(after["Nodes"])==1,"renamed candidate lost" + finally:p.kill();p.communicate(timeout=10) +print("PASS tkad post-rename directory-fsync EIO: fatal74, no reply, renamed candidate recovered") + + +def frames(snapshot): + result=[];p=16 + while True: + n=struct.unpack_from("<Q",snapshot,p)[0] + if n==0:return result + result.append(bytearray(snapshot[p+40:p+40+n])) + p+=40+n + + +def reseal(magic, payloads): + # Independent Python implementation of the documented store framing. + out=bytearray(magic);chain=bytes(32);total=0 + for count,payload in enumerate(payloads,1): + digest=hashlib.blake2s(payload).digest();total+=len(payload) + out+=struct.pack("<Q",len(payload))+digest+payload + chain=hashlib.blake2s(chain+digest+struct.pack("<QQQ",len(payload),total,count)).digest() + out+=bytes(8)+chain+struct.pack("<QQ",total,len(payloads)) + return out + + +with tempfile.TemporaryDirectory(prefix="tkad-semantic-recovery-") as name: + state=pathlib.Path(name);p=start(binary,state,True) + common=dict(Version=131,NodeKey=fixture["nodes"][0]) + try: + assert rpc(state,9,register)[0]==200 + assert rpc(state,1,dict(common,GenesisAUM=fixture["genesis"]),1)[0]==200 + pending=(state/"snapshot").read_bytes() + assert rpc(state,2,dict(common,Signatures={"1":fixture["signatures"][0]},SupportDisablement=fixture["secret"]),1)[0]==200 + finally:p.kill();p.communicate(timeout=10) + active=(state/"snapshot").read_bytes() + # Prove the independent reframer writes a valid baseline before using it + # to distinguish semantic validation from the checksum layer. + (state/"snapshot").write_bytes(reseal(active[:16],frames(active))) + p=start(binary,state);p.kill();p.communicate(timeout=10) + for label,index,offset in [("signature",2,-1),("support-secret",3,0),("genesis",4,-1),("reserved-metadata",0,40)]: + payloads=frames(active);payloads[index][offset]^=1 + (state/"snapshot").write_bytes(reseal(active[:16],payloads)) + refused=subprocess.run([str(binary),name],capture_output=True,timeout=10) + assert refused.returncode==73,(label,refused.returncode,refused.stderr) + payloads=frames(pending);struct.pack_into("<Q",payloads[0],16,99) + (state/"snapshot").write_bytes(reseal(pending[:16],payloads)) + refused=subprocess.run([str(binary),name],capture_output=True,timeout=10) + assert refused.returncode==73 +print("PASS tkad checksum-valid semantic corruption: NKS, genesis, support secret, reserved metadata, pending initiator rejected") diff --git a/cmd/tkad/test/fixture.go b/cmd/tkad/test/fixture.go new file mode 100644 index 0000000..0b97781 --- /dev/null +++ b/cmd/tkad/test/fixture.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// Test-only deterministic fixtures using the real pinned tailscale.com/tka API. +package main + +import ( + "bytes" + "crypto/ed25519" + "encoding/json" + "fmt" + "os" + "github.com/fxamacker/cbor/v2" + "tailscale.com/tailcfg" + "tailscale.com/tka" + "tailscale.com/types/key" + "tailscale.com/types/tkatype" +) + +func must(e error) { if e != nil { panic(e) } } +func sign(a tka.AUM, p ed25519.PrivateKey) tka.AUM { + h := a.SigHash() + a.Signatures = []tkatype.Signature{{KeyID:tkatype.KeyID(p.Public().(ed25519.PublicKey)), Signature:ed25519.Sign(p,h[:])}} + return a +} +func child(a, prev tka.AUM, p ed25519.PrivateKey) tka.AUM { + h:=prev.Hash(); a.PrevAUMHash=h[:]; return sign(a,p) +} +func hash(a tka.AUM) string { b,e:=a.Hash().MarshalText(); must(e); return string(b) } +func jsonOracle() { + var send tailcfg.TKASyncSendRequest + must(json.Unmarshal([]byte(`{"MiſſingAUMs":["AQ=="],"NodeKey":"nodekey:0909090909090909090909090909090909090909090909090909090909090909"}`), &send)) + if len(send.MissingAUMs)!=1 || send.MissingAUMs[0][0]!=1 || send.NodeKey.IsZero() { panic("Go Unicode field fold changed") } + for _, name:=range []string{"+1","01","-0"} { + var finish tailcfg.TKAInitFinishRequest + must(json.Unmarshal([]byte(`{"Signatures":{"`+name+`":"AQ=="}}`), &finish)) + if len(finish.Signatures)!=1 { panic("Go signed integer map key changed") } + } + var finish tailcfg.TKAInitFinishRequest + if json.Unmarshal([]byte(`{"Signatures":{"9223372036854775808":"AQ=="}}`), &finish)==nil { panic("Go accepted int64 map key overflow") } +} +func main() { + jsonOracle() + p:=ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1},32)) + q:=ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2},32)) + secret:=bytes.Repeat([]byte{42},32) + state:=tka.State{StateID1:123,StateID2:456,DisablementValues:[][]byte{tka.DisablementKDF(secret)},Keys:[]tka.Key{ + {Kind:tka.Key25519,Votes:1,Public:p.Public().(ed25519.PublicKey)}, + {Kind:tka.Key25519,Votes:1,Public:q.Public().(ed25519.PublicKey),Meta:map[string]string{"role":"old"}}, + }} + genesis:=sign(tka.AUM{MessageKind:tka.AUMCheckpoint,State:&state},p) + update:=child(tka.AUM{MessageKind:tka.AUMNoOp},genesis,p) + empty:=child(tka.AUM{MessageKind:tka.AUMUpdateKey,KeyID:tkatype.KeyID(q.Public().(ed25519.PublicKey)),Meta:map[string]string{}},update,p) + removal:=child(tka.AUM{MessageKind:tka.AUMRemoveKey,KeyID:tkatype.KeyID(q.Public().(ed25519.PublicKey))},empty,p) + // Serialize omits an empty Meta. Preserve its non-nil typed value on input, + // while hashing/signing retains upstream canonical omission semantics. + enc,e:=cbor.CTAP2EncOptions().EncMode(); must(e) + var wire map[uint64]any + must(cbor.Unmarshal(empty.Serialize(),&wire)); wire[7]=map[string]string{} + emptyWire,e:=enc.Marshal(wire); must(e) + ch:=tka.ChonkMem(); authority,e:=tka.Bootstrap(ch,genesis); must(e) + nodes:=[]string{}; rots:=[][]byte{}; sigs:=[][]byte{}; goodSigs:=[][]byte{} + for i:=byte(9);i<12;i++ { + var np key.NodePublic + must(np.UnmarshalBinary(append([]byte{'n','p'},bytes.Repeat([]byte{i},32)...))) + binary,e:=np.MarshalBinary(); must(e) + rot:=ed25519.NewKeyFromSeed(bytes.Repeat([]byte{i+32},32)).Public().(ed25519.PublicKey) + s:=tka.NodeKeySignature{SigKind:tka.SigDirect,Pubkey:binary,KeyID:q.Public().(ed25519.PublicKey),WrappingPubkey:rot} + h:=s.SigHash();s.Signature=ed25519.Sign(q,h[:]);must(authority.NodeKeyAuthorized(np,s.Serialize())) + nodes=append(nodes,np.String());rots=append(rots,rot);sigs=append(sigs,s.Serialize()) + s.KeyID=p.Public().(ed25519.PublicKey);h=s.SigHash();s.Signature=ed25519.Sign(p,h[:]);goodSigs=append(goodSigs,s.Serialize()) + } + var decoded tka.AUM;must(decoded.Unserialize(emptyWire));must(decoded.StaticValidate()) + must(authority.Inform(ch,[]tka.AUM{update,decoded,removal})) + var np key.NodePublic;must(np.UnmarshalText([]byte(nodes[0]))) + if authority.NodeKeyAuthorized(np,sigs[0])==nil { panic("removed signer remains trusted") } + must(authority.NodeKeyAuthorized(np,goodSigs[0])) + if !authority.ValidDisablement(secret) { panic("disablement mismatch") } + result:=map[string]any{"genesis":genesis.Serialize(),"head":hash(genesis),"update":update.Serialize(),"updatedHead":hash(update),"emptyMeta":emptyWire,"emptyHead":hash(empty),"removal":removal.Serialize(),"removedHead":hash(removal),"nodes":nodes,"rotations":rots,"signatures":sigs,"goodSignatures":goodSigs,"keyID":q.Public().(ed25519.PublicKey),"secret":secret,"source":"tailscale.com v1.102.0 real tka authority"} + b,e:=json.MarshalIndent(result,""," ");must(e);fmt.Fprintln(os.Stdout,string(b)) +} diff --git a/cmd/tkad/test/fixture.json b/cmd/tkad/test/fixture.json new file mode 100644 index 0000000..9132aee --- /dev/null +++ b/cmd/tkad/test/fixture.json @@ -0,0 +1,33 @@ +{ + "emptyHead": "SILUFPEH2OHZF55CW3D2JT5H5Q5KL6ZQNBSFBEQ5XFSHSTGLLC5Q", + "emptyMeta": "pQEEAlggWYa85PTslxB4mYC81L4JtsZXAxvnFs/GWHdER2+4amEEWCCBOXcOqH0XX1ajVGbDTH7My42KkbTuN6Jd9g9bj8mzlAegF4GiAVggiojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1wCWEAMdvLLJRnGpMqpIZR/cbkDoP5ga7WIe5GV++jA2p2AJqX9VrcuiaI1H8XTeX51AyqhNjFegYvGSBUwJzH2AW4O", + "genesis": "pAEFAvYFpQH2AoFYILTFrDQBTkQarp7XQWKK2+s40ndKlQxYmA9vuO4wtAI2A4KjAQECAQNYIIqI4910CfGV/VLbLTy6XXLKZwm/HZQSG/N0iAG0D29cpAEBAgEDWCCBOXcOqH0XX1ajVGbDTH7My42KkbTuN6Jd9g9bj8mzlAyhZHJvbGVjb2xkBBh7BRkByBeBogFYIIqI4910CfGV/VLbLTy6XXLKZwm/HZQSG/N0iAG0D29cAlhAvq6wLI0Zd6J6sDwK930ZQ/Xq4DPeFwzctcXkiygjDkzhUftSo+O4C/iTJINgWADWOY1obOsNS+xuGOpFtn1/Dw==", + "goodSignatures": [ + "pQEBAlgibnAJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQNYIIqI4910CfGV/VLbLTy6XXLKZwm/HZQSG/N0iAG0D29cBFhADq2E1CI/0BQYD4zDC0/QX5LqcyVluitoQaGC5kwze2xCMCZXFfpyRwlm0rIBnCVrWXF4RhoyvtBCGJv31nBMAwZYIPpINBR/bmkMNpPv9hM2BGQDzYrioU8xs8QHNYVpI5Vl", + "pQEBAlgibnAKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgNYIIqI4910CfGV/VLbLTy6XXLKZwm/HZQSG/N0iAG0D29cBFhAI+qILfP/4gMoMvy4avaI6qu/1/9gbzrnPVzPxfct7GptIzDlRfCQYBtxxBBlg8FyGPlqdI5adcgfPE2k50W6CwZYIBl/ayPhbIUyxqvIOPrNXqeJvgx2spIDNAOb+os9No1h", + "pQEBAlgibnALCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwNYIIqI4910CfGV/VLbLTy6XXLKZwm/HZQSG/N0iAG0D29cBFhAsxtvFFRit0eXITRkhWJHVVJwMkpgBueUVt365EagZJR8rrKWFDilHWWfr/F3eps1GSPn9qCfwZpi0ocPtXddCgZYIEUIoHqpQXB/PrLblMiJeoCywRl0drbeITrCc999hsT/" + ], + "head": "5RCWA2QNFG3NTGDHC6LPZJFIK5SFCJLBLVAUGSM7RJ3IH6H4OVJQ", + "keyID": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=", + "nodes": [ + "nodekey:0909090909090909090909090909090909090909090909090909090909090909", + "nodekey:0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a", + "nodekey:0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" + ], + "removal": "pAECAlggkhdCvIfTj5L3orbHpM+n7Dql+zBoZFCSHblkeUzLWLsEWCCBOXcOqH0XX1ajVGbDTH7My42KkbTuN6Jd9g9bj8mzlBeBogFYIIqI4910CfGV/VLbLTy6XXLKZwm/HZQSG/N0iAG0D29cAlhA59UFaWgC2wpmUbmRY8eE+9jqcbvZJQofL0j2uH+0a/j5k6qUJUvFgdOflive+r0dd6VWEyqcGFWaCUsqt8NLDw==", + "removedHead": "BQGJSMOERA4YEQGTHFRGZSALNRUHKN76QWIKZKTXWFUWMCBMU5QA", + "rotations": [ + "+kg0FH9uaQw2k+/2EzYEZAPNiuKhTzGzxAc1hWkjlWU=", + "GX9rI+FshTLGq8g4+s1ep4m+DHaykgM0A5v6iz02jWE=", + "RQigeqlBcH8+stuUyIl6gLLBGXR2tt4hOsJz332GxP8=" + ], + "secret": "KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKio=", + "signatures": [ + "pQEBAlgibnAJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQNYIIE5dw6ofRdfVqNUZsNMfszLjYqRtO43ol32D1uPybOUBFhA6Cl3+7cRNFdA5/gnnd9FdDvF6DtNu3TloqFmBu0KOW0N5fu9a+aOiZW/7+fALgVfQQnKS2p/U/GShN0GVQPPCAZYIPpINBR/bmkMNpPv9hM2BGQDzYrioU8xs8QHNYVpI5Vl", + "pQEBAlgibnAKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgNYIIE5dw6ofRdfVqNUZsNMfszLjYqRtO43ol32D1uPybOUBFhA4ELrzLB8Qmx/zQl+xtiGoHrXyoOfzEvVvRVl5D4Psz34JFPX+LYt2f6Kpd0y1pZCsx6jSYkwhGmjvLMgxm1CCAZYIBl/ayPhbIUyxqvIOPrNXqeJvgx2spIDNAOb+os9No1h", + "pQEBAlgibnALCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwNYIIE5dw6ofRdfVqNUZsNMfszLjYqRtO43ol32D1uPybOUBFhAh/fTPG/O9VsHFSENsD7ujZoYsdR+1tdXrmp+82T0kuD7xBeo+EkA/Yevur/HgHqc22idMC40rwEh4zUXSwhCCQZYIEUIoHqpQXB/PrLblMiJeoCywRl0drbeITrCc999hsT/" + ], + "source": "tailscale.com v1.102.0 real tka authority", + "update": "owEDAlgg7EVgag0pttmYZxeW/KSoV2RRJWFdQUNJn4p2g/j8dVMXgaIBWCCKiOPddAnxlf1S2y08ul1yymcJvx2UEhvzdIgBtA9vXAJYQGuq6mnwdcC4gWr82f70JmTEukBPdPEWcwvYEJRjR33XdVztmeP+/9yKoeYP25MafLpWRjRWTSttFRvQtrPyjgI=", + "updatedHead": "LGDLZZHU5SLRA6EZQC6NJPQJW3DFOAY344LM7RSYO5CEO35YNJQQ" +} diff --git a/cmd/tkad/test/mutant.py b/cmd/tkad/test/mutant.py new file mode 100755 index 0000000..722e6cf --- /dev/null +++ b/cmd/tkad/test/mutant.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +import pathlib +import subprocess +import sys + +root, binary = map(pathlib.Path, sys.argv[1:]) +source = pathlib.Path(str(binary) + ".om").read_text() +omc = subprocess.check_output(["sh", str(root / "tools/omc.sh")], text=True).strip() +needle = "fn dsbegin t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int\nif eq get ds_ctl 3 0\nret 403\nend" +assert source.count(needle) == 1 +variants = { + "admin-bypass": needle.replace("if eq get ds_ctl 3 0", "if eq get ds_ctl 3 2"), + "trap": needle.replace("ret 403", "trap 1"), +} +for label, replacement in variants.items(): + path = root / "build" / ("tkad-mutant-" + label) + build = subprocess.run([omc], input=source.replace(needle, replacement).encode(), capture_output=True) + assert build.returncode == 0, build.stderr.decode() + path.write_bytes(build.stdout) + path.chmod(0o700) + run = subprocess.run([sys.executable, str(root / "cmd/tkad/test/smoke.py"), str(path), "--probe"], capture_output=True, text=True, timeout=60) + completed_mismatch = run.returncode != 0 and "expected 403, got 200" in run.stderr + if label == "admin-bypass": + assert completed_mismatch, (run.returncode, run.stdout, run.stderr) + print("PASS tkad completed-response admin-bypass mutant detected") + else: + assert run.returncode != 0 and not completed_mismatch and "truncated daemon reply" in run.stderr, (run.returncode, run.stdout, run.stderr) + print("PASS tkad trapping mutant rejected, not counted as detection") diff --git a/cmd/tkad/test/rollover.py b/cmd/tkad/test/rollover.py new file mode 100755 index 0000000..e8d535c --- /dev/null +++ b/cmd/tkad/test/rollover.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +import json +import os +import pathlib +import socket +import struct +import subprocess +import sys +import tempfile +import time + +root, binary = map(pathlib.Path, sys.argv[1:]) +source = pathlib.Path(str(binary) + ".om").read_text() +needle = "fn dsbatch fd int to void\nfor i ulong 100000" +assert source.count(needle) == 1 +omc = subprocess.check_output(["sh", str(root / "tools/omc.sh")], text=True).strip() +built = subprocess.run([omc], input=source.replace(needle, needle.replace("100000", "2")).encode(), capture_output=True) +assert built.returncode == 0, built.stderr.decode() +epoch = root / "build/tkad-epoch2" +epoch.write_bytes(built.stdout); epoch.chmod(0o700) +frame = struct.pack("<4sBBHQI", b"TKA\x01", 11, 1, 0, 0, 2) + b"{}" + + +def exact(s, n): + out = b"" + while len(out) < n: + v = s.recv(n-len(out)) + assert v, "truncated rollover reply" + out += v + return out + + +def response(s): + magic, status, reserved, n = struct.unpack("<4sHHI", exact(s, 12)) + assert magic == b"TKA\x01" and status == 200 and reserved == 0 + result = json.loads(exact(s, n)); s.close() + assert result == {"TKAInfo":None,"Revision":0,"Nodes":[]}, result + + +with tempfile.TemporaryDirectory(prefix="tkad-rollover-") as name: + path = pathlib.Path(name) + p = subprocess.Popen([str(epoch), name, "--init"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + deadline = time.monotonic()+10 + while not (path/"tkad.sock").exists(): + assert p.poll() is None, p.communicate() + assert time.monotonic() < deadline + time.sleep(.01) + pid = p.pid + # Connect both before sending the first request. The next connection is + # queued while the epoch boundary exec replaces the process image. + for _ in range(8): + a = socket.socket(socket.AF_UNIX); a.settimeout(10); a.connect(str(path/"tkad.sock")) + b = socket.socket(socket.AF_UNIX); b.settimeout(10); b.connect(str(path/"tkad.sock")) + a.sendall(frame); b.sendall(frame) + response(a); response(b) + assert p.pid == pid and p.poll() is None + link = os.readlink(f"/proc/{pid}/fd/66") + for _ in range(4): + s = socket.socket(socket.AF_UNIX);s.settimeout(10);s.connect(str(path/"tkad.sock"));s.sendall(frame);response(s) + assert os.readlink(f"/proc/{pid}/fd/66") == link, "listener replaced" + contender = subprocess.run([str(binary),name],capture_output=True,timeout=10) + assert contender.returncode == 73, (contender.returncode,contender.stderr) + finally: + p.kill();p.communicate(timeout=10) + missing = subprocess.run([str(epoch),"--resume"],capture_output=True,timeout=10) + assert missing.returncode == 73 + directory = os.open(name,os.O_RDONLY|os.O_DIRECTORY) + wrong = socket.socket(socket.AF_UNIX);wrong.bind("\0tkad-invalid-resume-"+str(os.getpid())) + def swapped(): + os.dup2(wrong.fileno(),64,inheritable=True) + os.dup2(directory,65,inheritable=True) + bad = subprocess.run([str(epoch),"--resume"],preexec_fn=swapped,close_fds=False,capture_output=True,timeout=10) + assert bad.returncode == 73 + wrong.close();os.close(directory) +print("PASS tkad epoch2 self-exec: queued clients, stable PID/listener, retained exclusion, missing/swapped FD refusal") diff --git a/cmd/tkad/test/run.sh b/cmd/tkad/test/run.sh new file mode 100755 index 0000000..730c23b --- /dev/null +++ b/cmd/tkad/test/run.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +set -eu +root=$(CDPATH= cd -- "$(dirname -- "$0")/../../.." && pwd) +if [ "${REGEN:-0}" = 1 ] || [ ! -f "$root/cmd/tkad/test/fixture.json" ]; then + (cd "$root/om/tka/test/oracle" && "${GO:-go}" run -mod=readonly "$root/cmd/tkad/test/fixture.go") > "$root/cmd/tkad/test/fixture.json" +fi +bin=$(sh "$root/tools/build-tkad.sh") +python3 "$root/cmd/tkad/test/smoke.py" "$bin" +python3 "$root/cmd/tkad/test/mutant.py" "$root" "$bin" +python3 "$root/cmd/tkad/test/rollover.py" "$root" "$bin" +python3 "$root/cmd/tkad/test/faults.py" "$root" "$bin" diff --git a/cmd/tkad/test/smoke.py b/cmd/tkad/test/smoke.py new file mode 100755 index 0000000..607b338 --- /dev/null +++ b/cmd/tkad/test/smoke.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Real AF_UNIX tests: no production backend or protocol mocks.""" +import base64 +import json +import os +import pathlib +import resource +import signal +import socket +import struct +import subprocess +import sys +import tempfile +import time + +BIN = pathlib.Path(sys.argv[1]).resolve() +FIX = json.loads(pathlib.Path(__file__).with_name("fixture.json").read_text()) +PROBE = "--probe" in sys.argv +checks = 0 + + +def check(value, message): + global checks + assert value, message + checks += 1 + + +def exact(sock, count): + result = b"" + while len(result) < count: + part = sock.recv(count - len(result)) + if not part: + raise AssertionError("truncated daemon reply") + result += part + return result + + +class Daemon: + def __init__(self, directory, initialize=False, file_limit=None): + self.directory = pathlib.Path(directory) + self.path = str(self.directory / "tkad.sock") + def limits(): + if file_limit is not None: + signal.signal(signal.SIGXFSZ, signal.SIG_IGN) + resource.setrlimit(resource.RLIMIT_FSIZE, (file_limit, file_limit)) + self.p = subprocess.Popen([str(BIN), str(self.directory)] + (["--init"] if initialize else []), stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=limits) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + if self.p.poll() is not None: + raise AssertionError(f"startup rc={self.p.returncode}: {self.p.communicate()}") + try: + with socket.socket(socket.AF_UNIX) as s: + s.settimeout(.2) + s.connect(self.path) + return + except (FileNotFoundError, ConnectionRefusedError, TimeoutError): + time.sleep(.02) + raise AssertionError("socket readiness timeout") + + def stop(self): + if self.p.poll() is None: + self.p.kill() + self.p.communicate(timeout=10) + + def rpc(self, route, body=None, node=1, admin=False, expected=200, raw=None): + payload = raw if raw is not None else json.dumps(body or {}, separators=(",", ":")).encode() + frame = struct.pack("<4sBBHQI", b"TKA\x01", route, int(admin), 0, node, len(payload)) + payload + with socket.socket(socket.AF_UNIX) as s: + s.settimeout(30) + s.connect(self.path) + s.sendall(frame) + magic, status, reserved, size = struct.unpack("<4sHHI", exact(s, 12)) + check(magic == b"TKA\x01" and reserved == 0 and size <= 65536, "reply header") + answer = json.loads(exact(s, size)) + check(status == expected, f"route {route}: expected {expected}, got {status}: {answer}") + check(self.p.poll() is None, "daemon trapped/exited") + return answer + + def req(self, **fields): + return dict(Version=131, NodeKey=FIX["nodes"][0], **fields) + + def register(self, index, **kwargs): + return self.rpc(9, dict(NodeID=index + 1, NodeKey=FIX["nodes"][index], RotationPubkey=FIX["rotations"][index], **kwargs), node=0, admin=True) + + def map(self): + return self.rpc(11, node=0, admin=True) + + +def refused_start(directory, *args): + p = subprocess.run([str(BIN), str(directory), *args], capture_output=True, timeout=20) + check(p.returncode != 0 and not 100 <= p.returncode <= 114, f"startup must refuse normally, rc={p.returncode}") + + +def enable(d): + d.register(0) + d.register(1) + ans = d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), admin=True) + check([v["NodeID"] for v in ans["NeedSignatures"]] == [1, 2], "complete frozen roster") + check(ans["NeedSignatures"][1]["RotationPubkey"] == FIX["rotations"][1], "rotation public key") + d.rpc(2, d.req(Signatures={"1": FIX["signatures"][0], "2": FIX["signatures"][1]}, SupportDisablement=FIX["secret"]), admin=True) + + +with tempfile.TemporaryDirectory(prefix="omnet-tkad-") as top: + root = pathlib.Path(top) + state = root / "state" + state.mkdir(mode=0o700) + d = Daemon(state, True) + try: + d.register(0) + if PROBE: + # A completed-result mutant must return a different result, not trap. + d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), expected=403) + print("PASS tkad authorization probe") + sys.exit(0) + refused_start(state) + refused_start(state, "--init") + d.rpc(11, admin=False, expected=403) + d.rpc(3, d.req(), expected=409) + d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), expected=403) + d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), node=99, admin=True, expected=403) + d.rpc(1, dict(Version=131, NodeKey=FIX["nodes"][1], GenesisAUM=FIX["genesis"]), admin=True, expected=403) + d.rpc(1, d.req(GenesisAUM="AA=="), admin=True, expected=400) + d.register(1) + before = d.map() + begin = d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), admin=True) + check(len(begin["NeedSignatures"]) == 2, "begin roster") + check(d.map()["TKAInfo"] is None, "pending genesis invisible") + d.rpc(2, dict(Version=131, NodeKey=FIX["nodes"][1], Signatures={"1":FIX["signatures"][0],"2":FIX["signatures"][1]}), node=2, admin=True, expected=409) + d.rpc(2, d.req(Signatures={"1":FIX["signatures"][0]}), admin=True, expected=409) + d.rpc(2, d.req(Signatures={"1":FIX["signatures"][1],"2":FIX["signatures"][1]}), admin=True, expected=400) + d.rpc(2, d.req(Signatures={"1":FIX["signatures"][0],"01":FIX["signatures"][0]}), admin=True, expected=400) + d.rpc(2, d.req(Signatures={"9223372036854775808":FIX["signatures"][0],"2":FIX["signatures"][1]}), admin=True, expected=400) + d.rpc(2, d.req(Signatures={"-0":FIX["signatures"][0],"2":FIX["signatures"][1]}), admin=True, expected=409) + d.stop(); d = Daemon(state) + check(d.map()["TKAInfo"] is None, "pending recovered but invisible") + d.register(1) # Any roster update invalidates pending init, even same bytes. + d.rpc(2, d.req(Signatures={"1":FIX["signatures"][0],"2":FIX["signatures"][1]}), admin=True, expected=409) + d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), admin=True) + d.rpc(2, d.req(Signatures={"01":FIX["signatures"][0],"+2":FIX["signatures"][1]}, SupportDisablement=FIX["secret"]), admin=True) + check(d.map()["TKAInfo"] == {"Head":FIX["head"]}, "active map info") + boot = d.rpc(3, d.req(Head="")) + check(boot == {"GenesisAUM":FIX["genesis"]}, "bootstrap exact omission") + alias = d.req(Head=""); alias["NodeKey"] = alias.pop("NodeKey") + check(d.rpc(3, alias) == boot, "Go Kelvin-sign field fold") + duplicate = d.req(Head=""); duplicate["NodeKey"] = FIX["nodes"][0] + d.rpc(3, duplicate, expected=400) + d.rpc(5, d.req(Head=FIX["head"], **{"MiſſingAUMs": []})) + d.rpc(5, d.req(Head=FIX["head"], MissingAUMs=[], **{"MiſſingAUMs": []}), expected=400) + d.rpc(4, d.req(Head=FIX["head"], Ancestors=[])) + d.rpc(5, d.req(Head=FIX["updatedHead"], MissingAUMs=[FIX["update"]], Interactive=True)) + offer = d.rpc(4, d.req(Head=FIX["head"], Ancestors=[])) + check(offer["Head"] == FIX["updatedHead"] and offer["MissingAUMs"] == [FIX["update"]], "sync missing real AUM") + d.rpc(5, d.req(Head=FIX["updatedHead"], MissingAUMs=["AA=="], Interactive=False), expected=400) + check(d.map()["TKAInfo"]["Head"] == FIX["updatedHead"], "bad batch atomic") + d.register(2) + d.rpc(7, d.req(Signature=FIX["signatures"][2])) + check(d.map()["Nodes"][2]["KeySignature"] == FIX["signatures"][2], "sign caller differs from target") + bad = bytearray(base64.b64decode(FIX["signatures"][2])); bad[-1] ^= 1 + d.rpc(7, d.req(Signature=base64.b64encode(bad).decode()), expected=403) + affected = d.rpc(8, d.req(KeyID=FIX["keyID"])) + check(affected["Signatures"] == FIX["signatures"], "affected raw signature array") + d.rpc(5, d.req(Head=FIX["emptyHead"], MissingAUMs=[FIX["emptyMeta"]], Interactive=True)) + snapshot_map = d.map() + d.stop(); d = Daemon(state) + check(d.map() == snapshot_map, "typed empty metadata replay and signatures") + d.rpc(5, d.req(Head=FIX["removedHead"], MissingAUMs=[FIX["removal"]], Interactive=True)) + d.rpc(7, d.req(Signature=FIX["signatures"][2]), expected=403) + d.stop(); d = Daemon(state) + check(d.map()["TKAInfo"]["Head"] == FIX["removedHead"], "revoked historical signatures recover") + d.rpc(7, d.req(Signature=FIX["goodSignatures"][2])) + d.rpc(6, d.req(Head=FIX["removedHead"], DisablementSecret=FIX["secret"]), expected=403) + d.rpc(6, d.req(Head=FIX["head"], DisablementSecret=FIX["secret"]), admin=True, expected=409) + d.rpc(6, d.req(Head=FIX["removedHead"], DisablementSecret="AA=="), admin=True, expected=403) + d.rpc(3, raw=b'{"NodeKey":"x","NodeKey":"y"}', expected=400) + duplicate = json.dumps(d.req()).encode()[:-1] + b',"nodekey":"x"}' + d.rpc(3, raw=duplicate, expected=400) + d.rpc(3, raw=b'{', expected=400) + d.rpc(250, {}, node=0, admin=True, expected=404) + # Partial/oversized headers are isolated to their connection; later requests work. + for frame in [b"TK", struct.pack("<4sBBHQI", b"TKA\x01", 3, 0, 0, 1, 65537), struct.pack("<4sBBHQI", b"TKA\x01", 3, 0, 0, 1, 5) + b"{"]: + with socket.socket(socket.AF_UNIX) as s: + s.connect(d.path); s.sendall(frame) + d.map() + with socket.socket(socket.AF_UNIX) as s: + s.connect(d.path); s.sendall(b"T") + time.sleep(3.2) + d.map() + # Pre-rename disk write error must preserve live state and durable state. + stable = d.map() + d.stop(); d = Daemon(state, file_limit=1) + d.rpc(10, {"NodeID":3}, node=0, admin=True, expected=503) + check(d.map() == stable, "disk failure cannot publish candidate") + d.stop(); d = Daemon(state) + check(d.map() == stable, "disk failure cannot change recovery") + d.rpc(6, d.req(Head=FIX["removedHead"], DisablementSecret=FIX["secret"]), admin=True) + check(d.map()["TKAInfo"] == {"Disabled":True}, "disabled info distinct from nil") + check(d.rpc(3, d.req(Head=FIX["removedHead"])) == {"DisablementSecret":FIX["secret"]}, "disabled bootstrap secret only") + disabled = d.map() + d.stop(); d = Daemon(state) + check(d.map() == disabled, "disablement survives restart") + d.rpc(10, {"NodeID":3}, node=0, admin=True) + check(len(d.map()["Nodes"]) == 2, "registry remove") + finally: + d.stop() + # Corrupt snapshot is never interpreted as an empty fresh installation. + snap = state / "snapshot" + data = bytearray(snap.read_bytes()); data[len(data)//2] ^= 128; snap.write_bytes(data) + refused_start(state) + missing = root / "missing"; missing.mkdir(mode=0o700) + refused_start(missing) + insecure = root / "insecure"; insecure.mkdir(mode=0o755) + refused_start(insecure, "--init") + print(f"PASS tkad real socket {checks} assertions: 8 RPCs, registry/map, security, restart, disk failure, malformed framing") diff --git a/docs/design/tailnet-lock.md b/docs/design/tailnet-lock.md index b31fbc3..eb30b20 100644 --- a/docs/design/tailnet-lock.md +++ b/docs/design/tailnet-lock.md @@ -1,6 +1,6 @@ # Tailnet Lock for self-hosted control servers -Status: crypto, typed models, node signatures and bounded in-memory authority implemented. See [Plan and status](#plan-and-status). +Status: bounded local Omega daemon, durable snapshots, JSON RPCs and TKA authority implemented. Headscale integration remains pending. See [Plan and status](#plan-and-status). ## Problem @@ -102,10 +102,20 @@ flowchart LR It listens on a local socket, using the Omega native host operations from omega-mv `seed/host/`. -**Storage**: an append-only directory of AUM files named by hash, plus one state file that is -replaced by write, fsync and rename. Every file is opened through descriptors, never re-checked by path -(design rule 2). A request that would change the head is applied to a copy and becomes visible only -after it is durable. +**Storage design for stage four**: a single versioned whole-service snapshot, including authority +updates in reconstruction-preserving typed form, node records/signatures, pending initialization, +and disablement state. A candidate is built in the inactive authority slot. Write a temporary file, +fsync it, rename it over the committed snapshot, then fsync the directory before publishing the +candidate or acknowledging success. Failure after rename but before directory fsync is an uncertain +commit: stop serving, do not attempt a rollback rename. Recovery validates the entire committed +snapshot; a missing or corrupt snapshot is not interpreted as disabled TKA. + +The state directory is provisioned under trusted ancestors, owned by the effective UID, and mode +0700. Open and validate its descriptor, then use fixed relative names after `fchdir`; reject +unexpected file types, permissions, ownership and hard links. A separate bind-only abstract Unix +socket keyed by directory device/inode provides writer exclusion in one Linux network namespace. +Only its holder may remove a stale RPC socket. All writers must use the same network namespace; +same-UID processes and root remain trusted. This is not cross-namespace locking. **headscale glue** (Go, in a headscale fork) holds no protocol logic. It: 1. Registers the eight `/machine/tka/*` routes on the Noise router. Each passes the authenticated @@ -119,9 +129,11 @@ after it is durable. Its only decision is which nodes may call admin RPCs: `init/*` and `disable` are restricted to the tailnet owner. It makes that decision from headscale's own user model. -**Privilege**: tkad runs as its own unprivileged user. It owns only its state directory and the socket -that headscale connects to (design rule 4). A crash in tkad, which is what an Omega trap is, refuses -TKA requests. It never makes headscale skip verification: the glue fails closed. +**Local trust boundary for stage four**: the RPC socket lives inside the private state directory. +Same-UID local adapters may supply authenticated node identity and administrator assertions; +the daemon does not authenticate remote Tailscale clients itself. Before separate-UID Headscale +integration, move the RPC socket into a distinct access-controlled directory without granting the +adapter access to the state files. Production integration must fail closed on daemon errors. **Current unit limits**: model and crypto inputs are capped at 64 KiB. The in-memory authority holds 128 AUMs per slot and two slots; capacity exhaustion returns an error without evicting history. @@ -148,9 +160,10 @@ that way. That is a client issue outside this project; tkad's error bodies are s | CTAP2 CBOR encode and decode, bounded (`om/cbor`) | Omega | done: RFC 8949 App. A, 1,200 `tka` structures byte-identical with matching `AUM.Hash`, 475 hostile cases | | AUM / State / Key model, validation and authorized transitions (`om/tka`) | Omega | implemented: typed reconstruction and differential oracle | | NodeKeySignature model and verification (`om/tkasig`) | Omega | implemented: direct, credential and rotation, strict/ZIP-215 rules | -| Bounded in-memory chain (`om/tka`): fork choice, state at hash, sync, atomic Inform | Omega | implemented: two slots, 128 AUMs each; no durable storage | -| JSON for the eight RPC types | Omega | planned | -| tkad service: socket loop, storage | Omega | planned | +| Bounded in-memory chain (`om/tka`): fork choice, state at hash, sync, atomic Inform | Omega | implemented: two slots, 128 AUMs each; daemon adds persistence | +| JSON (`om/json`) and eight RPC handlers (`cmd/tkad`) | Omega | implemented: bounded parsing, trusted adapter identity binding | +| Snapshot storage (`om/store`) | Omega | implemented: descriptor validation, writer exclusion, atomic publication, recovery | +| tkad service (`cmd/tkad`) | Omega | implemented: private Unix socket, registry/map commands, controlled self-exec | | headscale glue | Go (fork) | planned | ## Verification plan @@ -187,13 +200,33 @@ Go 1.26.8 supplied the pinned TKA oracle; the existing optional oracle compariso These are bounded in-memory host results, not stock-client end-to-end, durable-storage, constant-time, or production-network qualification. +### Stage-four verification + +The complete `tools/test.sh` run passed all twelve library/daemon suites on ARM64 Linux. +The compiler pin was unchanged. New results: + +- JSON: 7,706 differential cases and 22 golden vectors; six completed-result mutants detected. +- Store: 116 completed native cases, independent BLAKE2s framing referee and checksum mutant. + Foreign-UID ownership fixtures were skipped because the runner was not root. +- Daemon: 224 real-socket assertions across all eight RPCs and registry/map commands. + Additional scenarios exercised two-iteration self-exec with queued clients and continuous + writer exclusion, missing/swapped resume descriptors, pre-rename ENOSPC followed by successful + mutation without restart, and post-rename fsync failure with no reply and recovery of the + renamed candidate. Checksum-valid but semantically corrupt snapshots were rejected. +- Separate launch smoke observed an initialized map response, a 403 for a missing admin assertion, + and identical state after process termination/restart. + +These checks do not establish filesystem power-loss durability, cross-namespace writer exclusion, +stock-client compatibility beyond the tested profile, or production deployment security. + ## Plan and status 1. Crypto primitives: BLAKE2s, SHA-512, Ed25519. **Done.** 2. BLAKE2b, Argon2i, codecs, CBOR. **Done.** 3. TKA model and bounded in-memory chain logic, differential against `tka`. **Implemented.** Cross-unit smoke checks node authorization before and after a signed authority-key removal. -4. tkad service, storage, JSON. +4. tkad service, storage, JSON. **Implemented for the bounded same-UID local-adapter profile.** + See [`cmd/tkad/README.md`](../../cmd/tkad/README.md) for invocation, framing, limits and tests. 5. headscale glue and end-to-end tests with stock clients. 6. Review by a second implementer before any production use. Until then this is pre-alpha and does not protect a tailnet. diff --git a/om/json/README.md b/om/json/README.md new file mode 100644 index 0000000..17a8bed --- /dev/null +++ b/om/json/README.md @@ -0,0 +1,143 @@ +# Bounded JSON + +`json.om` is an Omega-only, global-free JSON parser and encoder for the daemon's raw TKA requests. +It has no dependencies on another unit. Concatenate it before callers. Parsing is iterative, not +recursive, and retains exact number lexemes rather than converting through floating point. + +## Limits and policy + +- Input, decoded string/number arena, and output each have a separate 65,536-byte capacity. +- At most 4,095 tokens, counting object keys and container tokens. At most 32 nested containers. + Scalars inside the 32nd container are accepted. A string of 65,534 ASCII bytes fits as one input + string; decoded replacement characters can expand invalid input beyond the arena limit. +- At most 256 members per object, independently at every nesting level. The attempted 257th key + is rejected before its decoding or duplicate scan. This intentionally rejects larger objects + that Go accepts. It bounds the quadratic duplicate-key scan; the daemon's 64-node signature + map fits this profile. Arrays remain governed by the overall token bound. +- All JSON grammar is checked, including number grammar, matching delimiters, separators, control + characters, escapes, and the absence of a second root value or trailing non-whitespace bytes. +- Strings follow Go `encoding/json`: UTF-16 surrogate pairs combine; lone surrogates become U+FFFD; + invalid UTF-8 is replaced one offending byte at a time. Embedded U+0000 is preserved with an + explicit length. Valid UTF-8 and literal Unicode are retained. +- **Duplicate decoded object keys are rejected in every object.** This intentionally differs from + Go's last-value/merge behavior. Escape aliases (`"a"` and `"\u0061"`), invalid UTF-8 aliases and + lone-surrogate aliases therefore cannot overwrite one another. Equality is case-sensitive; it + does not perform Unicode normalization. Callers implementing Go's case-insensitive struct-field + lookup must additionally reject aliases of the same known field. `jsonfind` is exact-case only. +- This unit checks JSON syntax, not the TKA schema. For example `{"GenesisAUM":true}` is valid JSON + but is not a valid `tailcfg.TKAInitBeginRequest`. The daemon must enforce field types, required + fields, case aliases, integer destination widths and codec-specific limits. Byte arrays/base64, + node keys and AUM hashes are decoded by their existing codec/model units. + +Bound violations return errors, never attacker-triggered traps. Callers must provide the fixed-size +arrays named in the signatures, use distinct input/arena/token/output arrays, and discard partial +output on failure. Token accessors and `jsonencode` require an unmodified table and arena from a +successful `jsonparse`; a forged token table is a caller contract violation. Only `tok[0]` is valid +following a failed parse (it is zero). Other data is scratch and may contain partial results. + +## Parsing API + +`jsonparse(raw view uchar 65536, n ulong, tok edit ulong 32768, + dec edit uchar 65536) -> int` + +Returns zero on success, otherwise: 1 syntax, 2 input/decoded-byte bound, 3 token bound, +4 depth bound, 5 duplicate key, 6 object-member bound. Empty input is rejected. No I/O or global state is used. + +`tok[0]` is the token count. Root id is 1; zero is the absent-id sentinel. Header slots 1..7 +are reserved. Token `id` starts at `id * 8`, with these fields: + +| Offset | Meaning | +|---|---| +| 0 | Kind: 1 object, 2 array, 3 string, 4 number, 5 true, 6 false, 7 null | +| 1 | Offset into `dec` for decoded string or raw number lexeme | +| 2 | Byte length; zero for containers, booleans and null | +| 3 | Id immediately after the entire subtree | +| 4 | Parent container id; zero at root | +| 5 | Direct-child count; includes both keys and values for objects | +| 6 | 1 for an object key, otherwise 0 | +| 7 | Internal parser phase; callers must not inspect it | + +Children are preorder. An object's children alternate key, value; a key is always a string token +and its value starts at `key_id + 1`. Use a value's subtree-next field to advance to the next key. + +- `jsonfind(tok, dec, obj ulong, key view uchar 65536, n ulong) -> ulong`: exact decoded key lookup; + returns the value id or zero. Only direct members of `obj` are searched. +- `jsoncopy(tok, dec, id ulong, out edit uchar 65536) -> ulong`: copies the token's string/number + bytes, returning their length; invalid id returns `jsonbad` (65,537). +- `jsonuint(dec, off ulong, n ulong, result edit ulong 1) -> int`: exact unsigned 64-bit decimal + conversion; zero on success. Rejects negative signs, leading zeros, fractions, exponents, + whitespace and overflow. Result is zero on failure. +- `jsonint(dec, off ulong, n ulong, result edit long 1) -> int`: exact signed 64-bit conversion, + including -9,223,372,036,854,775,808 and `-0`; same rejection rules except an optional minus. + +No number precision is lost: numbers beyond 64-bit range remain valid JSON tokens but fail the +integer helpers. There is no implicit float conversion or arbitrary exponent computation. + +## Encoding API + +Every writer returns the next output offset, or `jsonbad` (65,537). That sentinel is sticky through +further writer calls. No writer terminates output with a NUL. Capacity is checked before access; +an error can leave a partial prefix, which must not be sent. Writer helpers do not maintain a JSON +syntax state: punctuation/field sequencing is the caller's responsibility. + +- `jsonbyte(out edit uchar 65536, pos ulong, byte uchar) -> ulong` +- `jsonraw(out, pos, src view uchar 65536, n ulong) -> ulong` +- `jsonspan(out, pos, src, off ulong, n ulong) -> ulong` +- `jsonstr(out, pos, src, n ulong) -> ulong`: encode a JSON string, including quotes. +- `jsonquote(out, pos, src, off ulong, n ulong) -> ulong`: same, for an arena span without a copy. +- `jsonu64(out, pos, value ulong) -> ulong` +- `jsoni64(out, pos, value long) -> ulong` +- `jsonencode(tok view ulong 32768, dec view uchar 65536, out edit uchar 65536) -> ulong`: + compactly encode the parsed tree. Retains member order and number spelling. This is not a + canonicalization scheme. Output can exceed the input size and fail explicitly. + +String output matches Go `json.Marshal(string)`: standard short control escapes, lowercase `\u` +hex, HTML escapes for `<`, `>` and `&`, and escapes for U+2028/U+2029. Invalid UTF-8 becomes +`\ufffd`; a valid U+FFFD scalar remains literal UTF-8, matching Go. Internal helpers all have the +`json` prefix; callers should use the APIs above. + +## Focused tests + +```sh +GO=/path/to/go1.26.8/bin/go sh om/json/test/run.sh +# Or pass the compiler already verified by tools/omc.sh: +GO=/path/to/go1.26.8/bin/go sh om/json/test/run.sh /path/to/pinned/omc +``` + +The suite builds with the repository-pinned Omega compiler. Go is a **test oracle only** and is +required for this suite; the module pins `tailscale.com v1.102.0`. Deterministic generated cases +compare complete token metadata/decoded data (a 64-bit rolling fingerprint), exact output bytes, +accept/reject behavior and exact signed/unsigned integer results with Go `encoding/json`. The +oracle uses `Decoder.UseNumber`, independently walks the token stream, and applies only the +explicit resource bounds and duplicate-key policy above. + +Coverage includes all eight actual `tailcfg` request types, their responses, map `TKAInfo`, NodeID +values above 2^53 and at the signed limit, nil/empty byte values, arrays, maps, case-insensitive +field decoding, escaped field names, ignored unknown fields, all 256 byte values, malformed and +boundary UTF-8, surrogate pairs, exact integer limits, malformed grammar, and message/token/depth/ +member/writer bounds. Tests explicitly distinguish valid generic JSON from a typed tailcfg rejection. +The driver also checks lookup, token copying, offset/length boundaries and sticky writer errors. +`test/vectors.json` supplies independently authored committed golden cases. Generated Go records +and compiled test artifacts live in `build/test/json`, not the production unit. +The member boundary includes 256 accepted and 257 rejected members, both at root and nested. +A measured smoke sends ten full 65,536-byte messages, each with 256 distinct 250-byte keys sharing +a 247-byte prefix. It prints actual wall time for parsing, token hashing and encoding together, +including process startup and pipe I/O; this is not an isolated parser benchmark or a latency SLA. + +Six mutants must finish the entire differential run normally and produce at least one wrong +answer: duplicate acceptance, wrong surrogate replacement, depth and member off-by-ones, integer +bound, and HTML escaping. A separate trapping mutant must be classified as abnormal, not counted as a +successful detection. A short output, compiler failure, process signal, trap or timeout fails. +These are host-only tests and make no stock-client deployment claim. + +## Third-party material and notices + +No upstream implementation or vector text is copied or translated into this unit. Tests import +the upstream Go packages through their pinned modules, which retain their own licenses. The +vectors are independently authored. Format references: + +- [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259), especially sections 6 and 7. +- [Go encoding/json](https://pkg.go.dev/encoding/json). +- [Pinned tailcfg TKA types](https://github.com/tailscale/tailscale/blob/v1.102.0/tailcfg/tka.go). + +References checked against the local pinned sources on 2026-10-25. diff --git a/om/json/json.om b/om/json/json.om new file mode 100644 index 0000000..9812919 --- /dev/null +++ b/om/json/json.om @@ -0,0 +1,800 @@ +note SPDX-License-Identifier: Apache-2.0 +note Bounded JSON syntax, decoded tokens, exact integer conversion and output. +const jsonbad ulong 65537 + +fn jsonbyte o edit uchar 65536 p ulong b uchar to ulong +if ge p 65536 +ret jsonbad +end +put o p b +ret add p 1 +end + +fn jsonraw o edit uchar 65536 p ulong s view uchar 65536 n ulong to ulong +if or gt p 65536 gt n 65536 +ret jsonbad +end +if gt n sub ulong 65536 p +ret jsonbad +end +for i ulong n +put o add p i get s i +end +ret add p n +end + +fn jsonhex c ulong to ulong +if and ge c 48 le c 57 +ret sub c 48 +end +if and ge c 65 le c 70 +ret sub c 55 +end +if and ge c 97 le c 102 +ret sub c 87 +end +ret 16 +end + +fn jsonh4 s view uchar 65536 p ulong n ulong to ulong +if gt add p 4 n +ret 65536 +end +v = ulong 0 +for i ulong 4 +c = jsonhex ulong get s add p i +if eq c 16 +ret 65536 +end +v = add mul v 16 c +end +ret v +end + +note Decode one UTF8 scalar. Bad sequences consume one byte, matching Go. +fn jsonutf s view uchar 65536 p ulong n ulong r edit ulong 2 to void +put r 0 65533 +put r 1 1 +c = ulong get s p +if lt c 128 +put r 0 c +ret +end +w = ulong 0 +v = ulong 0 +if and ge c 194 le c 223 +w = 2 +v = and c 31 +end +if and ge c 224 le c 239 +w = 3 +v = and c 15 +end +if and ge c 240 le c 244 +w = 4 +v = and c 7 +end +if or eq w 0 gt add p w n +ret +end +i = ulong 1 +while lt i w bound 4 +c = ulong get s add p i +if or lt c 128 gt c 191 +ret +end +v = add mul v 64 and c 63 +i = add i 1 +end +if and eq w 3 lt v 2048 +ret +end +if and eq w 4 lt v 65536 +ret +end +if or gt v 1114111 and ge v 55296 le v 57343 +ret +end +put r 0 v +put r 1 w +end + +fn jsonrune o edit uchar 65536 p ulong v ulong to ulong +if lt v 128 +ret jsonbyte o p uchar v +end +if lt v 2048 +p = jsonbyte o p uchar add ulong 192 shr v 6 +else +if lt v 65536 +p = jsonbyte o p uchar add ulong 224 shr v 12 +else +p = jsonbyte o p uchar add ulong 240 shr v 18 +p = jsonbyte o p uchar add ulong 128 and shr v 12 63 +end +p = jsonbyte o p uchar add ulong 128 and shr v 6 63 +end +ret jsonbyte o p uchar add ulong 128 and v 63 +end + +note State: input length, cursor, decoded length, token count, parent, depth. +fn jsonesc s view uchar 65536 st edit ulong 8 to ulong +p = get st 1 +n = get st 0 +if ge p n +ret 1114112 +end +c = ulong get s p +put st 1 add p 1 +if or eq c 34 or eq c 47 eq c 92 +ret c +end +if eq c 98 +ret 8 +end +if eq c 102 +ret 12 +end +if eq c 110 +ret 10 +end +if eq c 114 +ret 13 +end +if eq c 116 +ret 9 +end +if ne c 117 +ret 1114112 +end +p = add p 1 +c = jsonh4 s p n +if eq c 65536 +ret 1114112 +end +p = add p 4 +put st 1 p +if and ge c 55296 le c 56319 +if le add p 6 n +if and eq get s p 92 eq get s add p 1 117 +v = jsonh4 s add p 2 n +if and ge v 56320 le v 57343 +put st 1 add p 6 +ret add ulong 65536 add mul sub c 55296 1024 sub v 56320 +end +end +end +end +if and ge c 55296 le c 57343 +ret 65533 +end +ret c +end + +fn jsonstring s view uchar 65536 st edit ulong 8 d edit uchar 65536 to int +r = new ulong 2 0 +put st 1 add get st 1 1 +while lt get st 1 get st 0 bound 65536 +p = get st 1 +c = ulong get s p +put st 1 add p 1 +if eq c 34 +ret 0 +end +if lt c 32 +ret 1 +end +if eq c 92 +c = jsonesc s st +if gt c 1114111 +ret 1 +end +else +if ge c 128 +jsonutf s p get st 0 r +c = get r 0 +put st 1 add p get r 1 +end +end +p = jsonrune d get st 2 c +if eq p jsonbad +ret 2 +end +put st 2 p +end +ret 1 +end + +fn jsondigit c uchar to bool +ret and ge c 48 le c 57 +end + +fn jsonnumber s view uchar 65536 st edit ulong 8 d edit uchar 65536 to int +p = get st 1 +beg = p +n = get st 0 +if eq get s p 45 +p = add p 1 +end +if ge p n +ret 1 +end +if eq get s p 48 +p = add p 1 +else +if not jsondigit get s p +ret 1 +end +while lt p n bound 65536 +if not jsondigit get s p +break +end +p = add p 1 +end +end +if lt p n +if eq get s p 46 +p = add p 1 +begd = p +while lt p n bound 65536 +if not jsondigit get s p +break +end +p = add p 1 +end +if eq p begd +ret 1 +end +end +end +if lt p n +if or eq get s p 101 eq get s p 69 +p = add p 1 +if lt p n +if or eq get s p 43 eq get s p 45 +p = add p 1 +end +end +begd = p +while lt p n bound 65536 +if not jsondigit get s p +break +end +p = add p 1 +end +if eq p begd +ret 1 +end +end +end +cnt = sub p beg +if gt cnt sub ulong 65536 get st 2 +ret 2 +end +for i ulong cnt +put d add get st 2 i get s add beg i +end +put st 2 add get st 2 cnt +put st 1 p +ret 0 +end + +fn jsonoctet v ulong i ulong to uchar +ret uchar and shr v mul i 8 255 +end + +fn jsonliteral s view uchar 65536 st edit ulong 8 kind ulong to int +p = get st 1 +n = ulong 4 +v = ulong 1702195828 +if eq kind 6 +n = 5 +v = 435728179558 +end +if eq kind 7 +v = 1819047278 +end +if gt add p n get st 0 +ret 1 +end +for i ulong n +if ne get s add p i jsonoctet v i +ret 1 +end +end +put st 1 add p n +ret 0 +end + +fn jsonequal d view uchar 65536 a ulong b ulong n ulong to bool +for i ulong n +if ne get d add a i get d add b i +ret false +end +end +ret true +end + +fn jsonkeyeq t view ulong 32768 d view uchar 65536 a ulong b ulong to bool +if ne get t add a 2 get t add b 2 +ret false +end +ret jsonequal d get t add a 1 get t add b 1 get t add b 2 +end + +fn jsondupe t view ulong 32768 d view uchar 65536 id ulong to bool +b = mul id 8 +par = get t add b 4 +i = add par 1 +while lt i id bound 4096 +a = mul i 8 +if eq get t add a 6 1 +if jsonkeyeq t d a b +ret true +end +end +i = get t add a 3 +end +ret false +end + +fn jsonfinish t edit ulong 32768 st view ulong 8 b ulong to void +put t add b 2 sub get st 2 get t add b 1 +end + +fn jsonvalue s view uchar 65536 st edit ulong 8 t edit ulong 32768 d edit uchar 65536 key ulong to int +if ge get st 3 4095 +ret 3 +end +id = add get st 3 1 +put st 3 id +b = mul id 8 +for i ulong 8 +put t add b i 0 +end +put t b 4 +put t add b 1 get st 2 +put t add b 3 add id 1 +put t add b 4 get st 4 +put t add b 6 key +c = get s get st 1 +if or eq c 123 eq c 91 +if ge get st 5 32 +ret 4 +end +put t b 1 +if eq c 91 +put t b 2 +end +put st 4 id +put st 5 add get st 5 1 +put st 1 add get st 1 1 +ret 0 +end +e = int 0 +if eq c 34 +put t b 3 +e = jsonstring s st d +else +if or eq c 116 or eq c 102 eq c 110 +put t b 5 +if eq c 102 +put t b 6 +end +if eq c 110 +put t b 7 +end +e = jsonliteral s st get t b +else +e = jsonnumber s st d +end +end +if ne e 0 +ret e +end +jsonfinish t st b +if eq key 1 +if jsondupe t d id +ret 5 +end +end +ret 0 +end + +fn jsonspace c uchar to bool +ret or eq c 32 or eq c 9 or eq c 10 eq c 13 +end + +note Container phase 0 initial, 1 separator, 2 after comma, 3 colon, 4 object value. +fn jsonstep s view uchar 65536 st edit ulong 8 t edit ulong 32768 d edit uchar 65536 to int +par = get st 4 +b = mul par 8 +phase = get t add b 7 +c = get s get st 1 +obj = eq get t b 1 +if or eq phase 0 eq phase 1 +if or and obj eq c 125 and not obj eq c 93 +put t add b 3 add get st 3 1 +put st 4 get t add b 4 +put st 5 sub get st 5 1 +put st 1 add get st 1 1 +ret 0 +end +end +if eq phase 1 +if ne c 44 +ret 1 +end +put t add b 7 2 +put st 1 add get st 1 1 +ret 0 +end +if eq phase 3 +if ne c 58 +ret 1 +end +put t add b 7 4 +put st 1 add get st 1 1 +ret 0 +end +key = ulong 0 +put t add b 7 1 +if and obj ne phase 4 +if ne c 34 +ret 1 +end +if ge get t add b 5 512 +ret 6 +end +key = 1 +put t add b 7 3 +end +put t add b 5 add get t add b 5 1 +ret jsonvalue s st t d key +end + +fn jsonparse s view uchar 65536 n ulong t edit ulong 32768 d edit uchar 65536 to int +put t 0 0 +if or eq n 0 gt n 65536 +ret 2 +end +st = new ulong 8 0 +put st 0 n +e = int 0 +while lt get st 1 n bound 65536 +if jsonspace get s get st 1 +put st 1 add get st 1 1 +else +if eq get st 4 0 +if ne get st 3 0 +ret 1 +end +e = jsonvalue s st t d 0 +else +e = jsonstep s st t d +end +if ne e 0 +ret e +end +end +end +if or ne get st 4 0 eq get st 3 0 +ret 1 +end +put t 0 get st 3 +ret 0 +end + +fn jsonuint d view uchar 65536 off ulong n ulong r edit ulong 1 to int +put r 0 0 +if or gt off 65536 or eq n 0 gt n 20 +ret 1 +end +if gt n sub ulong 65536 off +ret 1 +end +if and gt n 1 eq get d off 48 +ret 1 +end +v = ulong 0 +for i ulong n +c = ulong get d add off i +if or lt c 48 gt c 57 +ret 1 +end +c = sub c 48 +if gt v div sub ulong 18446744073709551615 c 10 +ret 1 +end +v = add mul v 10 c +end +put r 0 v +ret 0 +end + +fn jsonint d view uchar 65536 off ulong n ulong r edit long 1 to int +put r 0 0 +if or ge off 65536 eq n 0 +ret 1 +end +negv = eq get d off 45 +if negv +off = add off 1 +n = sub n 1 +end +v = new ulong 1 0 +if ne jsonuint d off n v 0 +ret 1 +end +x = get v 0 +if negv +if gt x 9223372036854775808 +ret 1 +end +if eq x 9223372036854775808 +put r 0 -9223372036854775808 +ret 0 +end +put r 0 neg long x +else +if gt x 9223372036854775807 +ret 1 +end +put r 0 long x +end +ret 0 +end + +fn jsoncopy t view ulong 32768 d view uchar 65536 id ulong o edit uchar 65536 to ulong +if or eq id 0 gt id get t 0 +ret jsonbad +end +b = mul id 8 +n = get t add b 2 +for i ulong n +put o i get d add get t add b 1 i +end +ret n +end + +fn jsonname d view uchar 65536 off ulong key view uchar 65536 n ulong to bool +for j ulong n +if ne get key j get d add off j +ret false +end +end +ret true +end + +fn jsonfind t view ulong 32768 d view uchar 65536 obj ulong key view uchar 65536 n ulong to ulong +if or eq obj 0 gt obj get t 0 +ret 0 +end +if or ne get t mul obj 8 1 gt n 65536 +ret 0 +end +i = add obj 1 +while lt i get t add mul obj 8 3 bound 4096 +b = mul i 8 +if eq n get t add b 2 +if jsonname d get t add b 1 key n +ret add i 1 +end +end +i = get t add mul add i 1 8 3 +end +ret 0 +end + +fn jsonhc v ulong to uchar +if lt v 10 +ret uchar add v 48 +end +ret uchar add v 87 +end + +fn jsonuesc o edit uchar 65536 p ulong v ulong to ulong +p = jsonbyte o p 92 +p = jsonbyte o p 117 +p = jsonbyte o p jsonhc and shr v 12 15 +p = jsonbyte o p jsonhc and shr v 8 15 +p = jsonbyte o p jsonhc and shr v 4 15 +ret jsonbyte o p jsonhc and v 15 +end + +fn jsonneeds v ulong to bool +ret or lt v 32 or eq v 60 or eq v 62 or eq v 38 or eq v 8232 eq v 8233 +end + +fn jsonquote o edit uchar 65536 p ulong s view uchar 65536 off ulong n ulong to ulong +if or gt n 65536 gt off 65536 +ret jsonbad +end +if gt n sub ulong 65536 off +ret jsonbad +end +n = add off n +p = jsonbyte o p 34 +i = off +r = new ulong 2 0 +while lt i n bound 65536 +jsonutf s i n r +v = get r 0 +i = add i get r 1 +if or eq v 34 eq v 92 +p = jsonbyte o p 92 +p = jsonbyte o p uchar v +else +if jsonneeds v +c = ulong 0 +if eq v 8 +c = 98 +end +if eq v 9 +c = 116 +end +if eq v 10 +c = 110 +end +if eq v 12 +c = 102 +end +if eq v 13 +c = 114 +end +if ne c 0 +p = jsonbyte o p 92 +p = jsonbyte o p uchar c +else +p = jsonuesc o p v +end +else +if and eq v 65533 eq get r 1 1 +p = jsonuesc o p v +else +p = jsonrune o p v +end +end +end +if eq p jsonbad +ret jsonbad +end +end +ret jsonbyte o p 34 +end + +fn jsonstr o edit uchar 65536 p ulong s view uchar 65536 n ulong to ulong +ret jsonquote o p s 0 n +end + +fn jsonu64 o edit uchar 65536 p ulong v ulong to ulong +buf = new uchar 20 0 +n = ulong 0 +while ne v 0 bound 20 +put buf n uchar add rem v 10 48 +n = add n 1 +v = div v 10 +end +if eq n 0 +ret jsonbyte o p 48 +end +while gt n 0 bound 20 +n = sub n 1 +p = jsonbyte o p get buf n +end +ret p +end + +fn jsoni64 o edit uchar 65536 p ulong v long to ulong +if ge v 0 +ret jsonu64 o p ulong v +end +p = jsonbyte o p 45 +if eq v -9223372036854775808 +ret jsonu64 o p 9223372036854775808 +end +ret jsonu64 o p ulong neg v +end + +fn jsonspan o edit uchar 65536 p ulong s view uchar 65536 off ulong n ulong to ulong +if or gt off 65536 gt n 65536 +ret jsonbad +end +if gt n sub ulong 65536 off +ret jsonbad +end +if gt p 65536 +ret jsonbad +end +if gt n sub ulong 65536 p +ret jsonbad +end +for i ulong n +put o add p i get s add off i +end +ret add p n +end + +fn jsonword o edit uchar 65536 p ulong v ulong n ulong to ulong +for i ulong n +p = jsonbyte o p uchar and shr v mul i 8 255 +end +ret p +end + +fn jsonatom t view ulong 32768 d view uchar 65536 id ulong o edit uchar 65536 p ulong to ulong +b = mul id 8 +k = get t b +if eq k 1 +ret jsonbyte o p 123 +end +if eq k 2 +ret jsonbyte o p 91 +end +if eq k 3 +ret jsonquote o p d get t add b 1 get t add b 2 +end +if eq k 4 +ret jsonspan o p d get t add b 1 get t add b 2 +end +if eq k 5 +ret jsonword o p 1702195828 4 +end +if eq k 6 +ret jsonword o p 435728179558 5 +end +ret jsonword o p 1819047278 4 +end + +fn jsoncomma t view ulong 32768 b ulong par ulong to bool +ret or eq get t mul par 8 2 eq get t add b 6 1 +end + +note Token table must be from a successful parse and unmodified. +fn jsonencode t view ulong 32768 d view uchar 65536 o edit uchar 65536 to ulong +if or eq get t 0 0 gt get t 0 4095 +ret jsonbad +end +p = ulong 0 +cur = ulong 0 +id = ulong 1 +while le id get t 0 bound 4095 +b = mul id 8 +par = get t add b 4 +while ne cur par bound 32 +c = uchar 125 +if eq get t mul cur 8 2 +c = 93 +end +p = jsonbyte o p c +cur = get t add mul cur 8 4 +end +if ne par 0 +if gt id add par 1 +if jsoncomma t b par +p = jsonbyte o p 44 +end +end +end +p = jsonatom t d id o p +if eq get t add b 6 1 +p = jsonbyte o p 58 +end +if le get t b 2 +cur = id +end +if eq p jsonbad +ret jsonbad +end +id = add id 1 +end +while ne cur 0 bound 32 +c = uchar 125 +if eq get t mul cur 8 2 +c = 93 +end +p = jsonbyte o p c +cur = get t add mul cur 8 4 +end +ret p +end diff --git a/om/json/test/driver.om b/om/json/test/driver.om new file mode 100644 index 0000000..d5496f9 --- /dev/null +++ b/om/json/test/driver.om @@ -0,0 +1,250 @@ +note SPDX-License-Identifier: Apache-2.0 +note Test-only line protocol: mode P parse, Q quote, U unsigned, I signed, followed by hex. +global jib uchar 65536 +global jis ulong 2 + +fn jtgetc to int +if eq get jis 0 get jis 1 +n = read 0 jib 0 65536 +if le n 0 +ret -1 +end +put jis 0 0 +put jis 1 ulong n +end +p = get jis 0 +put jis 0 add p 1 +ret int get jib p +end + +fn jtline a edit uchar 65536 to long +n = ulong 0 +while true bound 65537 +c = jtgetc +if eq c 10 +ret long n +end +if or lt c 0 ge n 65536 +ret -1 +end +h = jsonhex ulong c +c = jtgetc +if lt c 0 +ret -1 +end +l = jsonhex ulong c +if or eq h 16 eq l 16 +ret -1 +end +put a n uchar add mul h 16 l +n = add n 1 +end +ret -1 +end + +fn jtwrite a view uchar 65536 n ulong to void +p = ulong 0 +while lt p n bound 65536 +r = write 1 a p sub n p +if le r 0 +exit 2 +end +p = add p ulong r +end +end + +fn jtbyte c uchar to void +a = new uchar 65536 0 +put a 0 c +jtwrite a 1 +end + +fn jtdec v ulong to void +a = new uchar 65536 0 +n = jsonu64 a 0 v +jtwrite a n +end + +fn jthex a view uchar 65536 n ulong to void +b = new uchar 65536 0 +p = ulong 0 +for i ulong n +v = ulong get a i +put b p jsonhc shr v 4 +put b add p 1 jsonhc and v 15 +p = add p 2 +if eq p 65536 +jtwrite b p +p = 0 +end +end +jtwrite b p +end + +fn jthbytes d view uchar 65536 off ulong n ulong h ulong to ulong +for j ulong n +h = mul xor h ulong get d add off j 1099511628211 +end +ret h +end + +fn jthash t view ulong 32768 d view uchar 65536 to ulong +h = ulong 14695981039346656037 +id = ulong 1 +while le id get t 0 bound 4095 +b = mul id 8 +for j ulong 7 +h = mul xor h get t add b j 1099511628211 +end +h = jthbytes d get t add b 1 get t add b 2 h +id = add id 1 +end +ret h +end + +fn jtparse a view uchar 65536 n ulong to void +t = new ulong 32768 0 +d = new uchar 65536 0 +o = new uchar 65536 0 +if ne jsonparse a n t d 0 +jtbyte 69 +ret +end +jtbyte 79 +jtbyte 32 +jtdec jthash t d +jtbyte 32 +n = jsonencode t d o +if eq n jsonbad +jtbyte 33 +else +jthex o n +end +end + +fn jtinteger a view uchar 65536 n ulong mode int to void +u = new ulong 1 0 +s = new long 1 0 +o = new uchar 65536 0 +if eq mode 85 +if ne jsonuint a 0 n u 0 +jtbyte 69 +ret +end +n = jsonu64 o 0 get u 0 +else +if ne jsonint a 0 n s 0 +jtbyte 69 +ret +end +n = jsoni64 o 0 get s 0 +end +jtbyte 79 +jtbyte 32 +jtwrite o n +end + +fn jtbound to int +a = new uchar 65536 97 +o = new uchar 65536 0 +t = new ulong 32768 0 +u = new ulong 1 0 +s = new long 1 0 +if ne jsonparse a 65537 t o 2 +ret 1 +end +if ne jsonbyte o 65536 97 jsonbad +ret 2 +end +if ne jsonraw o 65535 a 2 jsonbad +ret 3 +end +if ne jsonstr o 0 a 65535 jsonbad +ret 4 +end +if ne jsonquote o 0 a 65536 1 jsonbad +ret 5 +end +if ne jsonuint a 65536 1 u 1 +ret 6 +end +if ne jsonint a 65536 1 s 1 +ret 7 +end +if ne jsonu64 o 65536 0 jsonbad +ret 8 +end +if ne jsoni64 o 65535 -1 jsonbad +ret 9 +end +if ne jsonraw o 65536 a 0 65536 +ret 10 +end +if ne jsonstr o 0 a 65534 65536 +ret 11 +end +put a 0 123 +put a 1 34 +put a 2 120 +put a 3 34 +put a 4 58 +put a 5 49 +put a 6 125 +if ne jsonparse a 7 t o 0 +ret 12 +end +put a 0 120 +if ne jsonfind t o 1 a 1 3 +ret 13 +end +if ne jsoncopy t o 3 a 1 +ret 14 +end +if ne get a 0 49 +ret 15 +end +if ne jsoncopy t o 0 a jsonbad +ret 16 +end +ret 0 +end + +fn main to int +if ne jtbound 0 +ret 3 +end +a = new uchar 65536 0 +o = new uchar 65536 0 +while true bound 999999 +mode = jtgetc +if eq mode -1 +ret 0 +end +n = jtline a +if lt n 0 +ret 2 +end +if eq mode 80 +jtparse a ulong n +else +if eq mode 81 +p = jsonstr o 0 a ulong n +if eq p jsonbad +jtbyte 69 +else +jtbyte 79 +jtbyte 32 +jthex o p +end +else +if or eq mode 85 eq mode 73 +jtinteger a ulong n mode +else +ret 2 +end +end +end +jtbyte 10 +end +ret 0 +end diff --git a/om/json/test/oracle/go.mod b/om/json/test/oracle/go.mod new file mode 100644 index 0000000..bf009ef --- /dev/null +++ b/om/json/test/oracle/go.mod @@ -0,0 +1,12 @@ +module omnet/json-oracle + +go 1.26.5 + +require tailscale.com v1.102.0 + +require ( + github.com/go-json-experiment/json v0.0.0-20260214004413-d219187c3433 // indirect + go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect + golang.org/x/crypto v0.54.0 // indirect + golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect +) diff --git a/om/json/test/oracle/go.sum b/om/json/test/oracle/go.sum new file mode 100644 index 0000000..598cb4b --- /dev/null +++ b/om/json/test/oracle/go.sum @@ -0,0 +1,10 @@ +github.com/go-json-experiment/json v0.0.0-20260214004413-d219187c3433 h1:vymEbVwYFP/L05h5TKQxvkXoKxNvTpjxYKdF1Nlwuao= +github.com/go-json-experiment/json v0.0.0-20260214004413-d219187c3433/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg= +go4.org/mem v0.0.0-20240501181205-ae6ca9944745 h1:Tl++JLUCe4sxGu8cTpDzRLd3tN7US4hOxG5YpKCzkek= +go4.org/mem v0.0.0-20240501181205-ae6ca9944745/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g= +golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= +golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= +tailscale.com v1.102.0 h1:yAYrykMZWlgp7Qq2ECDrDnxeySWBhNXNMkXdDmVMyrE= +tailscale.com v1.102.0/go.mod h1:NdndXfkSklVPbRUZMAzzRuDNaR5B+YWGbAyE1HpSQZg= diff --git a/om/json/test/oracle/main.go b/om/json/test/oracle/main.go new file mode 100644 index 0000000..5b1eb0f --- /dev/null +++ b/om/json/test/oracle/main.go @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: Apache-2.0 +// Test-only oracle: encoding/json and actual tailscale.com v1.102.0 tailcfg types. +package main + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "math/rand/v2" + "os" + "regexp" + "strconv" + "strings" + "tailscale.com/tailcfg" +) + +type token struct { fields [7]uint64; data []byte } +type parser struct { dec *json.Decoder; tok []token; used int } +func (p *parser) value(parent, key uint64, depth int) error { + if len(p.tok) == 4095 { return fmt.Errorf("tokens") } + v, err := p.dec.Token(); if err != nil { return err } + id := len(p.tok)+1 + t := token{fields:[7]uint64{0,uint64(p.used),0,uint64(id+1),parent,0,key}} + switch x:=v.(type) { + case json.Delim: + if x!='{' && x!='[' { return fmt.Errorf("delimiter") } + if depth == 32 { return fmt.Errorf("depth") } + t.fields[0]=1; if x=='[' {t.fields[0]=2} + p.tok=append(p.tok,t) + seen:=map[string]bool{} + for p.dec.More() { + if x=='{' { + if len(seen)==256{return fmt.Errorf("members")} + k,err:=p.dec.Token(); if err!=nil{return err}; s,ok:=k.(string); if !ok{return fmt.Errorf("key")} + if seen[s] {return fmt.Errorf("duplicate")}; seen[s]=true + if len(p.tok)==4095{return fmt.Errorf("tokens")} + kid:=len(p.tok)+1 + p.tok=append(p.tok,token{[7]uint64{3,uint64(p.used),uint64(len(s)),uint64(kid+1),uint64(id),0,1},[]byte(s)}) + p.used+=len(s); if p.used>65536{return fmt.Errorf("bytes")} + p.tok[id-1].fields[5]++ + } + if err:=p.value(uint64(id),0,depth+1);err!=nil{return err} + p.tok[id-1].fields[5]++ + } + close,err:=p.dec.Token(); if err!=nil{return err} + want:=json.Delim('}'); if x=='['{want=']'}; if close!=want{return fmt.Errorf("close")} + p.tok[id-1].fields[3]=uint64(len(p.tok)+1) + return nil + case string: t.fields[0]=3; t.data=[]byte(x) + case json.Number: t.fields[0]=4; t.data=[]byte(x.String()) + case bool: t.fields[0]=6; if x {t.fields[0]=5} + case nil: t.fields[0]=7 + default: return fmt.Errorf("unexpected token") + } + t.fields[2]=uint64(len(t.data)); p.used+=len(t.data) + if p.used>65536{return fmt.Errorf("bytes")} + p.tok=append(p.tok,t) + return nil +} +func (p *parser) encoded(id int) []byte { + t:=p.tok[id-1] + switch t.fields[0] { + case 1,2: + obj:=t.fields[0]==1; var b bytes.Buffer + if obj {b.WriteByte('{')} else {b.WriteByte('[')} + i:=id+1 + for i<int(t.fields[3]) { + if i>id+1 {b.WriteByte(',')} + if obj {s,_:=json.Marshal(string(p.tok[i-1].data));b.Write(s);b.WriteByte(':');i++} + b.Write(p.encoded(i));i=int(p.tok[i-1].fields[3]) + } + if obj {b.WriteByte('}')} else {b.WriteByte(']')};return b.Bytes() + case 3: b,_:=json.Marshal(string(t.data));return b + case 4:return t.data + case 5:return []byte("true") + case 6:return []byte("false") + default:return []byte("null") + } +} +var uintRE=regexp.MustCompile(`^(0|[1-9][0-9]*)$`) +var intRE=regexp.MustCompile(`^-?(0|[1-9][0-9]*)$`) +func expected(mode string, raw []byte) string { + switch mode { + case "P": + if len(raw)==0 || len(raw)>65536{return "E"} + p:=parser{dec:json.NewDecoder(bytes.NewReader(raw))};p.dec.UseNumber() + if p.value(0,0,0)!=nil{return "E"} + if _,e:=p.dec.Token();e!=io.EOF{return "E"} + h:=uint64(14695981039346656037) + for _,t:=range p.tok {for _,v:=range t.fields{h=(h^v)*1099511628211};for _,v:=range t.data{h=(h^uint64(v))*1099511628211}} + b:=p.encoded(1);encoded:=hex.EncodeToString(b);if len(b)>65536{encoded="!"} + return fmt.Sprintf("O %d %s",h,encoded) + case "Q": + b,_:=json.Marshal(string(raw));if len(b)>65536{return "E"};return "O "+hex.EncodeToString(b) + case "U": + if !uintRE.Match(raw){return "E"};var v uint64;if json.Unmarshal(raw,&v)!=nil{return "E"};return "O "+strconv.FormatUint(v,10) + case "I": + if !intRE.Match(raw){return "E"};var v int64;if json.Unmarshal(raw,&v)!=nil{return "E"};return "O "+strconv.FormatInt(v,10) + } + panic(mode) +} +type row struct { Class string `json:"class"`; Mode string `json:"mode"`; Hex string `json:"hex"`; Want string `json:"want"` } +var enc=json.NewEncoder(os.Stdout) +func emit(class,mode string,raw []byte){if len(raw)>65536{panic("oversized driver record")};if err:=enc.Encode(row{class,mode,hex.EncodeToString(raw),expected(mode,raw)});err!=nil{panic(err)}} +func typed(name,raw string,v any){if err:=json.Unmarshal([]byte(raw),v);err!=nil{panic(fmt.Sprintf("%s: %v",name,err))};emit("tailcfg-"+name,"P",[]byte(raw));b,e:=json.Marshal(v);if e!=nil{panic(e)};emit("tailcfg-"+name+"-marshal","P",b)} +func tailcfgCases(){ + nk:="nodekey:"+strings.Repeat("01",32) + base:=`"Version":106,"NodeKey":"`+nk+`"` + typed("init-begin",`{`+base+`,"GenesisAUM":"AAECA/8="}`,&tailcfg.TKAInitBeginRequest{}) + typed("init-finish",`{`+base+`,"Signatures":{"9007199254740993":"AAE=","9223372036854775807":null},"SupportDisablement":""}`,&tailcfg.TKAInitFinishRequest{}) + typed("bootstrap",`{`+base+`,"Head":""}`,&tailcfg.TKABootstrapRequest{}) + typed("sync-offer",`{`+base+`,"Head":"A","Ancestors":["B","C"]}`,&tailcfg.TKASyncOfferRequest{}) + typed("sync-send",`{`+base+`,"Head":"A","MissingAUMs":["AAE=",null,""],"Interactive":true}`,&tailcfg.TKASyncSendRequest{}) + typed("disable",`{`+base+`,"Head":"A","DisablementSecret":"AAE="}`,&tailcfg.TKADisableRequest{}) + typed("sign",`{`+base+`,"Signature":"AAE="}`,&tailcfg.TKASubmitSignatureRequest{}) + typed("affected",`{`+base+`,"KeyID":"AAE="}`,&tailcfg.TKASignaturesUsingKeyRequest{}) + typed("begin-response",`{"NeedSignatures":[{"NodeID":9007199254740993,"NodePublic":"`+nk+`","RotationPubkey":"AAE="}]}`,&tailcfg.TKAInitBeginResponse{}) + typed("bootstrap-response",`{"GenesisAUM":"AAE=","DisablementSecret":"AAE="}`,&tailcfg.TKABootstrapResponse{}) + typed("offer-response",`{"Head":"A","Ancestors":["B"],"MissingAUMs":["AAE=",null,""]}`,&tailcfg.TKASyncOfferResponse{}) + typed("send-response",`{"Head":"A"}`,&tailcfg.TKASyncSendResponse{}) + typed("affected-response",`{"Signatures":["AAE=",null,""]}`,&tailcfg.TKASignaturesUsingKeyResponse{}) + typed("finish-response",`{}`,&tailcfg.TKAInitFinishResponse{}) + typed("disable-response",`{}`,&tailcfg.TKADisableResponse{}) + typed("sign-response",`{}`,&tailcfg.TKASubmitSignatureResponse{}) + typed("map-info",`{"Head":"A","Disabled":true}`,&tailcfg.TKAInfo{}) + typed("case-insensitive",`{"vErSiOn":106,"nodekey":"`+nk+`","GenesisAUM":null}`,&tailcfg.TKAInitBeginRequest{}) + typed("byte-array",`{`+base+`,"GenesisAUM":[0,1,2,255]}`,&tailcfg.TKAInitBeginRequest{}) + typed("null-optionals",`{"Version":null,"NodeKey":null,"Head":null,"Ancestors":null}`,&tailcfg.TKASyncOfferRequest{}) + typed("escaped-key",`{"\u0056ersion":106,"NodeKey":"`+nk+`","GenesisAUM":"AA\nE="}`,&tailcfg.TKAInitBeginRequest{}) + typed("unknown-field",`{`+base+`,"GenesisAUM":"","Future":{"x":[1,true,null]}}`,&tailcfg.TKAInitBeginRequest{}) + for _,field:=range []string{`"Version":1.0`,`"Version":9223372036854775808`,`"GenesisAUM":true`,`"GenesisAUM":"?"`,`"GenesisAUM":[256]`,`"NodeKey":"bad"`} { + raw:=[]byte(`{`+field+`}`);var v tailcfg.TKAInitBeginRequest + if json.Unmarshal(raw,&v)==nil{panic("expected typed rejection")} + emit("tailcfg-syntax-not-schema","P",raw) + } +} +func randomBytes(r *rand.Rand, n int) []byte { b:=make([]byte,n);for i:=range b{b[i]=byte(r.Uint64())};return b } +func randomValue(r *rand.Rand, depth int) any { + k:=r.IntN(7);if depth==4{k=r.IntN(5)} + switch k { + case 0:return nil + case 1:return r.IntN(2)==1 + case 2:return json.Number(fmt.Sprintf("%d",r.Uint64())) + case 3:return json.Number(fmt.Sprintf("-%de-%d",r.IntN(100000),r.IntN(1000))) + case 4:return string(randomBytes(r,r.IntN(40))) + case 5:a:=make([]any,r.IntN(6));for i:=range a{a[i]=randomValue(r,depth+1)};return a + default:a:=map[string]any{};for i:=range r.IntN(6){a[fmt.Sprintf("key%d",i)]=randomValue(r,depth+1)};return a + } +} +func main(){ + tailcfgCases() + valid:=[]string{`null`,`true`,`false`,`0`,`-0`,`18446744073709551615`,`-9223372036854775808`,`9007199254740993`,`1.234567890123456789e+999999`,`[]`,`{}`,`{"a":[],"b":{},"c":[1,{"d":2}],"e":false}`,`"\"\\\/\b\f\n\r\t"`,`"\u0000\u001f\u007f"`,`"\ud800\udc00\udbff\udfff"`,`"\ud800x\udc00\ud800\ud800"`,`"\u2028\u2029<>&"`,`"\uD834\uDd1E"`,`{"A":1,"a":2}`," \r\n\t[1, 2]\n"} + for _,s:=range valid{emit("grammar","P",[]byte(s))} + invalid:=[]string{""," ","+1","01","-01","--1","1.",".1","1e","1e+","1e-","NaN","Infinity","truefalse","null null","[1,]","[,1]","[1 2]","{,}","{\"a\":}","{\"a\":1,}","{1:2}","{\"a\" 2}","{\"a\":1 \"b\":2}","\"\\x00\"","\"\\u12\"","\"\\uZZZZ\"","\"a\nb\"","\"","\"abc\\","[","{","\ufeff{}","\x00","[true,false,null}",`"\ud800\u12xx"`} + for _,s:=range invalid{emit("malformed","P",[]byte(s))} + for _,s:=range []string{`{"a":1,"a":2}`,`{"a":1,"\u0061":2}`,`{"x":{"a":1,"a":2}}`,`{"\ud800":0,"\udc00":1}`,`{"a":{},"a":[]}`} {emit("duplicate-policy","P",[]byte(s))} + for i:=range 256 {emit("byte-quote","Q",[]byte{byte(i)});emit("byte-string","P",[]byte{'"',byte(i),'"'})} + for _,b:=range [][]byte{{0xc0,0x80},{0xe0,0x80,0x80},{0xed,0xa0,0x80},{0xf4,0x90,0x80,0x80},{0xf0,0x80,0x80,0x80},{0xe2,0x82},{0xef,0xbf,0xbd},{0xf0,0x90,0x80,0x80},{0xf4,0x8f,0xbf,0xbf}} {emit("utf8","Q",b);emit("utf8","P",append(append([]byte{'"'},b...), '"'))} + for _,s:=range []string{"0","-0","1","-1","9007199254740993","18446744073709551615","18446744073709551616","9223372036854775807","9223372036854775808","-9223372036854775808","-9223372036854775809","","00","01","-01","+1","1e0","1.0"," 1","1 ","--1",strings.Repeat("9",65536)} {emit("integer","U",[]byte(s));emit("integer","I",[]byte(s))} + for _,n:=range []int{31,32,33}{emit("depth-bound","P",[]byte(strings.Repeat("[",n)+"0"+strings.Repeat("]",n)))} + for _,n:=range []int{4093,4094,4095}{emit("token-bound","P",[]byte("["+strings.Repeat("0,",n-1)+"0]"))} + for _,n:=range []int{255,256,257}{ + fields:=make([]string,n);for i:=range fields{fields[i]=fmt.Sprintf(`"key%03d":0`,i)} + obj:="{"+strings.Join(fields,",")+"}" + emit("member-bound","P",[]byte(obj)) + emit("nested-member-bound","P",[]byte(`{"nested":`+obj+`}`)) + } + fields:=make([]string,256);for i:=range fields{fields[i]=fmt.Sprintf(`"%s%03x":0`,strings.Repeat("a",247),i)} + worst:="{"+strings.Join(fields,",")+"}" + worst+=strings.Repeat(" ",65536-len(worst)) + emit("member-long-prefix","P",[]byte(worst)) + for _,n:=range []int{65533,65534}{emit("message-bound","P",[]byte(`"`+strings.Repeat("a",n)+`"`))} + emit("message-bound","P",[]byte(strings.Repeat(" ",65535)+"0")) + emit("message-bound","P",[]byte(strings.Repeat(" ",65536))) + for _,n:=range []int{21845,21846}{emit("decoded-bound","P",append(append([]byte{'"'},bytes.Repeat([]byte{255},n)...),'"'))} + emit("writer-bound","Q",bytes.Repeat([]byte{0},65536)) + emit("writer-bound","P",[]byte(`"`+strings.Repeat("<",12000)+`"`)) + r:=rand.New(rand.NewPCG(1020,2119)) + for range 2000 { + b,e:=json.Marshal(randomValue(r,0));if e!=nil{panic(e)};emit("random-valid","P",b) + if len(b)>0{c:=append([]byte(nil),b...);c[r.IntN(len(c))]=byte(r.IntN(256));emit("random-mutation","P",c)} + } + for range 1000{b:=randomBytes(r,r.IntN(100));emit("random-bytes","P",b);emit("random-quote","Q",b)} + for range 500{v:=r.Uint64();emit("random-integer","U",[]byte(strconv.FormatUint(v,10)));emit("random-integer","I",[]byte(strconv.FormatInt(int64(v),10)))} +} diff --git a/om/json/test/run.py b/om/json/test/run.py new file mode 100755 index 0000000..2b68298 --- /dev/null +++ b/om/json/test/run.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Focused host-only JSON checks; generated mutants live only in build/test/json.""" +import collections +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +OUT = ROOT / "build/test/json" +OUT.mkdir(parents=True, exist_ok=True) +OMC = Path(sys.argv[1]).resolve() +SOURCE = (HERE.parent / "json.om").read_text() +DRIVER = (HERE / "driver.om").read_text() + + +def build(source, name): + src = OUT / f"{name}.om" + src.write_text(source + "\n" + DRIVER) + binary = OUT / name + with src.open("rb") as inp, binary.open("wb") as out: + result = subprocess.run([str(OMC)], stdin=inp, stdout=out, stderr=subprocess.PIPE) + if result.returncode: + raise RuntimeError(f"{name}: omc exit {result.returncode}: {result.stderr.decode()}") + binary.chmod(0o755) + return binary + + +def execute(binary, data, expected): + result = subprocess.run([str(binary)], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120) + lines = result.stdout.decode("ascii").splitlines() + if result.returncode != 0 or len(lines) != len(expected): + return "abnormal", lines, result.returncode + return ("match" if lines == expected else "mismatch"), lines, 0 + + +go = os.environ.get("GO", "go") +subprocess.run([go, "build", "-mod=mod", "-o", str(OUT / "oracle"), "."], cwd=HERE / "oracle", check=True) +result = subprocess.run([str(OUT / "oracle")], stdout=subprocess.PIPE, check=True) +(OUT / "oracle.jsonl").write_bytes(result.stdout) +rows = [json.loads(line) for line in result.stdout.splitlines()] +data = "".join(row["mode"] + row["hex"] + "\n" for row in rows).encode() +expected = [row["want"] for row in rows] +binary = build(SOURCE, "driver") +status, lines, rc = execute(binary, data, expected) +if status != "match": + for i, (actual, want) in enumerate(zip(lines, expected)): + if actual != want: + print(f"json: mismatch {i} {rows[i]['class']} input={rows[i]['hex'][:160]} want={want[:160]} got={actual[:160]}") + if sum(a != b for a, b in zip(lines[:i+1], expected[:i+1])) >= 12: + break + raise SystemExit(f"json: FAIL {status} rc={rc} lines={len(lines)}/{len(expected)}") +for cls, count in sorted(collections.Counter(row["class"] for row in rows).items()): + print(f"json: {cls} {count}/{count} PASS") + +worst = [row for row in rows if row["class"] == "member-long-prefix"] +assert len(worst) == 1 and worst[0]["want"].startswith("O ") +assert len(bytes.fromhex(worst[0]["hex"])) == 65536 +smoke_runs = 10 +smoke_input = ((worst[0]["mode"] + worst[0]["hex"] + "\n") * smoke_runs).encode() +started = time.perf_counter() +status, _, rc = execute(binary, smoke_input, [worst[0]["want"]] * smoke_runs) +elapsed = time.perf_counter() - started +assert status == "match", (status, rc) +print(f"json: long-prefix smoke 256 distinct 250-byte keys, 65536-byte message, " + f"{smoke_runs} parse/hash/encode records: {elapsed:.6f}s wall, " + f"{elapsed / smoke_runs:.6f}s/record (includes process startup and pipe I/O) PASS") + +vectors = json.loads((HERE / "vectors.json").read_text())["parse"] +golden_input = "".join("P" + row["input"].encode().hex() + "\n" for row in vectors).encode() +r = subprocess.run([str(binary)], input=golden_input, stdout=subprocess.PIPE, check=True, timeout=120) +got = r.stdout.decode().splitlines() +assert len(got) == len(vectors) +for row, line in zip(vectors, got): + if row["output"] is None: + assert line == "E", (row, line) + else: + assert line.startswith("O ") and line.split(" ")[2] == row["output"].encode().hex(), (row, line) +print(f"json: committed-vectors {len(vectors)}/{len(vectors)} PASS") + +mutants = { + "duplicates": ("if jsondupe t d id\nret 5", "if false\nret 5"), + "unicode": ("ret 65533", "ret 65532"), + "depth": ("if ge get st 5 32", "if ge get st 5 31"), + "members": ("if ge get t add b 5 512", "if ge get t add b 5 514"), + "integer": ("if gt v div sub ulong 18446744073709551615 c 10", "if ge v div sub ulong 18446744073709551615 c 10"), + "html": ("or eq v 60 or eq v 62", "or eq v 61 or eq v 62"), +} +for name, (old, new) in mutants.items(): + assert old in SOURCE, name + mutant = build(SOURCE.replace(old, new, 1), "mutant-" + name) + status, _, rc = execute(mutant, data, expected) + assert status == "mismatch", (name, status, rc) + print(f"json: completed-result mutant {name} detected PASS") +trap_source = SOURCE.replace("if jsondupe t d id\nret 5", "if jsondupe t d id\ntrap 5", 1) +trap = build(trap_source, "mutant-trap") +status, _, rc = execute(trap, data, expected) +assert status == "abnormal" and rc == 105, (status, rc) +print("json: trapping mutant rejected by harness PASS") +print(f"json: differential {len(rows)}/{len(rows)} PASS") +print(f"json: compiler sha256 {hashlib.sha256(OMC.read_bytes()).hexdigest()}") diff --git a/om/json/test/run.sh b/om/json/test/run.sh new file mode 100755 index 0000000..1ddb004 --- /dev/null +++ b/om/json/test/run.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +set -eu +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH= cd -- "$here/../../.." && pwd) +if [ "$#" -eq 0 ]; then + omc=$("$root/tools/omc.sh") +else + omc=$1 +fi +exec python3 "$here/run.py" "$omc" diff --git a/om/json/test/vectors.json b/om/json/test/vectors.json new file mode 100644 index 0000000..d2bcf6c --- /dev/null +++ b/om/json/test/vectors.json @@ -0,0 +1,27 @@ +{ + "source": "https://www.rfc-editor.org/rfc/rfc8259 and https://pkg.go.dev/encoding/json; independently authored edge cases, 2026-10-25", + "parse": [ + {"input": "null", "output": "null"}, + {"input": " {\"a\": [1,true,false,null]} ", "output": "{\"a\":[1,true,false,null]}"}, + {"input": "\"\\uD834\\uDD1E\"", "output": "\"𝄞\""}, + {"input": "\"\\ud800\"", "output": "\"�\""}, + {"input": "\"\\udc00\"", "output": "\"�\""}, + {"input": "\"\\ud800\\ud800\"", "output": "\"��\""}, + {"input": "\"<>&\"", "output": "\"\\u003c\\u003e\\u0026\""}, + {"input": "9007199254740993", "output": "9007199254740993"}, + {"input": "18446744073709551615", "output": "18446744073709551615"}, + {"input": "-9223372036854775808", "output": "-9223372036854775808"}, + {"input": "1e999999999999999999999", "output": "1e999999999999999999999"}, + {"input": "\"\\u0000\"", "output": "\"\\u0000\""}, + {"input": "\"\\/\"", "output": "\"/\""}, + {"input": "{\"x\":1,\"\\u0078\":2}", "output": null}, + {"input": "{\"x\":1,\"x\":2}", "output": null}, + {"input": "{\"x\":1,}", "output": null}, + {"input": "[1,]", "output": null}, + {"input": "01", "output": null}, + {"input": "1e+", "output": null}, + {"input": "true false", "output": null}, + {"input": "\"\\uD834\\uQQQQ\"", "output": null}, + {"input": "\"a\nb\"", "output": null} + ] +} diff --git a/om/store/README.md b/om/store/README.md new file mode 100644 index 0000000..2c90815 --- /dev/null +++ b/om/store/README.md @@ -0,0 +1,147 @@ +# Descriptor-secure snapshot store + +Program-mode Linux ARM64 storage. Include `om/blake2s/blake2s.om`, `store.om`, then +`storepool.om` once. Production logic and native I/O are Omega. The companion +owns fixed global descriptor/state cells; callers must serialize all operations. + +## API + +All `int` results are `0` on success, `1` on refusal or I/O failure, except +`stcommit`, which additionally returns `2` for an **uncertain commit**. + +- `stopen(path view uchar 65536, n ulong, init int)`: open a provisioned directory, + validate its descriptor, acquire the writer lock, and `fchdir` into it. `init=1` + requires no `snapshot` entry; it does not create a default state. The caller + must commit its explicit initial semantic state before serving. `init=0` + requires an existing fully valid snapshot and calls `stload`. Other modes, + embedded zero bytes, empty paths and paths over 4095 bytes are refused. +- `stbegin()`: create `snapshot.tmp` exclusively. No active transaction is allowed. +- `stwrite(bytes view uchar 65536, n ulong)`: append one frame, preserving chunk + boundaries. Zero length is a no-op. Maximum 65536 bytes per call, 65536 nonempty + calls and 33554432 payload bytes per snapshot. An error poisons the transaction; + it must be aborted, not committed or retried. +- `stcommit()`: append the terminator, fsync the staged file, reread and validate + its entire framing and checksums, rename it over `snapshot`, then fsync the + opened directory. Only result `0` permits in-memory publication and success + replies. A pre-rename failure returns `1` and permits `stabort`. After successful + rename, directory-sync or close failure returns `2`; the store rejects further + begin/load/read/abort operations. The daemon must exit without serving, replying + success, or attempting rollback. A retry on the same staged file is refused. +- `stabort()`: close the staged file and remove a validated reserved temporary + entry, while holding the lock. Never changes the committed snapshot. +- `stload()`: validate the complete committed snapshot, fsync it and the directory, + then reset the reader. Startup thus re-establishes durability of the selected + snapshot after an earlier uncertain rename. Never falls back to a temporary file. +- `stread(out edit uchar 65536) -> long`: next exact nonempty write frame; zero at + EOF, `-1` on error. Callers accumulate across frames when reading semantic records. + Framing and checksums are also checked on this pass. Errors poison the store. +- `stclose()`: close file descriptors and directory, then release the abstract lock. + Call only **after** the daemon has closed/removed its RPC socket and finished all + storage activity. A failed `stopen` cleans its own descriptors; an already-open + store is not closed by a second `stopen` call. +- `stpass(dirtgt int, locktgt int)`: first-epoch controlled-exec handoff. Requires a + healthy store with committed initialization, no writer, and no recovery read in + progress. An exhausted reader is closed. Targets must be distinct, at least 3, + and unused (`fstat` must return exactly `EBADF`); occupied targets are never + overwritten. Duplicates directory and lock with flags zero, retaining original + close-on-exec descriptors and tracking the copies for shutdown. Once duplication + begins, further storage operations are poisoned even on successful handoff: + immediately exec or exit, never resume serving. Any failure is fatal to rollover. +- `stresume(dirfd int, lockfd int)`: adopt structurally validated inherited + descriptors. Requires a 0700/effective-UID directory and an effective-UID socket + whose complete 34-byte abstract name exactly matches that directory's device + and inode. Anchors cwd and calls ordinary `stload`, including full validation and + recovery fsync. No bind, initialization, pathname reopen, stale-file removal or + fallback occurs. Missing, swapped, non-socket and wrong-directory descriptors + refuse. Subsequent resumed epochs retain these descriptors directly; they must + not call `stpass` or attempt `dup3(fd, fd, 0)`. + +Ordinary opened descriptors are close-on-exec. The sole exception is explicit +quiescent handoff, used by the daemon with directory FD 64 and lock FD 65 (listener +FD 66 belongs to the daemon). Controlled `/proc/self/exe --resume` must keep all +three references alive continuously and recover semantic state before serving. +The launcher must provide only standard I/O, trusted procfs and a trusted executable +without privilege changes. The service must not fork children retaining these +descriptors. Structural resume validation does not authenticate a hostile same-UID +launcher; same-UID/root trust remains a prerequisite. A returned exec failure must +exit, not clear poison, spin, unlink the RPC entry or reacquire the writer lock. +No environment variable, request field, or production API injects failures or +bypasses validation. + +## Sole writer and filesystem boundary + +The directory must be owned by effective UID, directory type, exactly mode 0700 +(including refusal of special permission bits). Files must be owned by effective +UID, regular, exactly 0600, single-link and bounded in size. Files use +`O_NOFOLLOW|O_NONBLOCK`; special files cannot block startup. The directory uses +`O_DIRECTORY|O_NOFOLLOW`. Metadata is checked on the opened descriptor, not by a +path check preceding open. Existing entries are never repaired to acceptable +permissions. An incompatible umask can cause staged-file validation to refuse. + +The bind-only abstract AF_UNIX lock name is the bytes `omnet.store.v1.` followed +by little-endian 64-bit `st_dev` and `st_ino`. No PID, configurable name, or software +version influences this identity. It is never listened on and accepts no requests. +The descriptor lives across all storage and RPC activity. Different spellings of +the same directory contend for the same lock; process death releases it. A failed +bind refuses startup. Only after acquisition may a daemon remove its reserved +stale RPC pathname. No connect-failed or stale-PID ownership heuristic is used. + +**Deployment prerequisites:** all writers must follow this protocol in the same +network namespace; the operator must provision a trusted ancestor chain; the +process is single-threaded and must not change cwd later. `O_NOFOLLOW` protects +only the final directory component, not ancestor symlinks or path traversal through +a symlink followed by `/`. Same-UID processes and root are trusted. Abstract names +have no filesystem permissions, so an unrelated local process can deny service by +pre-binding a predicted name, but cannot thereby authorize an RPC. A separate-UID +headscale adapter cannot traverse this 0700 directory; this is not a claim of that +integration or of a separate privilege boundary. + +A leftover `snapshot.tmp` is opened without following symlinks, validated as a +private regular single-link file, and removed only under the lock. Its contents +need not be valid because interrupted writes are expected. Unsafe temporary entry +types/ownership/permissions cause refusal, not deletion. In recovery mode the +committed snapshot must validate before stale cleanup. Missing/malformed committed +state never means disabled or empty, and a valid temporary file is never promoted. + +## Version 1 framing + +All integers are unsigned little-endian 64-bit. The file begins with the exact +16 ASCII bytes `OMNETSNAP0000001`. Each nonempty frame contains: + +1. payload byte length (1..65536); +2. BLAKE2s-256 of that frame's payload (32 bytes); +3. payload bytes. + +Maintain a 32-byte zero-initialized chain. For each frame, replace it with +`BLAKE2s-256(previous_chain || payload_digest || length || cumulative_payload_bytes +|| cumulative_frame_count)`. The final record is zero length, final chain, total +payload length, and frame count (56 bytes). Empty snapshots have an all-zero chain +and zero totals. No bytes may follow the terminator. Maximum file size is 36175944 +bytes (32 MiB payload + 65536 frame headers + header and terminator). + +This commits payload, ordering, frame boundaries and completeness; it is corruption +integrity, not owner authentication or anti-rollback. An owner can reconstruct a +valid file, and restoration of an old valid whole-store backup is undetectable. +Service semantics and reconstruction correctness are the daemon's responsibility. + +## Tests and scope + +`sh om/store/test/run.sh` compiles with the repository-pinned compiler and executes +isolated native processes. Python independently constructs BLAKE2s framing. Cases +cover restart, explicit initialization, abort, alias writer contention, kill and +stale-temp recovery, unsafe metadata/types/links, truncation, corruption, oversized +files, maximum frame/payload capacity, self-exec with continuous writer exclusion, +invalid inherited descriptors, partial I/O, bounded EINTR handling and +injected write/read/fsync/rename failures. Ownership-changing fixtures run only +when the test runner is root; non-root runs report that subset as skipped. Injection replaces +thin syscall wrappers only in a separately built test binary; production source +has no fault controls. A completed-result checksum mutant must differ, rather than +crash. Process-kill/restart and syscall-failure tests do not prove power-loss +behavior of any specific filesystem. No live state or services are touched. + +## Third-party material and notices + +No third-party code or vectors are copied here. BLAKE2s uses the repository's +existing Omega unit. Linux ABI layouts and operation semantics are referenced in +the pinned compiler's `docs/one_layer/OMEGESE.md` section 10 and Linux `unix(7)`, +`open(2)`, `stat(2)`, `rename(2)` and `fsync(2)`. diff --git a/om/store/store.om b/om/store/store.om new file mode 100644 index 0000000..f65a464 --- /dev/null +++ b/om/store/store.om @@ -0,0 +1,217 @@ +note SPDX-License-Identifier: Apache-2.0 +note Linux ARM64 descriptor and snapshot framing helpers; include blake2s.om first. +fn stget64 b view uchar 65536 p ulong to ulong +v = ulong 0 +for i ulong 8 +v = or v shl ulong get b add p i mul i 8 +end +ret v +end + +fn stput64 b edit uchar 65536 p ulong v ulong to void +for i ulong 8 +put b add p i uchar and shr v mul i 8 255 +end +end + +fn stpath b edit uchar 65536 to void +note Fixed ASCII snapshot.tmp; use its first eight bytes for snapshot. +stput64 b 0 8390039475830484595 +stput64 b 8 1886221358 +end + +fn staddr fd int a edit uchar 65536 to int +b = new uchar 65536 0 +if ne fstat fd b ulong 0 ulong 128 long 0 +ret 1 +end +put a 0 1 +put a 1 0 +put a 2 0 +note sockaddr_un: fixed abstract prefix omnet.store.v1. then binary device/inode. +stput64 a 3 8391101608174185839 +stput64 a 11 13002232582992495 +stput64 a 18 stget64 b 0 +stput64 a 26 stget64 b 8 +ret 0 +end + +fn stunused fd int to int +if lt fd 3 +ret 1 +end +b = new uchar 65536 0 +if ne fstat fd b ulong 0 ulong 128 long -9 +ret 1 +end +ret 0 +end + +fn stlockmeta dirfd int lockfd int to int +b = new uchar 65536 0 +a = new uchar 65536 0 +if ne fstat lockfd b ulong 0 ulong 128 long 0 +ret 1 +end +if ne and stget64 b 16 61440 ulong 49152 +ret 1 +end +if ne and stget64 b 24 4294967295 ulong geteuid +ret 1 +end +if ne staddr dirfd a 0 +ret 1 +end +if ne sockname lockfd b ulong 0 ulong 65536 long 34 +ret 1 +end +for i ulong 34 +if ne get a i get b i +ret 1 +end +end +ret 0 +end + +note Thin native boundaries deliberately have no production fault-injection switch. +fn stwr fd int b view uchar 65536 off ulong n ulong to long +ret write fd b off n +end +fn strd fd int b edit uchar 65536 off ulong n ulong to long +ret read fd b off n +end +fn stsync fd int to long +ret fsync fd +end +fn strename to long +p = new uchar 65536 0 +put p 0 2 +put p 2 12 +a = new uchar 65536 0 +stpath a +for i ulong 12 +put p add i 4 get a i +end +put p 16 8 +for i ulong 8 +put p add i 18 get a i +end +ret renames p ulong 0 ulong 26 int 0 +end + +fn stwriteall fd int b view uchar 65536 n ulong to int +p = ulong 0 +for attempt ulong 131072 +if eq p n +ret 0 +end +r = stwr fd b p sub n p +if eq r long -4 +r = long 0 +else +if le r long 0 +ret 1 +end +p = add p ulong r +end +end +ret 1 +end +fn streadall fd int b edit uchar 65536 n ulong to int +p = ulong 0 +for attempt ulong 131072 +if eq p n +ret 0 +end +r = strd fd b p sub n p +if eq r long -4 +r = long 0 +else +if le r long 0 +ret 1 +end +p = add p ulong r +end +end +ret 1 +end + +note fstat ARM64 mode16,nlink20,uid24,size48; reject special bits and hard links. +fn stmeta fd int isdir int to int +b = new uchar 65536 0 +if ne fstat fd b ulong 0 ulong 128 long 0 +ret 1 +end +m = and stget64 b 16 4294967295 +u = and stget64 b 24 4294967295 +if ne u ulong geteuid +ret 1 +end +if eq isdir 1 +if ne m ulong 16832 +ret 1 +end +else +if ne m ulong 33152 +ret 1 +end +if ne and shr stget64 b 16 32 4294967295 ulong 1 +ret 1 +end +if gt stget64 b 48 ulong 36175944 +ret 1 +end +end +ret 0 +end + +note Digest chaining commits order, frame lengths, cumulative bytes and frame count. +fn stchain prev view uchar 32 hash view uchar 32 n ulong total ulong count ulong out edit uchar 32 to void +b = new uchar 65536 0 +k = new uchar 32 0 +for i ulong 32 +put b i get prev i +put b add i 32 get hash i +end +stput64 b 64 n +stput64 b 72 total +stput64 b 80 count +b2shash b 88 k 0 32 out +end +fn sthashdata b view uchar 65536 n ulong out edit uchar 32 to void +k = new uchar 32 0 +b2shash b n k 0 32 out +end +fn steqhash b view uchar 65536 off ulong h view uchar 32 to int +v = ulong 0 +for i ulong 32 +v = or v ulong xor get b add off i get h i +end +if ne v 0 +ret 1 +end +ret 0 +end + +fn stmagic b edit uchar 65536 to void +note Exact 16 ASCII bytes OMNETSNAP0000001. +stput64 b 0 4705790282053864783 +stput64 b 8 3544385890265608272 +end +fn sthead fd int to int +b = new uchar 65536 0 +m = new uchar 65536 0 +stmagic m +if ne fseek fd long 0 int 0 long 0 +ret 1 +end +if ne streadall fd b 16 0 +ret 1 +end +for i ulong 16 +if ne get b i get m i +ret 1 +end +end +ret 0 +end diff --git a/om/store/storepool.om b/om/store/storepool.om new file mode 100644 index 0000000..6798eba --- /dev/null +++ b/om/store/storepool.om @@ -0,0 +1,529 @@ +note SPDX-License-Identifier: Apache-2.0 +note Single-threaded program companion. Descriptor cells store fd+1, zero means absent. +note ctx: dir,lock,writer,reader,poison,init,total,count,readtotal,readcount,writebad,eof. +note ctx12/13 track first-epoch inheritance copies until exec or shutdown. +global stctx long 14 +global sthash uchar 64 + +fn stgethash slot ulong h edit uchar 32 to void +for i ulong 32 +put h i get sthash add mul slot 32 i +end +end +fn stsethash slot ulong h view uchar 32 to void +for i ulong 32 +put sthash add mul slot 32 i get h i +end +end +fn stresetread to void +put stctx 8 0 +put stctx 9 0 +put stctx 11 0 +for i ulong 32 +put sthash add i 32 0 +end +end +fn stdrop slot ulong to int +v = get stctx slot +put stctx slot 0 +if gt v long 0 +if ne fclose int sub v long 1 long 0 +ret 1 +end +end +ret 0 +end + +note Reader rejects all damage including trailing data and missing terminator. +fn stnext fd int out edit uchar 65536 to long +if ne get stctx 11 long 0 +ret 0 +end +h = new uchar 65536 0 +d = new uchar 32 0 +p = new uchar 32 0 +q = new uchar 32 0 +if ne streadall fd h 40 0 +ret -1 +end +n = stget64 h 0 +if eq n 0 +stgethash 1 p +if ne steqhash h 8 p 0 +ret -1 +end +if ne streadall fd h 16 0 +ret -1 +end +if ne stget64 h 0 ulong get stctx 8 +ret -1 +end +if ne stget64 h 8 ulong get stctx 9 +ret -1 +end +if ne strd fd h 0 1 long 0 +ret -1 +end +put stctx 11 1 +ret 0 +end +if gt n 65536 +ret -1 +end +if gt add ulong get stctx 8 n 33554432 +ret -1 +end +if ge get stctx 9 long 65536 +ret -1 +end +if ne streadall fd out n 0 +ret -1 +end +sthashdata out n d +if ne steqhash h 8 d 0 +ret -1 +end +put stctx 8 add get stctx 8 long n +put stctx 9 add get stctx 9 long 1 +stgethash 1 p +stchain p d n ulong get stctx 8 ulong get stctx 9 q +stsethash 1 q +ret long n +end + +fn stvalidate fd int to int +if ne stmeta fd 0 0 +ret 1 +end +if ne sthead fd 0 +ret 1 +end +stresetread +b = new uchar 65536 0 +for i ulong 65537 +r = stnext fd b +if lt r long 0 +ret 1 +end +if eq r long 0 +ret 0 +end +end +ret 1 +end + +fn stread out edit uchar 65536 to long +if ne get stctx 4 long 0 +ret -1 +end +if eq get stctx 3 long 0 +ret -1 +end +r = stnext int sub get stctx 3 long 1 out +if lt r long 0 +put stctx 4 1 +end +ret r +end + +fn stload to int +if eq get stctx 0 long 0 +ret 1 +end +if ne get stctx 4 long 0 +ret 1 +end +if ne get stctx 2 long 0 +ret 1 +end +if ne stdrop 3 0 +ret 1 +end +name = new uchar 65536 0 +stpath name +f = fopen name ulong 0 ulong 8 int 559104 int 0 +if lt f long 0 +ret 1 +end +put stctx 3 add f long 1 +if ne stvalidate int f 0 +r = stdrop 3 +ret 1 +end +note Re-establish durability before resuming after a possible uncertain prior rename. +if ne stsync int f long 0 +r = stdrop 3 +ret 1 +end +if ne stsync int sub get stctx 0 long 1 long 0 +r = stdrop 3 +ret 1 +end +if ne sthead int f 0 +r = stdrop 3 +ret 1 +end +stresetread +ret 0 +end + +note O_NOFOLLOW|O_NONBLOCK prevents symlink following and FIFO open blocking. +fn ststale to int +name = new uchar 65536 0 +stpath name +f = fopen name ulong 0 ulong 12 int 559104 int 0 +if eq f long -2 +ret 0 +end +if lt f long 0 +ret 1 +end +r = stmeta int f 0 +c = fclose int f +if ne r 0 +ret 1 +end +if ne c long 0 +ret 1 +end +if ne unlink name ulong 0 ulong 12 long 0 +ret 1 +end +ret 0 +end + +fn stlock fd int to int +a = new uchar 65536 0 +if ne staddr fd a 0 +ret 1 +end +s = socknew int 1 int 524289 int 0 +if lt s long 0 +ret 1 +end +if ne bind int s a ulong 0 ulong 34 long 0 +r = fclose int s +ret 1 +end +put stctx 1 add s long 1 +ret 0 +end + +fn stclose to int +note All directory references close before either writer-lock reference. +r = stdrop 3 +r = or r stdrop 2 +r = or r stdrop 12 +r = or r stdrop 0 +r = or r stdrop 13 +r = or r stdrop 1 +put stctx 4 0 +ret r +end + +fn stopen path view uchar 65536 n ulong init int to int +if ne get stctx 0 long 0 +ret 1 +end +if eq n 0 +ret 1 +end +if gt n 4095 +ret 1 +end +for i ulong n +if eq get path i uchar 0 +ret 1 +end +end +if ne init 0 +if ne init 1 +ret 1 +end +end +note ARM64 O_DIRECTORY=16384, O_NOFOLLOW=32768, O_CLOEXEC=524288. +f = fopen path ulong 0 n int 573440 int 0 +if lt f long 0 +ret 1 +end +put stctx 0 add f long 1 +put stctx 4 0 +if ne stmeta int f 1 0 +r = stclose +ret 1 +end +if ne stlock int f 0 +r = stclose +ret 1 +end +if ne fchdir int f long 0 +r = stclose +ret 1 +end +put stctx 5 long init +name = new uchar 65536 0 +stpath name +if eq init 1 +v = fopen name ulong 0 ulong 8 int 559104 int 0 +if ne v long -2 +if ge v long 0 +r = fclose int v +end +r = stclose +ret 1 +end +else +if ne stload 0 +r = stclose +ret 1 +end +end +if ne ststale 0 +r = stclose +ret 1 +end +ret 0 +end + +fn stbegin to int +if eq get stctx 0 long 0 +ret 1 +end +if ne get stctx 4 long 0 +ret 1 +end +if ne get stctx 2 long 0 +ret 1 +end +if ne stdrop 3 0 +ret 1 +end +if ne ststale 0 +ret 1 +end +name = new uchar 65536 0 +stpath name +f = fopen name ulong 0 ulong 12 int 559298 int 384 +if lt f long 0 +ret 1 +end +put stctx 2 add f long 1 +put stctx 10 0 +put stctx 6 0 +put stctx 7 0 +for i ulong 32 +put sthash i 0 +end +if ne stmeta int f 0 0 +put stctx 10 1 +ret 1 +end +b = new uchar 65536 0 +stmagic b +if ne stwriteall int f b 16 0 +put stctx 10 1 +ret 1 +end +ret 0 +end + +fn stwrite b view uchar 65536 n ulong to int +if eq get stctx 2 long 0 +ret 1 +end +if ne get stctx 4 long 0 +ret 1 +end +if ne get stctx 10 long 0 +ret 1 +end +if eq n 0 +ret 0 +end +if gt n 65536 +put stctx 10 1 +ret 1 +end +if gt add ulong get stctx 6 n 33554432 +put stctx 10 1 +ret 1 +end +if ge get stctx 7 long 65536 +put stctx 10 1 +ret 1 +end +h = new uchar 65536 0 +d = new uchar 32 0 +p = new uchar 32 0 +q = new uchar 32 0 +sthashdata b n d +stput64 h 0 n +for i ulong 32 +put h add i 8 get d i +end +f = int sub get stctx 2 long 1 +if ne stwriteall f h 40 0 +put stctx 10 1 +ret 1 +end +if ne stwriteall f b n 0 +put stctx 10 1 +ret 1 +end +put stctx 6 add get stctx 6 long n +put stctx 7 add get stctx 7 long 1 +stgethash 0 p +stchain p d n ulong get stctx 6 ulong get stctx 7 q +stsethash 0 q +ret 0 +end + +fn stabort to int +if ne get stctx 4 long 0 +ret 1 +end +if eq get stctx 2 long 0 +ret 0 +end +r = stdrop 2 +if ne ststale 0 +ret 1 +end +ret r +end + +fn stcommit to int +if eq get stctx 2 long 0 +ret 1 +end +if ne get stctx 4 long 0 +ret 1 +end +if ne get stctx 10 long 0 +ret 1 +end +f = int sub get stctx 2 long 1 +b = new uchar 65536 0 +for i ulong 32 +put b add i 8 get sthash i +end +stput64 b 40 ulong get stctx 6 +stput64 b 48 ulong get stctx 7 +if ne stwriteall f b 56 0 +put stctx 10 1 +ret 1 +end +note A failed commit cannot be attempted again on the same staged file. +put stctx 10 1 +if ne stsync f long 0 +ret 1 +end +if ne stvalidate f 0 +ret 1 +end +if ne strename long 0 +ret 1 +end +note No rollback, retry or serving is permitted after an uncertain commit. +put stctx 4 1 +if ne stsync int sub get stctx 0 long 1 long 0 +ret 2 +end +if ne stdrop 2 0 +ret 2 +end +put stctx 4 0 +put stctx 5 0 +ret 0 +end + +note First cold-start epoch only. Caller must exec immediately or exit on failure. +fn stpass dirtgt int locktgt int to int +if eq get stctx 0 long 0 +ret 1 +end +if eq get stctx 1 long 0 +ret 1 +end +if ne get stctx 4 long 0 +ret 1 +end +if ne get stctx 5 long 0 +ret 1 +end +if ne get stctx 2 long 0 +ret 1 +end +if ne get stctx 12 long 0 +ret 1 +end +if ne get stctx 13 long 0 +ret 1 +end +if ne get stctx 3 long 0 +if eq get stctx 11 long 0 +ret 1 +end +end +if eq dirtgt locktgt +ret 1 +end +if ne stunused dirtgt 0 +ret 1 +end +if ne stunused locktgt 0 +ret 1 +end +if ne stdrop 3 0 +ret 1 +end +note Poison while constructing handoff; any partial failure is fail-stop. +put stctx 4 1 +r = dupfd int sub get stctx 0 long 1 dirtgt int 0 +if ne r long dirtgt +ret 1 +end +put stctx 12 add long dirtgt long 1 +r = dupfd int sub get stctx 1 long 1 locktgt int 0 +if ne r long locktgt +ret 1 +end +put stctx 13 add long locktgt long 1 +note Keep poisoned after handoff: no new storage work may race the exec boundary. +ret 0 +end + +note Structural adoption only; same-UID/root launcher and trusted procfs are prerequisites. +fn stresume dirfd int lockfd int to int +if ne get stctx 0 long 0 +ret 1 +end +if lt dirfd 3 +ret 1 +end +if lt lockfd 3 +ret 1 +end +if eq dirfd lockfd +ret 1 +end +if ne stmeta dirfd 1 0 +ret 1 +end +if ne stlockmeta dirfd lockfd 0 +ret 1 +end +put stctx 0 add long dirfd long 1 +put stctx 1 add long lockfd long 1 +put stctx 4 0 +put stctx 5 0 +if ne fchdir dirfd long 0 +r = stclose +ret 1 +end +if ne stload 0 +r = stclose +ret 1 +end +ret 0 +end diff --git a/om/store/test/driver.om b/om/store/test/driver.om new file mode 100644 index 0000000..d599dde --- /dev/null +++ b/om/store/test/driver.om @@ -0,0 +1,180 @@ +note SPDX-License-Identifier: Apache-2.0 +fn testresult code int to int +b = new uchar 65536 0 +put b 0 uchar code +r = write int 1 b ulong 0 ulong 1 +ret 0 +end +fn testfinish code int to int +r = stclose +ret testresult code +end +fn testcapacity b edit uchar 65536 mode uchar to int +if eq mode uchar 85 +if ne stwrite b 65537 1 +ret testfinish 4 +end +if ne stcommit 1 +ret testfinish 4 +end +ret testfinish stabort +end +count = ulong 512 +size = ulong 65536 +if eq mode uchar 81 +count = ulong 65536 +size = ulong 1 +end +for i ulong count +if ne stwrite b size 0 +ret testfinish 4 +end +end +if ne mode uchar 71 +if ne stwrite b 1 1 +ret testfinish 4 +end +if ne stcommit 1 +ret testfinish 4 +end +ret testfinish stabort +end +if ne stcommit 0 +ret testfinish 4 +end +if ne stload 0 +ret testfinish 4 +end +for i ulong count +if ne stread b long size +ret testfinish 4 +end +end +if ne stread b long 0 +ret testfinish 4 +end +ret testfinish 0 +end +fn main to int +p = new uchar 65536 0 +m = new uchar 65536 0 +b = new uchar 65536 0 +n = argread ulong 1 p ulong 0 ulong 65536 +v = argread ulong 2 m ulong 0 ulong 65536 +mode = get m 0 +seed = uchar 17 +if gt argcnt long 3 +v = argread ulong 3 b ulong 0 ulong 65536 +seed = get b 0 +end +init = int 0 +if eq mode uchar 73 +init = int 1 +end +if eq mode uchar 69 +init = int 1 +end +if lt n long 0 +ret testresult 1 +end +r = stopen p ulong n init +if ne r 0 +ret testresult r +end +if eq init 1 +if ne stpass 64 65 1 +ret testfinish 4 +end +end +if eq mode uchar 72 +put b 0 9 +v = write int 1 b ulong 0 ulong 1 +v = read int 0 b ulong 0 ulong 1 +ret testfinish 0 +end +if eq mode uchar 76 +r = stload +if ne r 0 +ret testfinish r +end +v = stread b +if ne v long 65536 +ret testfinish 3 +end +for i ulong 65536 +if ne get b i uchar and add ulong seed i 255 +ret testfinish 3 +end +end +v = stread b +if ne v long 17 +ret testfinish 3 +end +for i ulong 17 +if ne get b i seed +ret testfinish 3 +end +end +if ne stread b long 0 +ret testfinish 3 +end +ret testfinish 0 +end +note TEST_ARM +r = stbegin +if ne r 0 +ret testfinish r +end +if ne stpass 64 65 1 +ret testfinish 4 +end +if or eq mode uchar 71 eq mode uchar 67 +ret testcapacity b mode +end +if or eq mode uchar 81 eq mode uchar 85 +ret testcapacity b mode +end +if ne mode uchar 69 +for i ulong 65536 +put b i uchar and add ulong seed i 255 +end +r = stwrite b 65536 +if ne r 0 +ret testfinish r +end +for i ulong 17 +put b i seed +end +r = stwrite b 17 +if ne r 0 +ret testfinish r +end +end +if eq mode uchar 75 +put b 0 9 +v = write int 1 b ulong 0 ulong 1 +v = read int 0 b ulong 0 ulong 1 +ret testfinish 0 +end +if eq mode uchar 65 +r = stabort +ret testfinish r +end +r = stcommit +if eq r 2 +note Verify a poisoned store cannot mutate, recover or pretend to abort. +if ne stbegin 1 +ret testfinish 4 +end +if ne stload 1 +ret testfinish 4 +end +if ne stabort 1 +ret testfinish 4 +end +if ne stpass 64 65 1 +ret testfinish 4 +end +end +ret testfinish r +end diff --git a/om/store/test/resume.om b/om/store/test/resume.om new file mode 100644 index 0000000..24014f5 --- /dev/null +++ b/om/store/test/resume.om @@ -0,0 +1,91 @@ +note SPDX-License-Identifier: Apache-2.0 +note Test-only controlled self-exec driver; production daemon owns its resume grammar. +fn rsresult value uchar to int +b = new uchar 65536 0 +put b 0 value +r = write int 1 b ulong 0 ulong 1 +ret 0 +end +fn rsdrain to int +b = new uchar 65536 0 +for i ulong 65537 +r = stread b +if lt r long 0 +ret 1 +end +if eq r long 0 +ret 0 +end +end +ret 1 +end +fn main to int +p = new uchar 65536 0 +n = argread ulong 1 p ulong 0 ulong 65536 +if eq get p 0 uchar 45 +if ne stresume 64 65 0 +ret rsresult 1 +end +if ne rsdrain 0 +ret rsresult 1 +end +r = rsresult 9 +v = read int 0 p ulong 0 ulong 1 +r = stclose +ret rsresult uchar r +end +if ne stopen p ulong n 0 0 +ret rsresult 1 +end +note No handoff while a recovery read is in progress. +if ne stpass 64 65 1 +ret rsresult 4 +end +if ne rsdrain 0 +ret rsresult 1 +end +if ne stpass 64 64 1 +ret rsresult 4 +end +if ne stpass 1 65 1 +ret rsresult 4 +end +if ne stpass 64 65 0 +ret rsresult 1 +end +if ne stbegin 1 +ret rsresult 4 +end +note Packed argv: two records /proc/self/exe and --resume. +for i ulong 32 +put p i 0 +end +put p 0 2 +put p 2 14 +put p 4 47 +put p 5 112 +put p 6 114 +put p 7 111 +put p 8 99 +put p 9 47 +put p 10 115 +put p 11 101 +put p 12 108 +put p 13 102 +put p 14 47 +put p 15 101 +put p 16 120 +put p 17 101 +put p 18 8 +put p 20 45 +put p 21 45 +put p 22 114 +put p 23 101 +put p 24 115 +put p 25 117 +put p 26 109 +put p 27 101 +r = rsresult 8 +v = execprog p ulong 0 ulong 28 +ret rsresult 5 +end diff --git a/om/store/test/run.py b/om/store/test/run.py new file mode 100755 index 0000000..d3b96ef --- /dev/null +++ b/om/store/test/run.py @@ -0,0 +1,372 @@ +#!/usr/bin/env python3 +"""Native process tests. Python is an independent framing referee, never runtime logic.""" +import errno +import hashlib +import os +from pathlib import Path +import socket +import struct +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[3] +UNIT = ROOT / "om/store" +COMPILER = subprocess.check_output([str(ROOT / "tools/omc.sh")], text=True).strip() +BASE = (ROOT / "om/blake2s/blake2s.om").read_text() +HELP = (UNIT / "store.om").read_text() +POOL = (UNIT / "storepool.om").read_text() +DRIVER = (UNIT / "test/driver.om").read_text() +RESUME = (UNIT / "test/resume.om").read_text() +COUNT = 0 + + +def compile_binary(folder, name, helpers=HELP, pool=POOL, driver=DRIVER, prefix=""): + source = BASE + "\n" + prefix + "\n" + helpers + "\n" + pool + "\n" + driver + result = subprocess.run([COMPILER], input=source.encode(), capture_output=True) + if result.returncode: + (folder / (name + ".om")).write_text(source) + raise AssertionError(f"compile {name}: {result.stderr.decode()}") + target = folder / name + target.write_bytes(result.stdout) + target.chmod(0o700) + return target + + +def call(binary, path, mode, expected=0, seed="a"): + global COUNT + r = subprocess.run([str(binary), str(path), mode, seed], capture_output=True, timeout=120) + assert r.returncode == 0, (mode, "driver did not complete", r.returncode, r.stderr) + assert r.stdout == bytes([expected]), (mode, r.stdout, expected, r.stderr) + COUNT += 1 + + +def directory(root, name): + p = root / name + p.mkdir(mode=0o700) + return p + + +def frame(payloads): + result = bytearray(b"OMNETSNAP0000001") + chain = bytes(32) + total = 0 + for count, payload in enumerate(payloads, 1): + digest = hashlib.blake2s(payload).digest() + total += len(payload) + chain = hashlib.blake2s(chain + digest + struct.pack("<QQQ", len(payload), total, count)).digest() + result.extend(struct.pack("<Q", len(payload)) + digest + payload) + result.extend(struct.pack("<Q", 0) + chain + struct.pack("<QQ", total, len(payloads))) + return bytes(result) + + +def save(path, data): + path.write_bytes(data) + path.chmod(0o600) + + +def inherited_call(binary, first=None, second=None, arg="--resume", expected=b"\1"): + global COUNT + targets = [] + try: + for target, source in ((64, first), (65, second)): + try: + os.fstat(target) + except OSError as e: + assert e.errno == errno.EBADF + else: + raise AssertionError("test handoff target already occupied") + if source is not None: + os.dup2(source, target, inheritable=True) + targets.append(target) + result = subprocess.run([str(binary), str(arg)], pass_fds=targets, + input=b"x", capture_output=True, timeout=20) + assert result.returncode == 0 and result.stdout == expected, ( + "inheritance driver failed", result.returncode, result.stdout, result.stderr) + COUNT += 1 + finally: + for target in targets: + os.close(target) + + +with tempfile.TemporaryDirectory(prefix="omnet-store-") as tmp: + root = Path(tmp) + binary = compile_binary(root, "store") + for boundary in ("ret write fd b off n", "ret read fd b off n", "ret fsync fd", + "ret renames p ulong 0 ulong 26 int 0"): + assert HELP.count(boundary) == 1, ("fault boundary drift", boundary) + injected = HELP.replace("ret write fd b off n", """if eq get testfi 0 long 87 +ret -5 +end +if eq get testfi 0 long 90 +ret 0 +end +if eq get testfi 0 long 88 +ret -4 +end +if eq get testfi 0 long 74 +if eq get testfi 2 long 0 +put testfi 2 1 +ret -4 +end +end +if eq get testfi 0 long 80 +if gt n 7 +ret write fd b off ulong 7 +end +end +ret write fd b off n""").replace("ret read fd b off n", """if eq get testfi 0 long 82 +ret -5 +end +if eq get testfi 0 long 86 +ret 0 +end +if eq get testfi 0 long 74 +if eq get testfi 3 long 0 +put testfi 3 1 +ret -4 +end +end +if eq get testfi 0 long 84 +if gt n 7 +ret read fd b off ulong 7 +end +end +ret read fd b off n""").replace("ret fsync fd", """put testfi 1 add get testfi 1 long 1 +if eq get testfi 0 long 70 +ret -5 +end +if eq get testfi 0 long 68 +if eq get testfi 1 long 2 +ret -5 +end +end +ret fsync fd""").replace("ret renames p ulong 0 ulong 26 int 0", """if eq get testfi 0 long 78 +ret -5 +end +ret renames p ulong 0 ulong 26 int 0""") + assert injected != HELP + fault = compile_binary(root, "fault", helpers=injected, + prefix="global testfi long 4", + driver=DRIVER.replace("note TEST_ARM", "put testfi 0 long mode\nput testfi 1 0")) + p = directory(root, "state") + call(binary, p, "L", 1) + call(binary, p, "I") + original = (p / "snapshot").read_bytes() + payload = bytes((ord("a") + i) & 255 for i in range(65536)) + assert original == frame([payload, b"a" * 17]), "independent framing mismatch" + call(binary, p, "L") + ident = p.stat() + with socket.socket(socket.AF_UNIX) as guard: + guard.bind(b"\0omnet.store.v1." + struct.pack("<QQ", ident.st_dev, ident.st_ino)) + call(binary, p, "S", 1) + call(binary, p, "I", 1) + call(binary, p, "A", seed="b") + call(binary, p, "L") + call(binary, p, "S", seed="b") + call(binary, p, "L", seed="b") + call(binary, p, "S") + resume = compile_binary(root, "resume", driver=RESUME) + rollover = subprocess.Popen([str(resume), str(p)], stdin=subprocess.PIPE, stdout=subprocess.PIPE) + try: + pid = rollover.pid + assert rollover.stdout.read(2) == b"\x08\x09", "self-exec did not recover" + assert rollover.pid == pid and rollover.poll() is None + call(binary, p, "S", 1) + rollover.stdin.write(b"x") + rollover.stdin.flush() + assert rollover.stdout.read(1) == b"\0" + assert rollover.wait(timeout=5) == 0 + COUNT += 1 + finally: + if rollover.poll() is None: + rollover.kill() + rollover.wait(timeout=5) + rollover.stdin.close() + rollover.stdout.close() + call(binary, p, "L") + partial_driver = RESUME.replace("if ne stpass 64 65 0\nret rsresult 1", + "if ne stpass 64 2147483647 0\n" + "if ne stbegin 1\nret rsresult 4\nend\n" + "if ne stload 1\nret rsresult 4\nend\n" + "ret rsresult 1") + assert partial_driver != RESUME + partial = compile_binary(root, "partial-handoff", driver=partial_driver) + inherited_call(partial, arg=p) # first dup succeeds, impossible second FD fails, fail-stop + call(binary, p, "L") + failed_driver = RESUME.replace("put p 4 47", "put p 4 120") + assert failed_driver != RESUME + failed_exec = compile_binary(root, "failed-exec", driver=failed_driver) + inherited_call(failed_exec, arg=p, expected=b"\x08\x05") + call(binary, p, "L") + inherited_call(resume) # missing descriptors + otherdir = directory(root, "other-directory") + dirfd = os.open(p, os.O_RDONLY | os.O_DIRECTORY) + otherfd = os.open(otherdir, os.O_RDONLY | os.O_DIRECTORY) + filefd = os.open(p / "snapshot", os.O_RDONLY) + try: + inherited_call(resume, dirfd, None) + inherited_call(resume, dirfd, filefd) # non-socket lock + inherited_call(resume, dirfd, None, arg=p) # occupied first handoff target + with socket.socket(socket.AF_UNIX) as guard: + inherited_call(resume, dirfd, guard.fileno()) # unnamed socket + guard.bind(b"\0omnet.store.v1." + struct.pack("<QQ", ident.st_dev, ident.st_ino)) + inherited_call(resume, guard.fileno(), dirfd) # swapped resources + inherited_call(resume, otherfd, guard.fileno()) # lock belongs to another directory + inherited_call(resume, dirfd, guard.fileno(), expected=b"\x09\0") + with socket.socket(socket.AF_UNIX) as guard: + guard.bind(b"\0omnet.store.v1." + struct.pack("<QQ", ident.st_dev, ident.st_ino) + b"x") + inherited_call(resume, dirfd, guard.fileno()) # full address length must match + finally: + os.close(dirfd) + os.close(otherfd) + os.close(filefd) + + # Lock key is directory identity, not the spelling of its path. + holder = subprocess.Popen([str(binary), str(p), "H"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) + try: + assert holder.stdout.read(1) == b"\x09" + aliases = [p, p / ".", root / "state/../state"] + link = root / "parent-alias" + link.symlink_to(root, target_is_directory=True) + aliases.append(link / "state") # trusted ancestor alias, final component is a directory + for alias in aliases: + call(binary, alias, "S", 1) + save(p / "snapshot.tmp", b"stale") + call(binary, p, "S", 1) + assert (p / "snapshot.tmp").exists(), "contender removed owner's temporary file" + finally: + holder.kill() + holder.wait(timeout=5) + holder.stdin.close() + holder.stdout.close() + call(binary, p, "L") + assert not (p / "snapshot.tmp").exists() + # Kill a writer with real staged frames, not merely an invented stale file. + holder = subprocess.Popen([str(binary), str(p), "K", "b"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + try: + assert holder.stdout.read(1) == b"\x09" + assert (p / "snapshot.tmp").stat().st_size > 65536 + call(binary, p, "S", 1) + finally: + holder.kill() + holder.wait(timeout=5) + holder.stdin.close() + holder.stdout.close() + call(binary, p, "L") + assert (p / "snapshot").read_bytes() == original + assert not (p / "snapshot.tmp").exists() + + # Only explicit init accepts absent committed state; orphan temp is never promoted. + orphan = directory(root, "orphan") + save(orphan / "snapshot.tmp", original) + call(binary, orphan, "L", 1) + assert (orphan / "snapshot.tmp").exists() + call(binary, orphan, "I") + empty = directory(root, "empty") + call(binary, empty, "E") + assert (empty / "snapshot").read_bytes() == frame([]) + call(binary, empty, "L", 3) # framing accepts empty; driver expects nonempty semantic records + call(binary, p, "U") # too-large chunk is a declared error, not an array trap + call(binary, p, "Q") # exactly 65536 frames, then refuse one more + call(binary, p, "C") # exactly 32 MiB payload, then refuse one more byte + assert (p / "snapshot").read_bytes() == original + capacity = directory(root, "capacity") + call(binary, capacity, "E") + call(binary, capacity, "G") # durable full-capacity snapshot and streaming recovery + + symlink = root / "dir-link" + symlink.symlink_to(p, target_is_directory=True) + call(binary, symlink, "L", 1) + for mode in (0o755, 0o750, 0o1700): + p.chmod(mode) + call(binary, p, "L", 1) + p.chmod(0o700) + regular = root / "not-directory" + save(regular, b"x") + call(binary, regular, "L", 1) + for name in ("snapshot", "snapshot.tmp"): + target = p / name + if target.exists(): + target.unlink() + target.symlink_to(regular) + call(binary, p, "L", 1) + assert target.is_symlink() + target.unlink() + target.mkdir(mode=0o700) + call(binary, p, "L", 1) + target.rmdir() + os.mkfifo(target, 0o600) + call(binary, p, "L", 1) + target.unlink() + sock = socket.socket(socket.AF_UNIX) + sock.bind(str(target)) + call(binary, p, "L", 1) + sock.close() + target.unlink() + save(target, original) + for mode in (0o644, 0o400, 0o1600): + target.chmod(mode) + call(binary, p, "L", 1) + target.chmod(0o600) + other = root / "extra-link" + os.link(target, other) + call(binary, p, "L", 1) + other.unlink() + if os.geteuid() == 0: + os.chown(target, 12345, -1) + call(binary, p, "L", 1) + os.chown(target, 0, -1) + target.unlink() + save(p / "snapshot", original) + if os.geteuid() == 0: + os.chown(p, 12345, -1) + call(binary, p, "L", 1) + os.chown(p, 0, -1) + + # Truncations span header, frames, payload and footer. Corruption includes every field class. + for size in (0, 1, 15, 16, 23, 55, 56, 65591, 65592, len(original)-56, len(original)-1): + save(p / "snapshot", original[:size]) + call(binary, p, "L", 1) + for offset in (0, 15, 16, 20, 24, 55, 56, 1000, 65591, len(original)-49, len(original)-16, len(original)-1): + broken = bytearray(original) + broken[offset] ^= 1 + save(p / "snapshot", broken) + call(binary, p, "L", 1) + save(p / "snapshot", original + b"x") + call(binary, p, "L", 1) + save(p / "snapshot", original) + # Oversize metadata rejected before reading attacker-controlled file contents. + with (p / "snapshot").open("r+b") as f: + f.truncate(36175945) + call(binary, p, "L", 1) + save(p / "snapshot", original) + + # Fault controls exist only in a separately compiled test image, never in store source. + for mode in ("W", "Z", "R", "F", "N", "X", "V"): + call(fault, p, mode, 1, seed="b") + assert (p / "snapshot").read_bytes() == original, mode + call(binary, p, "L") + for mode in ("P", "T", "J"): + call(fault, p, mode, seed="b") + call(binary, p, "L", seed="b") + call(binary, p, "S") + call(fault, p, "D", 2, seed="b") + call(binary, p, "L", seed="b") # selected new snapshot, startup re-syncs it + + # Completed-result mutant: removing payload checksum comparison must be observable. + mutant_pool = POOL.replace("if ne steqhash h 8 d 0", "if ne int 0 int 0") + assert mutant_pool != POOL + mutant = compile_binary(root, "mutant", pool=mutant_pool) + # A payload mismatch still reaches semantic checking (3), rather than framing refusal (1). + # Keep the original frame digest but forge the final chain for altered payload bytes. + changed = bytearray(payload) + changed[944] ^= 1 + forged = bytearray(frame([bytes(changed), b"a" * 17])) + forged[24:56] = original[24:56] + save(p / "snapshot", forged) + call(binary, p, "L", 1) + call(mutant, p, "L", 3) + print(f"PASS store: {COUNT} completed native cases; independent BLAKE2s framing; checksum mutant detected") + if os.geteuid() != 0: + print("SKIP store foreign-UID chown fixtures: runner is non-root") diff --git a/om/store/test/run.sh b/om/store/test/run.sh new file mode 100755 index 0000000..23da207 --- /dev/null +++ b/om/store/test/run.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# Test-only coordinator; all production storage is Omega. +set -eu +root=$(CDPATH= cd -- "$(dirname "$0")/../../.." && pwd) +exec python3 "$root/om/store/test/run.py" diff --git a/tools/build-tkad.sh b/tools/build-tkad.sh new file mode 100755 index 0000000..e2d7a83 --- /dev/null +++ b/tools/build-tkad.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +# Build production Omega only. Optional output path, default build/tkad. +set -eu +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +omc=$(sh "$root/tools/omc.sh") +out=${1:-"$root/build/tkad"} +mkdir -p "$(dirname -- "$out")" +src="$out.om" +cat "$root/om/blake2s/blake2s.om" "$root/om/sha512/sha512.om" \ + "$root/om/ed25519/ed25519.om" "$root/om/blake2b/blake2b.om" \ + "$root/om/argon2/argon2.om" "$root/om/argon2/argon2pool.om" \ + "$root/om/codec/codec.om" "$root/om/cbor/cbor.om" \ + "$root/om/tka/tka.om" "$root/om/tka/tkastate.om" "$root/om/tka/tkapool.om" \ + "$root/om/tkasig/tkasig.om" "$root/om/json/json.om" "$root/om/store/store.om" "$root/om/store/storepool.om" \ + "$root/cmd/tkad/state.om" "$root/cmd/tkad/helpers.om" "$root/cmd/tkad/rpc.om" \ + "$root/cmd/tkad/adapter.om" "$root/cmd/tkad/socket.om" "$root/cmd/tkad/main.om" > "$src" +"$omc" < "$src" > "$out" +chmod +x "$out" +printf '%s\n' "$out" diff --git a/tools/test.sh b/tools/test.sh index e6b20d1..9bffbbb 100755 --- a/tools/test.sh +++ b/tools/test.sh @@ -1,11 +1,11 @@ #!/bin/sh -# Run every unit's test suite. Each om/<unit>/test/run.sh receives the pinned -# compiler path as $1 and exits 0 only when every vector and mutant check passes. +# Run library and executable suites with the pinned compiler path as $1. +# Each suite exits 0 only when its behavior checks pass. set -eu root=$(cd "$(dirname "$0")/.." && pwd) omc=$("$root/tools/omc.sh") fail=0 -for t in "$root"/om/*/test/run.sh; do +for t in "$root"/om/*/test/run.sh "$root"/cmd/*/test/run.sh; do [ -f "$t" ] || continue unit=$(basename "$(dirname "$(dirname "$t")")") if sh "$t" "$omc"; then