omnet
aien-dev/omnet
Brought by drakestapleton
GitHub aien-dev/omnet#5 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/omnet/patches/853a93de33197c6f.bundle -o 853a93de33197c6f.bundle git fetch 853a93de33197c6f.bundle refs/pull/5/head
Provenance
github-import 1
aien-dev/omnet
5
98dacfc834ea1bdcb66dd5352f3ecf08c034847e
{"kind":"github-import","owner":"aien-dev","repo":"omnet","number":5,"url":"https://github.com/aien-dev/omnet/pull/5","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:44Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/AGENTS.md b/AGENTS.md index 3360ae4..f2d4364 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,9 +22,10 @@ Rules: - **Notices.** Third-party text that is copied or translated (RFC excerpts, vector files, upstream code transcribed into a test oracle) ships with its upstream license or copyright notice next to it, and is listed in the unit README's "Third-party material and notices" section. -- **Public repository.** No hostnames, IP addresses, domains, usernames, home-directory paths, - credentials, names of private repositories, or names of the people behind the work in any file, - issue, or PR. Deployment details live outside this repository. +- **Public repository.** The owner's public identity and name/email attribution are intentional. + Do not anonymize that attribution or rewrite history to remove it. Credentials and private + deployment details (hostnames, addresses, home-directory paths, private repositories) stay + outside this repository; other people's private information still requires permission. - **Claims carry evidence.** Every number names its source: a command and its output, a vector file, or the arithmetic. Verdicts are PASS, FAIL, NOT_RUN. Never claim constant-time behaviour, or the absence of a vulnerability, without a check that shows it. diff --git a/README.md b/README.md index 2debe1d..8e3f967 100644 --- a/README.md +++ b/README.md @@ -47,8 +47,9 @@ denial-of-service bug. 1. **Bounded input.** Every read has an explicit capacity, and every message has a maximum size that is checked before it is parsed. 2. **No check-then-use on names.** Act on an opened descriptor, never on a path checked earlier. -3. **Fail closed.** A parse error, signature failure, or unknown field version means reject, never - skip. +3. **Fail closed.** Parse errors and signature failures reject. Compatibility behavior must match + the pinned protocol: unknown signed AUM kinds advance the hash chain as no-ops, as Tailscale + specifies; they never bypass authorization. 4. **Least privilege.** A component that parses untrusted input runs without the privileges of the component that acts on the result. 5. **Two referees.** Each algorithm is checked against published test vectors and against an @@ -61,14 +62,19 @@ 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 | +| `integration/headscale/` | Pinned Headscale v0.29.6 adapter patch, build script and trust contract | +| `integration/e2e/` | Unmodified Tailscale v1.102.0 client builds and isolated lifecycle harness | | `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 -Requirements: Linux on ARM64 (the Omega compiler emits AArch64 Linux programs), `git`, POSIX `sh`. -Python 3 is optional and is used only to generate differential test data. +Requirements: Linux on ARM64 (the Omega compiler emits AArch64 Linux programs), `git`, POSIX `sh`, +Python 3, and Go >=1.26.5 for the TKA differential oracle. Omega holds all TKA logic; +the optional Headscale adapter is Go glue and uses Go1.27.3. ```sh tools/test.sh # builds the pinned compiler on first use, then runs every unit's tests @@ -76,8 +82,20 @@ tools/test.sh # builds the pinned compiler on first use, then runs every un ## Status -Pre-alpha. See [`docs/design/tailnet-lock.md`](docs/design/tailnet-lock.md) for the plan and the -current state of each part. +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. +The Headscale adapter and stock-client control-plane lifecycle have passed isolated +end-to-end verification, including unsigned-peer filtering, authenticated rotation, +authority-key removal, persistence, owner authorization, outage rejection and disablement. +This is not deployed tailnet protection, data-plane qualification or a production security audit. +Build with `tools/build-tkad.sh`; see [`cmd/tkad/README.md`](cmd/tkad/README.md) and +[`integration/headscale/README.md`](integration/headscale/README.md) before running. + +See [`docs/design/tailnet-lock.md`](docs/design/tailnet-lock.md) for the implementation limits, +verification plan, and remaining stages. ## License diff --git a/cmd/tkad/README.md b/cmd/tkad/README.md new file mode 100644 index 0000000..43e2028 --- /dev/null +++ b/cmd/tkad/README.md @@ -0,0 +1,193 @@ +# 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,RotationPubkey,KeySignature}]}`. +`RotationPubkey` is the stored32byte base64 public key, exposed for adapter reconciliation. +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. An exact registry upsert retry (same ID, +node key, rotation key and omitted or identical signature) is nonmutating: it preserves the +revision and pending initialization, including after restart. This also permits replay of an +already accepted historical signature without reauthorizing it under a later authority. +Adapters must propagate these full values to initial/delta map responses and arrange notifications. + +## State transitions and durable publication + +Initialization binds a signed pending genesis to the initiating NodeID and the +frozen registry. Any actual registry change invalidates pending initialization; an exact +upsert retry does not. 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 requires the supplied Head to equal the server's **pre-update** +head; mismatch rejects before staging. Stock `TailnetLockModify` sends its current +head with newly generated AUMs, then checks that the reply names its last new AUM. +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. A +candidate whose registry snapshot would not fit the map response is rejected with +413 and never committed, so a successful mutation cannot make the registry +unreadable. Submitted node-key signatures are stored in canonical typed form: +ignored CBOR fields are dropped before storage, so they cannot pad the snapshot. +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..5d42953 --- /dev/null +++ b/cmd/tkad/adapter.om @@ -0,0 +1,297 @@ +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 +note Exact retries preserve pending initialization and the durable revision. +fn dsregsame t view ulong 32768 d view uchar 65536 i ulong to int +if eq i 64 +ret 0 +end +k = new uchar 32 0 +if eq dsnode t d dsfield t d 1 k 0 +ret 0 +end +if eq dsnodematch k i 0 +ret 0 +end +b = new uchar 65536 0 +n = dsbytes t d dsfield t d 13 b +if ne n 32 +ret 0 +end +p = mul dsrow i 32 +for j ulong 32 +if ne get ds_rot add p j get b j +ret 0 +end +end +r = dsfield t d 10 +if eq r 0 +ret 1 +end +n = dsbytes t d r b +if gt n 65536 +ret 0 +end +if ne n get ds_slen dsrow i +ret 0 +end +p = mul dsrow i 65536 +for j ulong n +if ne get ds_sig add p j get b j +ret 0 +end +end +ret 1 +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 ne dsregsame t d i 0 +put ds_ctl 6 dslit out 0 0 +ret 200 +end +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 +if ne dssetcanon i b n tkacget 1 0 +ret 400 +end +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 4 +for j ulong 32 +put b j get ds_rot add mul dsrow i 32 j +end +p = dsput64 out p b 32 +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 +note A committed registry must always be servable through the map response. +fn dsfits to ulong +keep = get ds_ctl 6 +scr = new uchar 65536 0 +z = dsmap scr +w = get ds_ctl 6 +put ds_ctl 6 keep +if or ne z 200 gt w 65536 +ret 0 +end +ret 1 +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 +if eq dsfits 0 +z = 413 +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 +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..08111c4 --- /dev/null +++ b/cmd/tkad/rpc.om @@ -0,0 +1,491 @@ +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 +note Ignored CBOR fields are dropped, so a stored signature cannot be padded. +fn dscanon sig view uchar 65536 n ulong out edit uchar 65536 to ulong +t = new ulong 131074 0 +m = new ulong 132 0 +if ne nksdec sig n t m 0 +ret 65537 +end +ret nksser sig t m out 0 0 +end +note Store the canonical form; an empty signature still clears the node. +fn dssetcanon i ulong src view uchar 65536 n ulong auth ulong to ulong +if eq n 0 +dssetsig i src 0 auth +ret 0 +end +c = new uchar 65536 0 +z = dscanon src n c +if gt z 65536 +ret 1 +end +dssetsig i c z auth +ret 0 +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 +if eq dskind t dsfield t d 8 5 +if eq dsheadmatch t d 0 +ret 409 +end +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 +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 +if ne dssetcanon i b n tkacget 1 0 +ret 400 +end +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..43e5b98 --- /dev/null +++ b/cmd/tkad/test/faults.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Compile test-only syscall-boundary fault variants; never production switches.""" +import base64 +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") +canon_needle = """note Store the canonical form; an empty signature still clears the node. +fn dssetcanon i ulong src view uchar 65536 n ulong auth ulong to ulong +if eq n 0 +dssetsig i src 0 auth +ret 0 +end +c = new uchar 65536 0 +z = dscanon src n c +if gt z 65536 +ret 1 +end +dssetsig i c z auth +ret 0 +end""" +assert source.count(canon_needle)==1 +# Test-only: keep submitted bytes so an ignored CBOR field can reach the limit. +raw_store=build("raw-store",canon_needle,"""note Test-only raw storage to exercise the registry capacity guard. +fn dssetcanon i ulong src view uchar 65536 n ulong auth ulong to ulong +dssetsig i src n auth +ret 0 +end""") + + +def padded(signature, size): + raw=base64.b64decode(signature) + assert 0xa0<=raw[0]<=0xb7 + pad=b"\x18\x63" + n=size-len(raw)-len(pad)-1-5 + assert n>0 + return base64.b64encode(bytes([raw[0]+1])+raw[1:]+pad+b"\x5a"+struct.pack(">I",n)+bytes(n)).decode() + + +with tempfile.TemporaryDirectory(prefix="tkad-registry-capacity-") as name: + state=pathlib.Path(name);p=start(raw_store,state,True) + for i in (0,1): + assert rpc(state,9,dict(NodeID=i+1,NodeKey=fixture["nodes"][i],RotationPubkey=fixture["rotations"][i]))[0]==200 + common=dict(Version=131,NodeKey=fixture["nodes"][0]) + try: + assert rpc(state,1,dict(common,GenesisAUM=fixture["genesis"]),1)[0]==200 + assert rpc(state,2,dict(common,Signatures={"1":fixture["signatures"][0],"2":fixture["signatures"][1]}),1)[0]==200 + assert rpc(state,9,dict(NodeID=3,NodeKey=fixture["nodes"][2],RotationPubkey=fixture["rotations"][2]))[0]==200 + assert rpc(state,7,dict(Version=131,NodeKey=fixture["nodes"][2],Signature=padded(fixture["signatures"][2],30000)),3)[0]==200 + first=rpc(state,11,{})[1] + assert len(first["Nodes"])==3 and first["Nodes"][2]["KeySignature"]==padded(fixture["signatures"][2],30000),first + # A second individually valid signature would push the registry past the + # map response limit; the candidate must be rejected, never committed. + assert rpc(state,7,dict(common,Signature=padded(fixture["signatures"][0],30000)),1)[0]==413 + assert rpc(state,11,{})[1]==first,"rejected candidate cannot change the registry" + finally:p.kill();p.communicate(timeout=10) + p=start(raw_store,state) + try: + assert rpc(state,11,{})[1]==first,"over-capacity rejection is durable, registry still readable" + finally:p.kill();p.communicate(timeout=10) +print("PASS tkad registry capacity guard: ignored CBOR padding rejected 413, registry unchanged and readable") + 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..eb3f2ee --- /dev/null +++ b/cmd/tkad/test/smoke.py @@ -0,0 +1,265 @@ +#!/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 padded(signature, size): + """Re-encode a valid NKS map with one ignored field, without touching its hash.""" + raw = base64.b64decode(signature) + check(0xa0 <= raw[0] <= 0xb7, "fixture NKS is a small CBOR map") + pad = b"\x18\x63" # unknown unsigned key 99 + value = b"\x5a" + struct.pack(">I", size - len(raw) - len(pad) - 1 - 5) + return base64.b64encode(bytes([raw[0] + 1]) + raw[1:] + pad + value + b"\x00" * struct.unpack(">I", value[1:])[0]).decode() + + +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) + pending = d.map() + check(pending["TKAInfo"] is None, "pending recovered but invisible") + check(pending["Nodes"][1]["RotationPubkey"] == FIX["rotations"][1], "map exposes reconciliation rotation key") + d.register(1) + check(d.map() == pending, "exact registration retry preserves pending revision") + 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"]}, "pending finish survives restart and exact registration retry") + stable = d.map() + d.register(1, Signature=FIX["signatures"][1]) + check(d.map() == stable, "accepted signature retry preserves revision") + 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=[])) + stable = d.map() + d.rpc(5, d.req(Head=FIX["updatedHead"], MissingAUMs=[FIX["update"]], Interactive=True), expected=409) + check(d.map() == stable, "interactive pre-update head mismatch cannot mutate state") + d.rpc(5, d.req(Head=FIX["head"], 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["updatedHead"], 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["emptyHead"], 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") + historical = d.map() + d.register(2, Signature=FIX["signatures"][2]) + check(d.map() == historical, "historical accepted registration retry is nonmutating") + 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() + changed = root / "changed-roster" + changed.mkdir(mode=0o700) + d = Daemon(changed, True) + try: + d.register(0) + d.register(1) + d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), admin=True) + pending = d.map() + d.rpc(9, dict(NodeID=2, NodeKey=FIX["nodes"][1], RotationPubkey=FIX["rotations"][0]), node=0, admin=True) + check(d.map()["Revision"] == pending["Revision"] + 1, "rotation-key change is a durable registry mutation") + d.rpc(2, d.req(Signatures={"1":FIX["signatures"][0],"2":FIX["signatures"][1]}), admin=True, expected=409) + 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") + # Ignored CBOR fields cannot pad the durable registry past the map limit. + bounded = root / "registry-bounds" + bounded.mkdir(mode=0o700) + d = Daemon(bounded, True) + try: + d.register(0) + d.register(1) + d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), admin=True) + d.rpc(2, d.req(Signatures={"1":FIX["signatures"][0],"2":FIX["signatures"][1]}), admin=True) + d.register(2) + d.rpc(7, d.req(Signature=padded(FIX["signatures"][2], 30000))) + stored = d.map() + check(stored["Nodes"][2]["KeySignature"] == FIX["signatures"][2], "ignored CBOR fields are stripped before storage") + check(d.rpc(8, d.req(KeyID=FIX["keyID"]))["Signatures"][2] == FIX["signatures"][2], "affected-sigs serves the canonical signature") + d.stop(); d = Daemon(bounded) + check(d.map() == stored, "canonical storage survives restart") + finally: + d.stop() + 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 825d958..595b57b 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: design accepted for implementation; crypto primitives done. See [Plan and status](#plan-and-status). +Status: bounded Omega daemon and pinned Headscale adapter implemented; isolated stock-client control-plane lifecycle verified. Not deployed or production-qualified. See [Plan and status](#plan-and-status). ## Problem @@ -11,8 +11,8 @@ its node key carries a signature from a key the devices themselves hold. The device side ships in the stock Tailscale client. The self-hosted control server headscale does not implement the server side ([headscale#1307](https://github.com/juanfont/headscale/issues/1307), -open since 2023). Without it, a self-hosted tailnet has no defence against a compromised control -server. +open since 2023). Without server-side support, a self-hosted tailnet cannot use this client-enforced +signature check to constrain device admission by a compromised control server. ## Goal and non-goals @@ -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,12 +129,17 @@ 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. -**Message limits**: every request body is capped (64 KiB, the capacity of the crypto units) before -it is parsed, and the number of AUMs per sync is capped (design rule 1). Some fields have tighter +**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. +These limits are not a claim of full client interoperability: valid large checkpoints and long +histories can exceed this implementation profile. Service message limits and durable storage must +be resolved and exercised against stock clients before deployment. Some fields have tighter limits, which the request handler checks before calling a unit. A decoded `DisablementSecret` longer than 1024 bytes is rejected, because `om/argon2` `a2tka` traps on longer input. The client sends 32 bytes. The pinned client caps @@ -143,11 +158,13 @@ that way. That is a client issue outside this project; tkad's error bodies are s | Argon2i, TKA disablement KDF (`om/argon2`) | Omega | done: RFC 9106 §5.2, 41 Go cases incl. TKA parameters, 200 random Go cases | | base64, base32, hex, `nodekey:` codecs (`om/codec`) | Omega | done: RFC 4648 §10, 249 malformed cases, 39,806-case Go differential | | 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 / NodeKeySignature model and validation | Omega | planned | -| Chain: fork choice, state at hash, sync offer, intersection, Inform | Omega | planned | -| JSON for the eight RPC types | Omega | planned | -| tkad service: socket loop, storage | Omega | planned | -| headscale glue | Go (fork) | planned | +| 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; 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 (pinned patch) | implemented and exercised with unmodified Tailscale v1.102.0 | ## Verification plan @@ -157,21 +174,153 @@ Each component is checked against two referees: published vectors where they exi the Omega CBOR, and must produce identical hashes. - **Chain**: generated chains with forks, checkpoints, removed keys and bad signatures. tkad's head, sync offers and missing-AUM sets must equal `tka.Authority`'s. -- **Negative corpus**: truncated CBOR, non-canonical CBOR, oversized fields, unknown kinds, wrong - parents and bad signatures. Each must be rejected, with no trap (a trap is a denial-of-service bug). - Type-level rejections that a generic CBOR layer cannot decide (a wrong field type, an out-of-range - integer, a duplicate `Meta` key, bad UTF-8 in `Meta`) belong to the model layer; `om/cbor`'s hostile - corpus already marks these cases for it. +- **Negative corpus**: truncated CBOR, oversized fields, wrong parents and bad signatures reject + without trapping. Non-shortest CBOR and reordered maps are accepted where the client accepts + them; hashes use typed canonical reserialization. Unknown AUM kinds follow the upstream signed + no-op compatibility contract, not an unconditional rejection rule. Typed duplicates, field-type + errors and invalid decoded UTF-8 are rejected by the model layer. - **End to end**: stock clients in containers against the patched headscale. Run `tailscale lock init`, sign, add a node, remove a key, rotate a node key, and disable. Check that an unsigned node is refused by its peers. -## Plan and status +### Stage-three verification + +The complete `tools/test.sh` run on ARM64 Linux passed all nine unit suites with the pinned +compiler (`734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61`). +Go 1.26.8 supplied the pinned TKA oracle; the existing optional oracle comparisons also ran. + +- Authority/model: 10,691 differential records matched upstream; a signature-bypass mutant + completed all records and differed on four. +- Node signatures: 1,135 differential cases matched upstream; nine completed-result mutants + were detected, and a trapping mutant was rejected by the harness. +- Cross-unit scenario: bootstrap a signed authority, authorize a node, apply a signed removal + of its authority key, export the new trusted-key table, then reject the same node signature. + The fixture generator asserts the same before/after result using upstream `Authority`. + +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. + +### Stage-five verification + +Headscale v0.29.6 (`a2b1d7863926834e94479dcdd91ab344a9356bd0`) plus the committed +adapter patch passed the isolated stock Tailscale v1.102.0 lifecycle: + +- Initialize and sign the initial roster; filter a newly registered unsigned peer. +- Sign that peer and propagate signature-only updates. +- Rotate its node key through real interactive Headscale authentication; reject signing + the retired key. The pending rotation does not change the committed identity. +- Remove its signing authority, observe peer rejection, and re-sign under the surviving + authority. Both peer and self signatures must refresh without unrelated metadata changes. +- Restart daemon, controller and clients; retain authority, signatures and removed-key state. +- Reject a non-owner disable request even with a valid secret. +- Stop the isolated daemon; reject signing, disablement and fresh registration without + disabling protection. Restart it; rejected mutations remain unapplied. +- Disable and restart every component; unsigned peers become visible and disablement persists. +The run reported 13 PASS records including the artifact-provenance check. It uses a fresh +network/PID namespace, loopback and a dummy link with no egress. On the verification host, +unprivileged user namespaces were denied; the explicit `--sudo-netns` launcher creates +the namespace and drops UID/GID privileges before running any daemon. No live services, +interfaces, tailnet state or SSH configuration are used. + +All twelve Omega suites passed; the later interactive-sync correction passed the daemon suite +with 279 socket assertions plus failure/recovery checks. The correction checks interactive +Head against pre-update state, matching stock `TailnetLockModify`. +Headscale control/state/mapper/types suites and SQLite migration tests passed after review +fixes. The final self-signature propagation fix additionally passed upstream self-deduplication +regressions and the full stock-client lifecycle. Rebuilding the final patch from a fresh clone +produced the identical controller SHA-256: +`7e6eeb414dc6fd439425b56c4672e2898f71b667b6528f36a75154d3ce27b138`. + +The adapter keeps rejected registration signatures from poisoning unrelated nodes, retains +upstream interactive authentication, rejects duplicate/zero identities before persistence, +and freezes coherent map frames before releasing its publication lock for network writes. +Omega remains the only accepted-signature and authority implementation. The local adapter +still shares the daemon UID. Its durable revision floor is not authenticated rollback protection. +These checks prove control-plane behavior, not packet delivery, power-loss durability, +constant-time cryptography, or production security. + +### Stage-six readiness review + +Two independent read-only source reviews covered recovery/deployment hazards and the admission +boundary. Both found defects rather than only limitations, and each was fixed and regression +tested: + +- **Registry readability.** A verified node-key signature was stored as submitted, and typed + decoding ignores unknown CBOR fields, so an ordinary registered client could keep padding + accepted signatures until the registry no longer fit the 64-KiB map response. Reconciliation + then failed for every request and the daemon could not be repaired through normal RPCs. + Accepted signatures are now stored in canonical typed form, and any candidate whose registry + snapshot would not fit the map response is rejected with 413 before it is persisted. The new + suite covers a 30,000-byte padded signature being accepted and stored canonically, surviving + restart, and a test-only raw-storage variant proving that an over-limit second signature is + refused while the registry stays readable. +- **Unauthenticated admission.** TKA RPCs and map polls took the global publication mutex and + performed SQL plus daemon reconciliation before the caller's identity was checked, so an + arbitrary Noise client could queue on the barrier. A TKA RPC now resolves the caller against + committed SQL first and returns 401 without touching the daemon, and registration and map + admission take a bounded slot and answer 503 instead of queueing. +- **Silent downgrade.** Unsetting both adapter variables after activation used to start stock + behaviour and publish maps with nil `TKAInfo`. Startup now refuses when the database already + records adapter state. + +The remaining findings were deployment limitations, not defects: one committed node without an +NLKey blocks publication for the whole tailnet, SQLite cannot be downgraded in place, the +revision floor is not authenticated rollback protection, and disablement is permanent for that +database. They are recorded as gates in +[`integration/headscale/README.md`](../../integration/headscale/README.md). + +Re-verification after these changes, on the pinned compiler +`734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61`: + +- All twelve Omega suites passed (`tools/test.sh`, exit 0). The daemon suite reported 310 + socket assertions and the new failure/recovery checks, including the registry capacity guard, + and the JSON differential remained 7,706/7,706. That differential now pins its oracle + toolchain in `om/json/test/run.py`: Go 1.27 changes `encoding/json` UTF-8 escaping, so an + unpinned oracle fails on byte comparison. +- Focused adapter regressions, the complete control/state/mapper/types suites and SQLite + migration tests passed, including three new tests: unregistered identity refuses before + authority work, saturated admission fails fast, and adapter state without settings refuses + startup. The deleted-identity test now drives orphan removal through the watcher instead of + relying on an unauthorized request. +- The isolated stock-client lifecycle passed all 13 records again with the rebuilt binaries. +- The committed patch applied to a fresh clone of the pinned tag and rebuilt to a byte-identical + controller: SHA-256 `71ffcb5e6aed6bd6b2ec441b718220e2ad1d70d3fa767c728d104447f8668807` + (supersedes the stage-five hash, which predates these fixes). + +These are host and isolated-namespace results. They do not establish packet delivery, power-loss +durability, constant-time cryptography, or production security, and no deployment is approved. + +## Plan and status 1. Crypto primitives: BLAKE2s, SHA-512, Ed25519. **Done.** 2. BLAKE2b, Argon2i, codecs, CBOR. **Done.** -3. TKA model and chain logic, differential against `tka`. -4. tkad service, storage, JSON. -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. +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. **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. **Implemented and verified in isolation.** + See [`integration/headscale/README.md`](../../integration/headscale/README.md) for reproduction. +6. Independent readiness review and deployment planning. **Done for source review and + rehearsal planning.** Two reviews found three defects, fixed and regression tested in + [Stage six](#stage-six-readiness-review). Deployment gates and the paired-restore + procedure are in [`integration/headscale/README.md`](../../integration/headscale/README.md). + This is not a production audit, and no live deployment is approved. diff --git a/integration/e2e/build-clients.sh b/integration/e2e/build-clients.sh new file mode 100755 index 0000000..bdea3d7 --- /dev/null +++ b/integration/e2e/build-clients.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# Test-only dependency acquisition. Run from any directory: +# GO=/path/to/go GOTOOLCHAIN=auto sh integration/e2e/build-clients.sh +# Builds unmodified tailscale.com v1.102.0 from the checksum-verified Go module. +# The module proxy/checksum database and Go toolchain download require network; +# the lifecycle runner creates an isolated network namespace without egress. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) +GO=${GO:-go} +OUT=${E2E_BIN_DIR:-"$ROOT/build/e2e"} +mkdir -p "$OUT" +OUT=$(CDPATH= cd -- "$OUT" && pwd) +export GOTOOLCHAIN=${GOTOOLCHAIN:-auto} +export GO111MODULE=on +"$GO" mod download -json tailscale.com@v1.102.0 > "$OUT/tailscale-module.json" +SRC=$(python3 - "$OUT/tailscale-module.json" <<'PY' +import json, sys +m = json.load(open(sys.argv[1])) +if m.get('Error') or m.get('Version') != 'v1.102.0' or not m.get('Sum'): + raise SystemExit('pinned Tailscale module acquisition failed') +origin = m.get('Origin', {}) +if origin and origin.get('Hash') != '35283c95445fb198af1ce708dac05714bdfaa037': + raise SystemExit('unexpected Tailscale v1.102.0 source revision') +print(m['Dir']) +PY +) +(cd "$SRC" && "$GO" build -trimpath -buildvcs=false -o "$OUT/tailscale" ./cmd/tailscale) +(cd "$SRC" && "$GO" build -trimpath -buildvcs=false -o "$OUT/tailscaled" ./cmd/tailscaled) +"$GO" version -m "$OUT/tailscale" > "$OUT/tailscale.buildinfo" +"$GO" version -m "$OUT/tailscaled" > "$OUT/tailscaled.buildinfo" +python3 - "$OUT" <<'PY' +import hashlib, json, pathlib, sys +out = pathlib.Path(sys.argv[1]) +module = json.loads((out / 'tailscale-module.json').read_text()) +manifest = { + 'version': 'v1.102.0', + 'source_revision': '35283c95445fb198af1ce708dac05714bdfaa037', + 'module_sum': module['Sum'], + 'sha256': {name: hashlib.sha256((out / name).read_bytes()).hexdigest() + for name in ('tailscale', 'tailscaled')}, +} +(out / 'stock-client.json').write_text(json.dumps(manifest, indent=2) + '\n') +PY +printf 'Built stock v1.102.0 clients in %s\n' "$OUT" diff --git a/integration/e2e/lifecycle.py b/integration/e2e/lifecycle.py new file mode 100755 index 0000000..28391c5 --- /dev/null +++ b/integration/e2e/lifecycle.py @@ -0,0 +1,534 @@ +#!/usr/bin/env python3 +"""Test-only stock-client lifecycle, invoked exclusively through run.sh. + +No synthetic control replies or direct tkad mutations: every authority change is +made by the unmodified tailscale CLI. Observations use the real tailscaled LocalAPI +(/tka/status and /status), not CLI text parsing. Source contracts: Tailscale +v1.102.0 client/local/tailnetlock.go, ipn/ipnstate/ipnstate.go, and +control/controlclient/direct.go (LoginInteractive regenerates the node key). +Rotation completes Headscale's real `auth register` flow only after observing +an AuthURL and checking the old identity remains committed while auth is pending. +Negative requests use stock-generated signatures and require explicit upstream +HTTP rejection; CLI-local validation failures and timeouts do not count. + +This proves client netmap admission, not packet delivery, production isolation, +power-loss durability, or immediate revocation of already-installed peers during +an outage. DERP is deliberately unavailable on loopback: only control-plane state +is asserted. All subprocesses and state belong to this one disposable invocation. +""" +import argparse +import hashlib +import http.client +import json +import os +from pathlib import Path +import re +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import time +import urllib.request + +ROOT = Path(__file__).resolve().parents[2] +TIMEOUT = 90 + + +class Failure(Exception): + pass + + +class UnixHTTP(http.client.HTTPConnection): + def __init__(self, path): + super().__init__("local-tailscaled.sock", timeout=4) + self.path = str(path) + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(self.timeout) + self.sock.connect(self.path) + + +class Harness: + def __init__(self, args): + self.args = args + self.root = Path(tempfile.mkdtemp(prefix="omnet-e2e-", dir="/tmp")) + self.root.chmod(0o700) + self.bin = args.bin_dir.resolve() + self.headscale = args.headscale.resolve() + self.tkad = args.tkad.resolve() + self.env = {k: v for k, v in os.environ.items() + if not k.startswith(("TS_", "HEADSCALE_", "OMNET_", "TAILSCALE_")) + and k.lower() not in ("http_proxy", "https_proxy", "all_proxy", "no_proxy")} + self.env.update(HOME=str(self.root / "home"), XDG_CONFIG_HOME=str(self.root / "config"), + XDG_CACHE_HOME=str(self.root / "cache"), TS_NO_LOGS_NO_SUPPORT="true", + NO_PROXY="*") + for name in ("home", "config", "cache", "authority"): + (self.root / name).mkdir(mode=0o700) + self.processes = {} + self.clients = {} + self.events = [] + self.sequence = 0 + self.url = "http://127.0.0.1:18080" + self.hsenv = dict(self.env, OMNET_TKAD_SOCKET=str(self.root / "authority/tkad.sock"), + OMNET_TKAD_ADMIN_USER_ID="1") + self.hsconfig = self.root / "headscale.json" + # Headscale accepts JSON through Viper. A nonempty local-only DERP map is + # mandatory upstream even when no data-plane checks are requested. + # Local DERP files use Go YAML field names, unlike the remote JSON API. + (self.root / "derp.yaml").write_text( + "regions:\n 999:\n regionid: 999\n regioncode: e2e\n" + " regionname: Isolated E2E\n nodes:\n" + " - name: e2e\n regionid: 999\n hostname: localhost\n" + " ipv4: 127.0.0.1\n derpport: 9\n stunport: -1\n") + self.hsconfig.write_text(json.dumps({ + "server_url": self.url, "listen_addr": "127.0.0.1:18080", + "metrics_listen_addr": "127.0.0.1:19090", "grpc_listen_addr": "127.0.0.1:15043", + "grpc_allow_insecure": False, "disable_check_updates": True, + "unix_socket": str(self.root / "headscale.sock"), "unix_socket_permission": "0600", + "noise": {"private_key_path": str(self.root / "noise.key")}, + "database": {"type": "sqlite", "sqlite": {"path": str(self.root / "headscale.sqlite"), + "write_ahead_log": True}}, + "prefixes": {"v4": "100.64.0.0/24", "allocation": "sequential"}, + "dns": {"magic_dns": False, "override_local_dns": False, + "base_domain": "e2e.invalid", "nameservers": {"global": []}}, + "derp": {"server": {"enabled": False}, "urls": [], + "paths": [str(self.root / "derp.yaml")], "auto_update_enabled": False}, + "logtail": {"enabled": False}, "log": {"level": "info"}, + "policy": {"mode": "file"}, "node": {"ephemeral": {"inactivity_timeout": "30m"}}, + })) + + def start(self, label, argv, env=None): + old = self.processes.get(label) + if old and old.poll() is None: + raise Failure("attempt to duplicate process " + label) + self.sequence += 1 + with open(self.root / f"{self.sequence:03}-{label}.log", "wb") as log: + proc = subprocess.Popen([str(x) for x in argv], stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, env=env or self.env, + cwd=self.root, start_new_session=True) + self.processes[label] = proc + return proc + + def stop(self, label, crash=False): + proc = self.processes.pop(label, None) + if not proc or proc.poll() is not None: + return + os.killpg(proc.pid, signal.SIGKILL if crash else signal.SIGTERM) + try: + proc.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait(timeout=8) + + def command(self, label, argv, env=None, timeout=40, require=True): + self.sequence += 1 + try: + result = subprocess.run([str(x) for x in argv], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=timeout, env=env or self.env, cwd=self.root) + except subprocess.TimeoutExpired as exc: + raise Failure(label + " timed out (not counted as a negative-test success)") from exc + (self.root / f"{self.sequence:03}-{label}.stdout").write_bytes(result.stdout) + (self.root / f"{self.sequence:03}-{label}.stderr").write_bytes(result.stderr) + if require and result.returncode != 0: + raise Failure(label + f" returned {result.returncode}; private log retained only with --keep") + return result + + def hs(self, *args): + result = self.command("headscale-cli", [self.headscale, "--config", self.hsconfig, + *args, "--output", "json"], env=self.hsenv) + return json.loads(result.stdout) + + def cli(self, name, *args, require=True): + return self.command(name + "-cli", [self.bin / "tailscale", "--socket", + self.clients[name]["socket"], *args], require=require) + + def local(self, name, endpoint="tka/status"): + connection = UnixHTTP(self.clients[name]["socket"]) + try: + connection.request("GET", "/localapi/v0/" + endpoint, + headers={"Sec-Tailscale": "localapi", "Connection": "close"}) + response = connection.getresponse() + data = response.read(1024 * 1024 + 1) + if response.status != 200 or len(data) > 1024 * 1024: + raise Failure("LocalAPI read failed on " + name) + return json.loads(data) + finally: + connection.close() + + def wait(self, label, predicate, timeout=TIMEOUT): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + for service in ("tkad", "headscale"): + p = self.processes.get(service) + if p and p.poll() is not None and not getattr(self, "outage", False): + raise Failure(service + f" exited unexpectedly ({p.returncode}) during " + label) + try: + value = predicate() + if value: + return value + except (OSError, http.client.HTTPException, json.JSONDecodeError): + pass # The same bounded predicate must eventually positively succeed. + time.sleep(0.25) + raise Failure("timed out awaiting " + label) + + def check(self, condition, message): + if not condition: + raise Failure(message) + + def receipt(self, name, **details): + self.events.append({"scenario": name, "verdict": "PASS", **details}) + print("PASS: " + name, flush=True) + + def start_tkad(self, initialize=False): + argv = [self.tkad, self.root / "authority"] + if initialize: + argv.append("--init") + self.start("tkad", argv) + # Connect only: do not act as a trusted adapter or fabricate any RPC. + def ready(): + with socket.socket(socket.AF_UNIX) as sock: + sock.settimeout(1) + sock.connect(str(self.root / "authority/tkad.sock")) + return True + self.wait("tkad socket", ready) + + def start_headscale(self): + self.start("headscale", [self.headscale, "--config", self.hsconfig, "serve"], self.hsenv) + def healthy(): + with urllib.request.urlopen(self.url + "/health", timeout=2) as response: + return response.status == 200 + self.wait("Headscale health", healthy) + + def start_client(self, name, user=None): + if name not in self.clients: + directory = self.root / name + directory.mkdir(mode=0o700) + self.clients[name] = {"socket": directory / "tailscaled.sock", "dir": directory, + "user": user} + client = self.clients[name] + self.start(name, [self.bin / "tailscaled", "--tun=userspace-networking", "--port=0", + "--socket=" + str(client["socket"]), + "--state=" + str(client["dir"] / "tailscaled.state"), + "--statedir=" + str(client["dir"])]) + self.wait(name + " LocalAPI", lambda: self.local(name, "status")) + + def login(self, name): + key = self.hs("preauthkeys", "create", "--user", str(self.clients[name]["user"]), + "--expiration", "1h", "--reusable")["key"] + # The authentication key is kept in the private runtime directory, not + # printed in the test receipt. All CLI calls select an explicit socket. + keyfile = self.clients[name]["dir"] / "auth-key" + keyfile.write_text(key) + args = [self.bin / "tailscale", "--socket", self.clients[name]["socket"], "up", + "--login-server=" + self.url, "--auth-key=file:" + str(keyfile), + "--hostname=" + name, "--accept-dns=false", "--accept-routes=false", + "--timeout=45s"] + self.stop(name + "-up") + self.start(name + "-up", args) + + def rotate_interactively(self, name): + old_key = self.keys(name)[0] + old_url = self.local(name, "status").get("AuthURL") + before = [n for n in self.hs("nodes", "list") if n["node_key"] == old_key] + self.check(len(before) == 1, "rotation requires one committed original identity") + original = before[0] + self.stop(name + "-up") + # Deliberately supply no preauth key: the stock LoginInteractive flow + # generates and signs the new key, then requires real controller auth. + proc = self.start(name + "-up", [ + self.bin / "tailscale", "--socket", self.clients[name]["socket"], "up", + "--login-server=" + self.url, "--force-reauth", "--hostname=" + name, + "--accept-dns=false", "--accept-routes=false", "--timeout=45s"]) + + def pending_auth(): + self.check(proc.poll() is None, "interactive rotation exited before authentication") + url = self.local(name, "status").get("AuthURL") + return url if url and url != old_url else None + + url = self.wait("interactive rotation authentication URL", pending_auth, timeout=30) + match = re.fullmatch(re.escape(self.url) + r"/register/([A-Za-z0-9_-]+)", url) + self.check(match is not None, "unexpected interactive registration URL") + + def uncommitted(): + nodes = [n for n in self.hs("nodes", "list") if n["id"] == original["id"]] + return (proc.poll() is None and len(nodes) == 1 and + nodes[0]["node_key"] == old_key and nodes[0]["user"]["id"] == original["user"]["id"]) + + self.stable("rotation waits for authenticated registration", uncommitted, seconds=1) + # CLI auth registration is the upstream non-OIDC operator flow. The + # registration ID and its output stay only in the private runtime logs. + registered = self.hs("auth", "register", "--auth-id", match.group(1), + "--user", original["user"]["name"]) + self.check(registered["id"] == original["id"] and + registered["user"]["id"] == original["user"]["id"], + "interactive registration changed node or user identity") + self.wait("authenticated rotation CLI completion", lambda: proc.poll() is not None, timeout=30) + self.check(proc.returncode == 0, "authenticated rotation CLI failed") + + def joined(self, name): + st = self.local(name, "status") + return (st.get("Self") or {}).get("ID") and self.local(name).get("NodeKey") + + def connected(self, name): + status = self.local(name, "status") + # Cached client state alone must not satisfy a server recovery check. + return status.get("BackendState") == "Running" and (status.get("Self") or {}).get("Online") + + def keys(self, name): + status = self.local(name) + return status["NodeKey"], status["PublicKey"] + + @staticmethod + def peers(status, field): + return {p["NodeKey"] for p in status.get(field) or []} + + def admitted(self, observer, nodekey): + status = self.local(observer) + normal = self.local(observer, "status") + return (status["Enabled"] and nodekey in self.peers(status, "VisiblePeers") + and nodekey not in self.peers(status, "FilteredPeers") + and nodekey in (normal.get("Peer") or {})) + + def rejected(self, observer, nodekey): + status = self.local(observer) + normal = self.local(observer, "status") + return (status["Enabled"] and nodekey in self.peers(status, "FilteredPeers") + and nodekey not in self.peers(status, "VisiblePeers") + and nodekey not in (normal.get("Peer") or {})) + + def same_head(self, names, expected=None): + states = [self.local(n) for n in names] + head = states[0].get("Head") + return head and all(s.get("Enabled") and s.get("Head") == head for s in states) and ( + expected is None or head == expected) + + def stable(self, label, predicate, seconds=3): + self.wait(label, predicate) + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + self.check(predicate(), label + " regressed during stable observation") + time.sleep(0.25) + + def restart_all(self): + for name in self.clients: + self.stop(name + "-up") + self.stop(name) + self.stop("headscale") + self.stop("tkad", crash=True) + self.start_tkad() + self.start_headscale() + for name in self.clients: + self.start_client(name) + + def scenario(self): + for path in (self.headscale, self.tkad, self.bin / "tailscale", self.bin / "tailscaled"): + self.check(path.is_file() and os.access(path, os.X_OK), "missing executable: " + str(path)) + provenance = json.loads((self.bin / "stock-client.json").read_text()) + self.check(provenance["version"] == "v1.102.0", "wrong stock-client version") + for name in ("tailscale", "tailscaled"): + digest = hashlib.sha256((self.bin / name).read_bytes()).hexdigest() + self.check(digest == provenance["sha256"][name], "stock-client provenance mismatch: " + name) + self.receipt("stock-client-artifacts", version=provenance["version"], sha256=provenance["sha256"]) + self.start_tkad(initialize=True) + self.start_headscale() + owner = self.hs("users", "create", "owner") + member = self.hs("users", "create", "member") + self.check(int(owner["id"]) == 1, "fresh DB owner ID differs from explicit adapter configuration") + for name in ("a", "b"): + self.start_client(name, int(owner["id"])) + self.login(name) + self.wait(name + " registration", lambda n=name: self.joined(n)) + akey, apub = self.keys("a") + bkey, bpub = self.keys("b") + self.wait("pre-lock peer roster", lambda: bkey in (self.local("a", "status").get("Peer") or {})) + output = self.cli("a", "lock", "init", "--confirm", "--gen-disablements=1", apub, bpub) + secrets = re.findall(rb"disablement-secret:[0-9A-Fa-f]{64}", output.stdout) + self.check(len(secrets) == 1, "init did not return exactly one disablement secret") + secret = secrets[0].decode("ascii") + self.wait("initialized authority", lambda: self.same_head(["a", "b"]) and + self.local("a")["NodeKeySigned"] and self.local("b")["NodeKeySigned"] and + self.admitted("a", bkey) and self.admitted("b", akey)) + self.receipt("init-and-initial-roster-signatures") + + self.start_client("c", int(member["id"])) + self.login("c") + self.wait("unsigned node registration", lambda: self.joined("c")) + ckey, cpub = self.keys("c") + self.stable("unsigned peer rejection", lambda: self.rejected("a", ckey) and + self.rejected("b", ckey) and self.local("c")["Enabled"] and + not self.local("c")["NodeKeySigned"]) + self.receipt("new-unsigned-node-filtered-by-stock-clients") + self.cli("b", "lock", "sign", ckey, cpub) + self.wait("signature-only notification", lambda: self.admitted("a", ckey) and + self.admitted("b", ckey) and self.local("c")["NodeKeySigned"]) + self.receipt("sign-and-signature-only-peer-notification") + + # The stock client signs its rotation wrapper, but that is not a user + # login. Complete upstream interactive auth before accepting the change. + self.rotate_interactively("c") + self.wait("client node-key rotation", lambda: self.joined("c") and + self.keys("c")[0] != ckey and self.local("c")["NodeKeySigned"]) + rotated = self.keys("c")[0] + self.wait("rotated peer signature", lambda: self.admitted("a", rotated) and self.admitted("b", rotated)) + rotation = self.local("c")["NodeKeySignature"] + self.check(rotation.get("SigKind") == 2 and rotation.get("Nested"), "client did not retain a rotation signature") + for observer in ("a", "b"): + self.check(ckey not in (self.local(observer, "status").get("Peer") or {}), "old node key remained visible") + self.receipt("stock-client-node-key-rotation", + authentication="headscale-auth-register", pending_rotation_uncommitted=True) + + # A real, valid stock-generated signature for the retired key must reach + # the daemon and get 404. Local validation failures and transport failures + # are not passes, and the rejection must not poison other clients. + rotation_head = self.local("a")["Head"] + failed = self.cli("a", "lock", "sign", ckey, cpub, require=False) + self.check(failed.returncode > 0 and b"404" in failed.stderr + failed.stdout, + "retired-key sign must produce explicit 404, not success or local validation failure") + self.stable("rejected signature leaves active tailnet healthy", lambda: + self.same_head(["a", "b", "c"], rotation_head) and + all(self.connected(n) for n in ("a", "b", "c")) and + self.admitted("a", rotated) and self.admitted("b", rotated) and + self.local("c")["NodeKeySigned"]) + self.receipt("retired-node-key-signature-request-rejected", http_status=404) + + # Disabling automatic re-sign is deliberate: it makes key removal's + # authorization effect observable rather than transparently repairing it. + self.cli("a", "lock", "remove", "--re-sign=false", bpub) + self.wait("authority-key removal", lambda: self.same_head(["a", "b", "c"]) and + all(bpub not in {k["Key"] for k in self.local(n)["TrustedKeys"]} for n in ("a", "b", "c"))) + self.stable("removed authority rejects its rotated node", lambda: self.rejected("a", rotated) and + self.rejected("b", rotated) and not self.local("c")["NodeKeySigned"]) + self.receipt("authority-key-removal-invalidates-rotated-node") + self.cli("a", "lock", "sign", rotated, cpub) + self.wait("surviving authority re-sign", lambda: self.admitted("a", rotated) and self.local("c")["NodeKeySigned"]) + + head = self.local("a")["Head"] + state_id = self.local("a")["StateID"] + self.restart_all() + self.wait("persisted active authority", lambda: self.same_head(["a", "b", "c"], head) and + self.admitted("a", rotated) and self.local("c")["NodeKeySigned"] and + all(self.connected(n) and self.local(n)["StateID"] == state_id for n in ("a", "b", "c"))) + self.check(self.keys("c")[0] == rotated, "restart changed node identity") + self.check({k["Key"] for k in self.local("a")["TrustedKeys"]} == {apub}, "removed key returned after recovery") + self.receipt("daemon-controller-and-client-persisted-recovery") + + # c belongs to the non-owner Headscale user. Its real client validates + # this known-good secret locally, then the authenticated controller must + # deny the operation; possession of the secret is not an admin assertion. + denied = self.cli("c", "lock", "disable", secret, require=False) + self.check(denied.returncode > 0 and b"403" in denied.stderr + denied.stdout, + "non-owner disable must produce explicit 403, not success, timeout, or local validation failure") + self.stable("owner policy preserves authority", lambda: self.same_head(["a", "b", "c"], head) + and all(self.local(n)["StateID"] == state_id for n in ("a", "b", "c"))) + self.receipt("non-owner-valid-secret-disable-denied", http_status=403) + + self.start_client("d", int(member["id"])) + self.login("d") + self.wait("outage test unsigned registration", lambda: self.joined("d")) + dkey, dpub = self.keys("d") + self.wait("outage test initial rejection", lambda: self.rejected("a", dkey)) + self.outage = True + self.stop("tkad", crash=True) + for operation in (("sign", dkey, dpub), ("disable", secret)): + failed = self.cli("a", "lock", *operation, require=False) + self.check(failed.returncode > 0 and b"503" in failed.stderr + failed.stdout, + "outage must produce explicit 503, not success, timeout, or local CLI validation failure") + self.stable("outage retains client protection", lambda: self.local("a")["Enabled"] and + self.local("a")["Head"] == head and self.rejected("a", dkey)) + self.start_client("e", int(member["id"])) + self.login("e") + # Positive observation of the upstream registration failure, plus actual + # client state, distinguishes a rejected request from a merely slow join. + def registration_rejected(): + logs = list(self.root.glob("*-e.log")) + if not logs: + return False + data = logs[-1].read_bytes() + # RegisterResponse.Error is an upstream application-level rejection, + # unlike the TKA RPCs' HTTP503. Require a completed negative response. + return (b"RegisterReq: got response; nodeKeyExpired=false, machineAuthorized=false; authURL=false" in data + and b"Received error:" in data + and self.local("e", "status").get("BackendState") == "NeedsLogin") + self.wait("registration receives explicit outage rejection", registration_rejected, timeout=30) + self.check(not self.joined("e"), "fresh client joined during tkad outage") + self.receipt("daemon-outage-sign-disable-and-registration-fail-closed") + self.start_tkad() + self.outage = False + self.wait("outage recovery retains authority", lambda: self.same_head(["a", "b", "c", "d"], head)) + self.wait("retry joins after daemon recovery", lambda: self.joined("e")) + ekey, _ = self.keys("e") + self.wait("retry remains unsigned", lambda: self.rejected("a", ekey) and self.rejected("a", dkey)) + self.receipt("outage-recovery-does-not-authorize-failed-mutations") + + self.cli("a", "lock", "disable", secret) + names = list(self.clients) + self.wait("disable propagates to all stock clients", lambda: all(not self.local(n)["Enabled"] for n in names) + and all(k in (self.local("a", "status").get("Peer") or {}) for k in (rotated, dkey, ekey))) + self.receipt("disable-unfilters-previously-unsigned-peers") + self.restart_all() + self.wait("persisted disablement", lambda: all(self.connected(n) and not self.local(n)["Enabled"] for n in names) + and all(k in (self.local("a", "status").get("Peer") or {}) for k in (rotated, dkey, ekey))) + self.receipt("disablement-persists-across-full-restart") + + def close(self): + for label in reversed(list(self.processes)): + self.stop(label) + if self.args.keep: + print("Private disposable state retained at " + str(self.root), file=sys.stderr) + else: + shutil.rmtree(self.root) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--outer-netns", required=True, help=argparse.SUPPRESS) + parser.add_argument("--bin-dir", type=Path, default=ROOT / "build/e2e") + parser.add_argument("--headscale", type=Path, default=ROOT / "build/headscale") + parser.add_argument("--tkad", type=Path, default=ROOT / "build/tkad") + parser.add_argument("--run-uid", type=int, help=argparse.SUPPRESS) + parser.add_argument("--run-gid", type=int, help=argparse.SUPPRESS) + parser.add_argument("--keep", action="store_true") + parser.add_argument("--result", type=Path, help="write a redacted machine-readable receipt") + args = parser.parse_args() + if os.readlink("/proc/self/ns/net") == args.outer_netns or {n for _, n in socket.if_nameindex()} != {"lo"}: + print("NOT_RUN: requires a fresh loopback-only network namespace; use run.sh", file=sys.stderr) + return 77 + subprocess.run(["ip", "link", "set", "lo", "up"], check=True) + # Stock clients pause control traffic with only loopback. A namespace-local + # dummy link satisfies their network monitor without providing any egress. + subprocess.run(["ip", "link", "add", "e2e0", "type", "dummy"], check=True) + subprocess.run(["ip", "addr", "add", "192.0.2.1/32", "dev", "e2e0"], check=True) + subprocess.run(["ip", "link", "set", "e2e0", "up"], check=True) + if args.run_uid is not None or args.run_gid is not None: + if args.run_uid is None or args.run_gid is None or args.run_uid <= 0 or args.run_gid < 0: + raise SystemExit("privileged launcher requires a non-root invoking UID and its GID") + os.setgroups([]) + os.setresgid(args.run_gid, args.run_gid, args.run_gid) + os.setresuid(args.run_uid, args.run_uid, args.run_uid) + if os.getuid() != args.run_uid or os.geteuid() != args.run_uid: + raise SystemExit("failed to drop namespace setup privileges") + os.umask(0o077) + harness = Harness(args) + result = {"verdict": "FAIL", "suite": "stock-client-tailnet-lock-v1.102.0", "scenarios": harness.events} + try: + harness.scenario() + result["verdict"] = "PASS" + returncode = 0 + except (Failure, OSError, ValueError, KeyError, http.client.HTTPException) as exc: + result["failure"] = str(exc) + print("FAIL: " + str(exc), file=sys.stderr) + returncode = 1 + finally: + harness.close() + if args.result: + args.result.resolve().write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, sort_keys=True)) + return returncode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/integration/e2e/run.sh b/integration/e2e/run.sh new file mode 100755 index 0000000..dbfbe95 --- /dev/null +++ b/integration/e2e/run.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# Test-only. Prerequisites (acquisition/build may use the network): +# GO=/path/to/go GOTOOLCHAIN=auto sh integration/e2e/build-clients.sh +# GO=/path/to/go GOTOOLCHAIN=auto sh integration/headscale/build.sh +# sh tools/build-tkad.sh +# Then, on Linux with unprivileged user/network namespaces enabled: +# sh integration/e2e/run.sh [--keep] [--result /absolute/result.json] +# If user namespaces are prohibited, explicitly opt into namespace setup only: +# sh integration/e2e/run.sh --sudo-netns [--keep] [--result /absolute/result.json] +# This uses sudo -n, creates a NEW network namespace with loopback and a dummy +# link (no egress), then drops all UID/GID privileges to the invoking user before +# creating state or launching any daemon. No implicit sudo or host-network fallback. +# Requires python3, util-linux unshare, iproute2 ip. Never uses the host tailnet, +# Docker, a host network interface, or a global tailscaled socket. +# --keep retains private temporary logs/state (including disposable private keys). +# Default cleanup removes only the directory created by this invocation. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) +for tool in unshare ip python3; do + command -v "$tool" >/dev/null || { printf 'NOT_RUN: required tool %s unavailable\n' "$tool" >&2; exit 77; } +done +OUTER=$(readlink /proc/self/ns/net) +BIN=${E2E_BIN_DIR:-"$ROOT/build/e2e"} +HS=${HEADSCALE_BIN:-"$ROOT/build/headscale"} +TKAD=${TKAD_BIN:-"$ROOT/build/tkad"} +if [ "${1:-}" = "--sudo-netns" ]; then + shift + UID_NOW=$(id -u) + GID_NOW=$(id -g) + [ "$UID_NOW" -ne 0 ] || { printf 'NOT_RUN: invoke --sudo-netns as the ordinary test user\n' >&2; exit 77; } + exec sudo -n unshare --net --pid --fork --kill-child \ + python3 "$ROOT/integration/e2e/lifecycle.py" --outer-netns "$OUTER" \ + --run-uid "$UID_NOW" --run-gid "$GID_NOW" \ + --bin-dir "$BIN" --headscale "$HS" --tkad "$TKAD" "$@" +fi +exec unshare --user --map-root-user --net --pid --fork --kill-child \ + python3 "$ROOT/integration/e2e/lifecycle.py" --outer-netns "$OUTER" \ + --bin-dir "$BIN" --headscale "$HS" --tkad "$TKAD" "$@" diff --git a/integration/headscale/README.md b/integration/headscale/README.md new file mode 100644 index 0000000..28bbf9e --- /dev/null +++ b/integration/headscale/README.md @@ -0,0 +1,303 @@ +# Headscale adapter + +`headscale.patch` applies to Headscale **v0.29.6**, commit +`a2b1d7863926834e94479dcdd91ab344a9356bd0` (see `headscale.pin`). No fork is +vendored. The patch adds Go transport/authentication glue to the existing +Headscale server. TKA parsing, signatures, authority transitions and durable +accepted signatures remain in the Omega daemon. + +## Build + +From the Omnet checkout, with Git, a Go launcher supporting automatic toolchain +selection, and network access to GitHub and the Go module proxy: + +```sh +GO=/path/to/go sh integration/headscale/build.sh +# output: build/headscale (override with HEADSCALE_OUTPUT) +sh tools/build-tkad.sh +``` + +The builder clones the pinned tag into a disposable directory, verifies its +commit, applies the patch, and builds using `go1.27.3` and the patched module +checksums. It removes only its own temporary checkout. Dependencies are not +vendored. Headscale requires Go 1.27.3. Its original x/tools v0.49.0 cannot read +that compiler's V5 export data, so the patch pins x/tools v0.50.0 and includes +regenerated Node views/clones. Re-generation requires Go on `PATH`: +`go generate ./hscontrol/types` in the patched source. + +## Isolated operation + +Provision tkad exactly as described in `cmd/tkad/README.md`, then start both +processes as the **same UID**, in the same network namespace. Use private state, +private sockets and an isolated Headscale configuration, not an existing tailnet. +The two required adapter settings are environment variables, not YAML keys: + +```sh +OMNET_TKAD_SOCKET=/absolute/private/tkad/tkad.sock \ +OMNET_TKAD_ADMIN_USER_ID=1 \ + build/headscale --config /absolute/private/headscale.yaml serve +``` + +`OMNET_TKAD_ADMIN_USER_ID` must be the explicitly selected numeric Headscale user +ID. The example value `1` is not a default. It may be configured before that user +is created; the isolated E2E harness creates the user and checks the returned ID. +Only currently unexpired, untagged nodes owned by that user receive the admin +assertion. Noise machine identity and the current unique node key must both match. A body +cannot assert a user, NodeID or administrator status. Setting only one variable +is an error. Setting neither leaves ordinary upstream Headscale behavior **only on +a database that has never used this adapter**; once adapter state exists (a +checkpoint row or any node with a tailnet-lock key), the server refuses to start +instead of publishing maps without TKA state. + +Headscale still needs a nonempty DERP map, even in isolation. The E2E harness +supplies a private region and private client sockets; it never uses the live +Tailscale socket. See `integration/e2e/` for the runnable stock-client scenario. + +## Persistence and failure behavior + +The patch adds `nodes.tka_key`, `nodes.tka_signature` and a one-row +`omnet_checkpoints` table through an append-only migration. NLKey and the pending +submitted NKS are committed with Headscale's desired registration tuple, including +interactive auth callbacks. The pending signature is an outbox, **not** a trusted +map signature. Only a tkad snapshot supplies map signatures. + +A shared publication barrier serializes identity changes, reconciliation, +Noise/admin resolution and map-frame construction. Reconciliation reads committed +SQL, rejects ambiguous or speculative identities, removes daemon orphans and +vacates obsolete keys before claiming desired keys, including key-reuse cycles +after an outage. Accepted-signature readback resolves an ambiguous IPC outcome +without replaying a historical signature after key removal. An unchanged registry +causes no upsert, including after adapter restart, so it does not cancel pending +initialization. + +A definitively rejected pending signature is retried without a signature. Only +after that unsigned tuple succeeds is the rejected outbox cleared. A new key is +then unsigned; an unchanged key retains its existing Omega-accepted signature. +The submitting registration gets an explicit signature error, but unrelated +nodes keep working. IPC authentication failures, failed unsigned retries, 5xx +and lost replies remain fail-closed and retain the outbox for recovery. + +All eight raw GET RPC bodies and replies are forwarded without re-encoding. +Initial, self, peer, changed-peer, non-streaming and queued map responses use one +fresh daemon snapshot. Key-only patches become full maps so an unsigned new key +cannot retain an old signature through JSON omission. Stale sessions cannot +restore an old node key through MapRequest. Revision changes wake streams even +when the authority head is unchanged (for example, signing a node). +Non-key patches never carry signatures. Each stream writes its frozen frames in +order after releasing the global barrier, with bounded writes and a stop deadline +that cannot be lengthened by a queued frame. Client cancellation does not mark +the daemon unhealthy. Interactive reauthentication retains the signature challenge +and then requires upstream authentication; the old Noise identity never silently +rotates the key or replaces an AuthURL. + +Daemon connection/read/shape failures block publication and close existing map +streams; no stale-cache, empty-signature, disabled-state or nil-TKAInfo fallback +is used. An absent daemon refuses server startup. A reachable daemon plus a +pending registration permits authenticated retries and administrative repair while +unresolved transport/registry failures block map/TKA publication. Older Headscale +nodes without NLKey must re-register; there is no invented rotation key. A committed +identity whose outbox cannot be reconciled is not reported as successful registration. +Post-commit policy refresh runs even when reconciliation will reject registration. + +The durable observed-revision floor rejects an empty/older daemon snapshot after +adapter restart. It is **not authenticated rollback protection**, and cannot +identify an arbitrary different authority with a higher revision. Back up and +restore the Headscale database and tkad directory together. Same-UID processes +and root are trusted and can alter either store. Outages do not revoke already +installed peer connectivity. This is not a separate-UID deployment profile or a +production security audit. + +Limits remain one tailnet, 64 nodes, 128 AUMs and 64-KiB IPC JSON messages. Every +committed mutation must still be servable through the 64-KiB registry response: +an accepted node signature is stored in canonical form, so ignored CBOR fields +cannot pad it, and a candidate that would exceed the response limit is rejected +with 413 before it is persisted. A saturated registration or map admission +answers 503 instead of queueing on the publication barrier, and a TKA RPC from +an unregistered Noise identity is refused before any daemon work. IPC and +raw RPC read/write phases have absolute deadlines; a bounded serial daemon and +publication barrier trade throughput for simple ordering. New registrations beyond +64, zero node keys, duplicate keys even across users on one machine, and signatures +above 48,768 raw bytes are rejected before persistence. + +## Validation + +Focused adapter regressions, upstream control/state/mapper/types suites, SQLite +migration tests and the isolated stock-client lifecycle passed. Reproduce focused tests +in a checkout at the pinned commit with `headscale.patch` applied: + +```sh +GOTOOLCHAIN=go1.27.3 go test -count=1 -run '^TestOmnet' ./hscontrol ./hscontrol/state +GOTOOLCHAIN=go1.27.3 go test -count=1 -run '^TestSQLite' ./hscontrol/db +``` + +Build and run the stock clients separately from the library suite: + +```sh +GO=/path/to/go sh integration/e2e/build-clients.sh +GO=/path/to/go sh integration/headscale/build.sh +sh tools/build-tkad.sh +sh integration/e2e/run.sh --result /tmp/omnet-e2e-result.json +# If user namespaces are prohibited, explicitly request privileged namespace setup: +sh integration/e2e/run.sh --sudo-netns --result /tmp/omnet-e2e-result.json +``` + +The launcher requires Linux `unshare`, `ip` and Python3. It creates a fresh network +namespace with loopback and a dummy link, no egress or host interfaces. Privileged +setup drops UID/GID privileges before starting the daemons. Clients use private state +and explicit sockets. Default cleanup removes the invocation's disposable state; +`--keep` retains it, including private test keys, for debugging. Do not publish those logs. +The receipt includes only scenario verdicts and public artifact hashes. + +The successful lifecycle reports 13 PASS records including provenance. It covers +initialization, unsigned-peer filtering, signing, authenticated rotation, authority +removal and re-signing, restart recovery, non-owner denial, daemon outage/recovery, +disablement and disabled restart. This is netmap admission evidence, not packet delivery. + +The tests exercise durable outbox/revision persistence, committed identity +refusal, same-machine cross-user duplicate-key prevention, expired-owner denial, +historical-signature readback, definitive rejection isolation, ambiguous replies, +unchanged restart reconciliation, interactive authentication, old-map rollback +refusal, full-node signature clearing, signature-free non-key patches, cancelled +requests, stopped/slow writers, key-reuse recovery cycles, policy refresh after +reconciliation failure, and map outage closure. Transport fixtures do not replace +the real Omega suite or stock-client E2E. The parent integration run supplies those +receipts. For broader upstream regression coverage run the normal Headscale unit +suites separately; Docker-based Headscale integration tests are not required by +this adapter's isolated stock-client harness. + +## Deployment gate and recovery plan + +The [Tailworm disclosure](https://tailworm.com/) also describes SSH forwarding, +app connectors, unauthenticated control-server exhaustion, hostile DERP responses +and Serve exposure. This adapter does not patch those components. Signature-based +node admission does not stop an already authorized compromised device from using +its existing permissions, or protect signing keys on a compromised endpoint. +Qualify upstream fixes and feature-specific hardening separately; passing this +suite must never be reported as “Tailworm fixed” or “the network is secure.” + +**Not approved for live deployment.** The isolated lifecycle is a control-plane +receipt, not a production security audit or proof of packet delivery. Keep this +adapter off the live controller until the following gates have evidence: + +- **Every committed node must carry an NLKey before activation, and the roster + must fit the profile (at most 64 nodes, unique node keys, no ambiguous + identity).** Reconciliation fails as a whole while any node lacks one, which + closes map streams and answers new map polls 503 for the entire tailnet until + that node re-registers or is deleted. Nodes created before this migration have + a null NLKey, so activating in place over an existing database blackouts + control until every node, including offline ones, re-registers. A running + client may not re-register on its own. Verify with `SELECT` on `nodes` that no + row has a null `tka_key` and that the count is within 64, immediately before + the change window. +- Inventory the actual clients, registered nodes (including offline nodes), NLKeys, + authority history and expected message sizes against this bounded profile. + The tested client is v1.102.0; other versions need their own qualification. + Every accepted node signature occupies part of one 64-KiB registry response. + A mutation that would not fit is now rejected with 413 instead of being + committed unreadable, so qualification must show the real roster plus signature + history stays below that response limit for the operational horizon. The 128-AUM + authority limit has no compaction path; plan for it before exhaustion. +- Establish and test an administration path independent of this tailnet, including + console or direct SSH access. An existing tailnet SSH session is not a recovery + path: controller loss, key rotation or signature rejection can prevent reconnect. +- Select the owner user by numeric ID and enumerate every unexpired, untagged + device that will receive administrator privileges. Ownership is user-wide, not + restricted to one operator device; a newly enrolled unsigned owner device also + qualifies, so its enrollment credentials are part of the administration boundary. +- Keep at least two separately held signing keys and protect the disablement + secret offline. Do not store signing private keys or recovery secrets on the + controller. Test operator recovery using disposable keys first. A nonempty + `SupportDisablement` value submitted at `init/finish` is stored in the tkad + snapshot, so a same-UID controller compromise can read and use it: either + accept that, or never submit it and keep the secret off the controller + entirely (the client then needs its own copy for `tailscale lock disable`). +- Rehearse the database migration, paired backup/restore, client reconnect and + packet-level signed/unsigned-peer behavior in a separate representative network. + Include the phone and the actual SSH path before scheduling a live change. +- Review the same-UID trust boundary and untrusted-client availability limits. + Controller compromise grants access to tkad state; Omega is not a sandbox for + the controller. Source review does not establish constant-time behavior. + Registration and map admission are bounded (a saturated adapter answers 503 + "busy" instead of queueing), and a TKA RPC from an unregistered Noise identity + is refused before any shared persistence work. That bounds amplification; it + does not make the control plane immune to load. +- On SQLite, a stock v0.29.6 binary refuses a migrated database at its schema + check, and the migration has no rollback. Treat the adapter as a one-way + migration for that database: keep the original binary and pre-migration + database together, and rebase and re-qualify the patch for every Headscale + upgrade. PostgreSQL is unqualified and does not perform that schema check, so + it would start stock and silently drop Tailnet Lock state. +- Run tkad and Headscale as separate units under the same UID, in the same + network namespace, with tkad started first. Never put `--init` in a unit file. + Handle the daemon's exit codes distinctly: 73 is a refused start (do not + restart in a loop), 74 is a deliberate storage fail-stop, 76 is a failed + rollover or exec. Restored state directories must be 0700/0600, owned by the + service UID, without hard links or a symlinked final component, and no tkad + process may be running while the directory is copied. + +### Quiescent backup and restore + +This is the required ordering for a rehearsal, not a claim that a live restore +has been tested: + +1. Stop Headscale and prevent its automatic restart so no registry or TKA request + can be submitted. Stop tkad and prevent its automatic restart. +2. Capture a consistent Headscale database using the database's supported backup + mechanism, plus the tkad state directory, controller configuration, policy, + artifact hashes and both adapter settings. Keep SQLite WAL/journal consistency; + copying a live main database file alone is not a backup. +3. Keep the pair together, access-restricted and labelled with one capture ID. + The snapshot includes secrets. Do not put it in this public repository. +4. Restore both stores into an isolated environment under trusted ancestors and + the intended UID/modes. Never restore one store alone, decrement the observed + revision floor, or use `--init` to bypass missing/corrupt state. +5. Start tkad without `--init`, then Headscale with both adapter settings. Check + the authority head, roster and accepted signatures, then reconnect clients. + A checksum-valid backup is not proof that clients accept its authority history. + +The revision floor detects some stale restores; it is not authentication of the +backup. Rolling both stores back can evade that floor and conflict with client +state. If a rehearsal cannot reconcile the saved authority with current clients, +keep publication stopped and recover the correct stores rather than resetting +the authority. + +### Change window and interruption + +Before enabling Tailnet Lock, preserve the pre-migration database and original +controller binary/configuration. A pre-activation rollback restores that original +set, not an older binary against the migrated database. + +After activation, there is **no transparent downgrade** to ordinary Headscale: +removing the adapter variables does not safely undo the authority already stored +by clients. On SQLite a stock binary refuses the migrated database outright; on +PostgreSQL it would start and silently drop Tailnet Lock state. To make that +failure explicit, the adapter now refuses to start when both settings are absent +and the database already records adapter state (a checkpoint row or any node with +a tailnet-lock key). Prefer repair/roll-forward using the paired stores. +Disabling Tailnet Lock is an explicit security downgrade requiring the owner's +approval, a valid recovery secret and verified client convergence. Disablement is +permanent for that database: a disabled authority cannot be reinitialized, and a +fresh `--init` directory starts at revision 0, which the durable floor rejects. +Re-enabling Tailnet Lock therefore needs a new Headscale database. Run `disable` +only while the adapter is active, so clients can fetch the stored disablement +secret; a client that misses it needs `tailscale lock local-disable` locally. +Do not present disablement as a reversible toggle. + +The revision floor catches a lower daemon revision, not an arbitrary different +authority at an equal or higher revision, and it advances before reconciliation. +Restoring an older database beside a newer tkad therefore removes the nodes and +signatures the older database lacks. That is why the stores must always be +restored together from one capture. + +A controller restart interrupts control-plane requests and map streams. Existing +peer paths may continue, but new connections, relay-dependent paths, registration, +rotation and SSH reconnect are not guaranteed. A tkad outage blocks publication; +it does not revoke existing data-plane connectivity. No live-service interruption +is part of the isolated build/review workflow. + +## Third-party notices + +The patch includes context from Headscale and regenerated Tailscale-derived view +code. Their BSD-3-Clause notices are `headscale.LICENSE` and `tailscale.LICENSE`. +New Omnet glue is covered by the repository license. No upstream cryptographic +implementation is added to Headscale by this patch. diff --git a/integration/headscale/build.sh b/integration/headscale/build.sh new file mode 100755 index 0000000..d258a50 --- /dev/null +++ b/integration/headscale/build.sh @@ -0,0 +1,28 @@ +#!/bin/sh +set -eu +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH= cd -- "$here/../.." && pwd) +. "$here/headscale.pin" +go=${GO:-go} +go=$(command -v "$go") +case "$go" in /*) ;; *) go=$(pwd)/$go ;; esac +PATH=$(dirname -- "$go"):$PATH +GOTOOLCHAIN=$HEADSCALE_GO_TOOLCHAIN +export PATH GOTOOLCHAIN +out=${HEADSCALE_OUTPUT:-$root/build/headscale} +case "$out" in /*) ;; *) out=$(pwd)/$out ;; esac +work=$(mktemp -d "${TMPDIR:-/tmp}/omnet-headscale-build.XXXXXX") +trap 'rm -rf -- "$work"' EXIT HUP INT TERM +git clone --quiet --depth 1 --branch "$HEADSCALE_VERSION" "$HEADSCALE_URL" "$work/source" +actual=$(git -C "$work/source" rev-parse HEAD) +if [ "$actual" != "$HEADSCALE_COMMIT" ]; then + printf '%s\n' 'Headscale tag no longer matches pinned commit' >&2 + exit 1 +fi +git -C "$work/source" apply "$here/headscale.patch" +mkdir -p -- "$(dirname -- "$out")" +( + cd -- "$work/source" + "$go" build -trimpath -o "$out" ./cmd/headscale +) +printf '%s\n' "$out" diff --git a/integration/headscale/headscale.LICENSE b/integration/headscale/headscale.LICENSE new file mode 100644 index 0000000..dfa1a5c --- /dev/null +++ b/integration/headscale/headscale.LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2020, Juan Font +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/integration/headscale/headscale.patch b/integration/headscale/headscale.patch new file mode 100644 index 0000000..183cd8f --- /dev/null +++ b/integration/headscale/headscale.patch @@ -0,0 +1,2764 @@ +diff --git a/go.mod b/go.mod +index 6b96022..0067eae 100644 +--- a/go.mod ++++ b/go.mod +@@ -2,6 +2,23 @@ module github.com/juanfont/headscale + + go 1.27.3 + ++// NOTE: modernc sqlite has a fragile dependency ++// chain and it is important that they are updated ++// in lockstep to ensure that they do not break ++// some architectures and similar at runtime: ++// https://github.com/juanfont/headscale/issues/2188 ++// ++// Fragile libc dependency: ++// https://pkg.go.dev/modernc.org/sqlite#hdr-Fragile_modernc_org_libc_dependency ++// https://gitlab.com/cznic/sqlite/-/issues/177 ++// ++// To upgrade, determine the new SQLite version to ++// be used, and consult the `go.mod` file: ++// https://gitlab.com/cznic/sqlite/-/blob/master/go.mod ++// to find ++// the appropriate `libc` version, then upgrade them ++// together, e.g: ++// go get modernc.org/libc@v1.55.3 modernc.org/sqlite@v1.33.1 + require ( + github.com/arl/statsviz v0.8.0 + github.com/cenkalti/backoff/v5 v5.0.3 +@@ -54,43 +71,12 @@ require ( + gopkg.in/yaml.v3 v3.0.1 + gorm.io/driver/postgres v1.6.0 + gorm.io/gorm v1.31.1 ++ modernc.org/sqlite v1.52.0 + pgregory.net/rapid v1.3.0 + tailscale.com v1.102.0 + zombiezen.com/go/postgrestest v1.0.1 + ) + +-// NOTE: modernc sqlite has a fragile dependency +-// chain and it is important that they are updated +-// in lockstep to ensure that they do not break +-// some architectures and similar at runtime: +-// https://github.com/juanfont/headscale/issues/2188 +-// +-// Fragile libc dependency: +-// https://pkg.go.dev/modernc.org/sqlite#hdr-Fragile_modernc_org_libc_dependency +-// https://gitlab.com/cznic/sqlite/-/issues/177 +-// +-// To upgrade, determine the new SQLite version to +-// be used, and consult the `go.mod` file: +-// https://gitlab.com/cznic/sqlite/-/blob/master/go.mod +-// to find +-// the appropriate `libc` version, then upgrade them +-// together, e.g: +-// go get modernc.org/libc@v1.55.3 modernc.org/sqlite@v1.33.1 +-require ( +- modernc.org/libc v1.72.3 // indirect +- modernc.org/mathutil v1.7.1 // indirect +- modernc.org/memory v1.11.0 // indirect +- modernc.org/sqlite v1.52.0 +-) +- +-// NOTE: gvisor must be updated in lockstep with +-// tailscale.com. The version used here should match +-// the version required by the tailscale.com dependency. +-// To find the correct version, check tailscale.com's +-// go.mod file for the gvisor.dev/gvisor version: +-// https://github.com/tailscale/tailscale/blob/main/go.mod +-require gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8 // indirect +- + require ( + atomicgo.dev/cursor v0.2.0 // indirect + atomicgo.dev/keyboard v0.2.10 // indirect +@@ -245,11 +231,21 @@ require ( + golang.org/x/term v0.46.0 // indirect + golang.org/x/text v0.42.0 // indirect + golang.org/x/time v0.15.0 // indirect +- golang.org/x/tools v0.49.0 // indirect ++ golang.org/x/tools v0.50.0 // indirect + golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect + golang.zx2c4.com/wireguard/windows v0.5.3 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect ++ // NOTE: gvisor must be updated in lockstep with ++ // tailscale.com. The version used here should match ++ // the version required by the tailscale.com dependency. ++ // To find the correct version, check tailscale.com's ++ // go.mod file for the gvisor.dev/gvisor version: ++ // https://github.com/tailscale/tailscale/blob/main/go.mod ++ gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8 // indirect + k8s.io/client-go v0.34.0 // indirect ++ modernc.org/libc v1.72.3 // indirect ++ modernc.org/mathutil v1.7.1 // indirect ++ modernc.org/memory v1.11.0 // indirect + sigs.k8s.io/yaml v1.6.0 // indirect + software.sslmate.com/src/go-pkcs12 v0.4.0 // indirect + ) +diff --git a/go.sum b/go.sum +index 07b0670..8ec874d 100644 +--- a/go.sum ++++ b/go.sum +@@ -610,6 +610,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc + golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= + golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= + golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= ++golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= ++golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= + golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= + golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg= + golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= +diff --git a/hscontrol/app.go b/hscontrol/app.go +index 864252f..654d7e0 100644 +--- a/hscontrol/app.go ++++ b/hscontrol/app.go +@@ -98,6 +98,7 @@ type Headscale struct { + state *state.State + noisePrivateKey *key.MachinePrivate + ephemeralGC *db.EphemeralGarbageCollector ++ tkad *tkaAdapter + + DERPServer *derpServer.DERPServer + +@@ -642,6 +643,10 @@ func (h *Headscale) Serve() error { + Str("minimum_version", capver.TailscaleVersion(capver.MinSupportedCapabilityVersion)). + Msg("Clients with a lower minimum version will be rejected") + ++ if err := h.initTKA(); err != nil { ++ return fmt.Errorf("initializing omnet adapter: %w", err) ++ } ++ + h.mapBatcher = mapper.NewBatcherAndMapper(h.cfg, h.state) + + h.mapBatcher.Start() +@@ -701,6 +706,7 @@ func (h *Headscale) Serve() error { + defer scheduleCancel() + + go h.scheduledTasks(scheduleCtx) ++ go h.watchTKA(scheduleCtx) + + if zl.GlobalLevel() == zl.TraceLevel { + zerolog.RespLog = true +diff --git a/hscontrol/auth.go b/hscontrol/auth.go +index 7f50f80..0c05334 100644 +--- a/hscontrol/auth.go ++++ b/hscontrol/auth.go +@@ -331,6 +331,9 @@ func (h *Headscale) waitForFollowup( + case verdict = <-reg.WaitForAuth(): + } + } ++ if h.tkad != nil && verdict.Err != nil { ++ return nil, verdict.Err ++ } + + if verdict.Accept() { + if !verdict.Node.Valid() { +@@ -397,10 +400,12 @@ func registrationDataFromRequest( + } + + regData := &types.RegistrationData{ +- MachineKey: machineKey, +- NodeKey: req.NodeKey, +- Hostname: hostname, +- Hostinfo: req.Hostinfo, ++ MachineKey: machineKey, ++ NodeKey: req.NodeKey, ++ Hostname: hostname, ++ Hostinfo: req.Hostinfo, ++ TKAKey: req.NLKey, ++ TKASignature: append([]byte(nil), req.NodeKeySignature...), + } + + if !req.Expiry.IsZero() { +diff --git a/hscontrol/db/db.go b/hscontrol/db/db.go +index 824afb4..5836e3e 100644 +--- a/hscontrol/db/db.go ++++ b/hscontrol/db/db.go +@@ -808,6 +808,18 @@ WHERE tags IS NOT NULL AND tags != '[]' AND tags != '' AND tags != 'null' + }, + Rollback: func(db *gorm.DB) error { return nil }, + }, ++ { ++ ID: "202610251600-omnet-tka-registration", ++ Migrate: func(tx *gorm.DB) error { ++ if err := tx.Migrator().AddColumn(&types.Node{}, "TKAKey"); err != nil { ++ return err ++ } ++ if err := tx.Migrator().AddColumn(&types.Node{}, "TKASignature"); err != nil { ++ return err ++ } ++ return tx.Migrator().CreateTable(&types.OmnetCheckpoint{}) ++ }, ++ }, + }, + ) + +@@ -819,6 +831,7 @@ WHERE tags IS NOT NULL AND tags != '[]' AND tags != '' AND tags != 'null' + &types.APIKey{}, + &types.Node{}, + &types.Policy{}, ++ &types.OmnetCheckpoint{}, + ) + if err != nil { + return err +diff --git a/hscontrol/db/schema.sql b/hscontrol/db/schema.sql +index 781446c..95986af 100644 +--- a/hscontrol/db/schema.sql ++++ b/hscontrol/db/schema.sql +@@ -72,6 +72,8 @@ CREATE TABLE nodes( + machine_key text, + node_key text, + disco_key text, ++ tka_key text, ++ tka_signature blob, + + endpoints text, + host_info text, +@@ -112,3 +114,8 @@ CREATE TABLE database_versions( + version text NOT NULL, + updated_at datetime + ); ++ ++CREATE TABLE omnet_checkpoints( ++ id integer PRIMARY KEY AUTOINCREMENT, ++ revision integer ++); +diff --git a/hscontrol/mapper/batcher.go b/hscontrol/mapper/batcher.go +index e37daa0..c6facb7 100644 +--- a/hscontrol/mapper/batcher.go ++++ b/hscontrol/mapper/batcher.go +@@ -876,6 +876,12 @@ func (b *Batcher) MapResponseFromChange(id types.NodeID, ch change.Change) (*tai + } + } + ++// FullMapResponse builds a full response without requiring an existing stream. ++// The Omnet wire barrier uses this for non-stream reads and key-patch replacement. ++func (b *Batcher) FullMapResponse(id types.NodeID, version tailcfg.CapabilityVersion) (*tailcfg.MapResponse, error) { ++ return b.mapper.fullMapResponse(id, version) ++} ++ + // DebugNodeInfo contains debug information about a node's connections. + type DebugNodeInfo struct { + Connected bool `json:"connected"` +diff --git a/hscontrol/mapper/node_conn.go b/hscontrol/mapper/node_conn.go +index 9396854..f114ba0 100644 +--- a/hscontrol/mapper/node_conn.go ++++ b/hscontrol/mapper/node_conn.go +@@ -370,7 +370,13 @@ func (mc *multiChannelNodeConn) send(data *tailcfg.MapResponse) error { + ) + + for _, conn := range snapshot { +- err := conn.send(conn.withSSHPolicyDelta(conn.withSelfDelta(data))) ++ frame := data ++ // Omega decorates self signatures after this queue. Comparing the ++ // undecorated self would hide signature-only updates from that node. ++ if mc.mapper == nil || mc.mapper.state == nil || mc.mapper.state.TKAReconcile == nil { ++ frame = conn.withSelfDelta(frame) ++ } ++ err := conn.send(conn.withSSHPolicyDelta(frame)) + if err != nil { + lastErr = err + +diff --git a/hscontrol/noise.go b/hscontrol/noise.go +index 20b0889..f57647f 100644 +--- a/hscontrol/noise.go ++++ b/hscontrol/noise.go +@@ -168,6 +168,7 @@ func (h *Headscale) NoiseUpgradeHandler( + r.Route("/machine", func(r chi.Router) { + r.Post("/register", ns.RegistrationHandler) + r.Post("/map", ns.PollNetMapHandler) ++ ns.tkaRoutes(r) + + // SSH Check mode endpoint, consulted to validate if a given SSH connection should be accepted or rejected. + r.Get("/ssh/action/{src_node_id}/to/{dst_node_id}", ns.SSHActionHandler) +@@ -752,6 +753,11 @@ func (ns *noiseServer) PollNetMapHandler( + return + } + ++ if err := ns.headscale.tkaMapReady(req.Context()); err != nil { ++ http.Error(writer, errTKAUnavailable.Error(), http.StatusServiceUnavailable) ++ return ++ } ++ + nv, err := ns.getAndValidateNode(mapRequest) + if err != nil { + // The node is gone, but the client does not know that. Tailscale +@@ -761,7 +767,7 @@ func (ns *noiseServer) PollNetMapHandler( + // that says "deleted", so reuse the expiry signal headscale already + // sends for expired nodes. + // See: https://github.com/juanfont/headscale/issues/3410 +- if errors.Is(err, errNodeNotInStore) && mapRequest.Stream { ++ if errors.Is(err, errNodeNotInStore) && mapRequest.Stream && ns.headscale.tkad == nil { + expired := &tailcfg.MapResponse{ + Node: &tailcfg.Node{ + Key: mapRequest.NodeKey, +@@ -823,6 +829,13 @@ func (ns *noiseServer) RegistrationHandler( + return ®Req, regErr(err) + } + ++ resp, err = ns.headscale.registrationPrelude(req.Context(), regReq, ns.machineKey) ++ if err != nil { ++ return ®Req, regErr(err) ++ } ++ if resp != nil { ++ return ®Req, resp ++ } + resp, err = ns.headscale.handleRegister(req.Context(), regReq, ns.conn.Peer()) + if err != nil { + if httpErr, ok := errors.AsType[HTTPError](err); ok { +@@ -836,6 +849,12 @@ func (ns *noiseServer) RegistrationHandler( + return ®Req, regErr(err) + } + ++ if ns.headscale.tkad != nil && resp != nil && resp.MachineAuthorized && !resp.NodeKeyExpired && resp.AuthURL == "" { ++ if err := ns.headscale.state.TKARegisterCurrent(req.Context(), regReq, ns.machineKey); err != nil { ++ return ®Req, regErr(err) ++ } ++ } ++ + return ®Req, resp + }() + +diff --git a/hscontrol/poll.go b/hscontrol/poll.go +index 09b8ccd..8212f4c 100644 +--- a/hscontrol/poll.go ++++ b/hscontrol/poll.go +@@ -8,6 +8,7 @@ import ( + "fmt" + "math/rand/v2" + "net/http" ++ "sync" + "sync/atomic" + "time" + +@@ -51,6 +52,8 @@ type mapSession struct { + // writing is set while [mapSession.writeMap] runs, so + // [mapSession.stopFromBatcher] interrupts only a write that may be stuck. + writing atomic.Bool ++ // Serializes deadline changes with stopFromBatcher, never network writes. ++ writeDeadlineMu sync.Mutex + + keepAlive time.Duration + keepAliveTicker *time.Ticker +@@ -105,6 +108,8 @@ func (m *mapSession) resetKeepAlive() { + } + + func (m *mapSession) stopFromBatcher() { ++ m.writeDeadlineMu.Lock() ++ defer m.writeDeadlineMu.Unlock() + if m.cancelChClosed.CompareAndSwap(false, true) { + close(m.cancelCh) + +@@ -162,6 +167,17 @@ func (m *mapSession) serve() { + if m.isEndpointUpdate() { + m.w.WriteHeader(http.StatusOK) + mapResponseEndpointUpdates.WithLabelValues("ok").Inc() ++ return ++ } ++ if m.h.tkad != nil { ++ resp, err := m.h.mapBatcher.FullMapResponse(m.node.ID, m.capVer) ++ if err != nil { ++ httpError(m.w, err) ++ return ++ } ++ if err := m.writeMap(resp); err != nil { ++ httpError(m.w, err) ++ } + } + } + +@@ -312,11 +328,14 @@ func (m *mapSession) serveLongPoll() { + m.h.Change(mapReqChange) + m.h.Change(connectChanges...) + ++ tkaFailure := m.h.tkaFailure() + // Loop through updates and continuously send them to the + // client. + for { + // consume channels with update, keep alives or "batch" blocking signals + select { ++ case <-tkaFailure: ++ return + case <-m.cancelCh: + m.log.Trace().Caller().Msg("poll cancelled received") + mapResponseEnded.WithLabelValues("cancelled").Inc() +@@ -390,7 +409,7 @@ func (m *mapSession) writeMap(msg *tailcfg.MapResponse) error { + + startWrite := time.Now() + +- err := writeMapResponse(m.w, m.req.Compress, m.isStreaming(), msg) ++ err := m.writeTKAMap(msg) + if err != nil { + return err + } +@@ -414,9 +433,17 @@ func (m *mapSession) writeMap(msg *tailcfg.MapResponse) error { + // It is shared with the deleted-node path in [noiseServer.PollNetMapHandler], + // which has no [mapSession] to write through. + func writeMapResponse(w http.ResponseWriter, compress string, flush bool, msg *tailcfg.MapResponse) error { ++ data, err := encodeMapResponse(compress, msg) ++ if err != nil { ++ return err ++ } ++ return writeMapFrame(w, flush, data) ++} ++ ++func encodeMapResponse(compress string, msg *tailcfg.MapResponse) ([]byte, error) { + jsonBody, err := json.Marshal(msg) + if err != nil { +- return fmt.Errorf("marshalling map response: %w", err) ++ return nil, fmt.Errorf("marshalling map response: %w", err) + } + + if compress == util.ZstdCompression { +@@ -427,8 +454,11 @@ func writeMapResponse(w http.ResponseWriter, compress string, flush bool, msg *t + //nolint:gosec // G115: JSON response size will not exceed uint32 max + binary.LittleEndian.PutUint32(data, uint32(len(jsonBody))) + data = append(data, jsonBody...) ++ return data, nil ++} + +- _, err = w.Write(data) ++func writeMapFrame(w http.ResponseWriter, flush bool, data []byte) error { ++ _, err := w.Write(data) + if err != nil { + return err + } +diff --git a/hscontrol/state/state.go b/hscontrol/state/state.go +index 293e6ba..2f43e70 100644 +--- a/hscontrol/state/state.go ++++ b/hscontrol/state/state.go +@@ -141,6 +141,10 @@ type sshCheckPair struct { + // See [policy.PolicyManager] for policy evaluation and [NodeStore] for the + // in-memory node cache. + type State struct { ++ // TKA publishes only committed identities. Set once before Serve. ++ TKAMu sync.Mutex ++ TKAReconcile func(context.Context, types.NodeID, []byte) error ++ + // cfg holds the current Headscale configuration + cfg *types.Config + +@@ -342,6 +346,7 @@ func (s *State) DERPMap() tailcfg.DERPMapView { + // ReloadPolicy reloads the access control policy and triggers auto-approval if changed. + // Returns the resulting [change.Change] slice when the policy or routes changed. + func (s *State) ReloadPolicy() ([]change.Change, error) { ++ defer s.lockTKA()() + pol, err := hsdb.PolicyBytes(s.db.DB, s.cfg) + if err != nil { + return nil, fmt.Errorf("loading policy: %w", err) +@@ -471,6 +476,7 @@ func (s *State) UpdateUser(userID types.UserID, updateFn func(*types.User) error + // It also updates the policy manager to ensure ACL policies referencing the deleted + // user are re-evaluated immediately, fixing issue #2967. + func (s *State) DeleteUser(userID types.UserID) (change.Change, error) { ++ defer s.lockTKA()() + err := s.db.DestroyUser(userID) + if err != nil { + return change.Change{}, err +@@ -599,6 +605,7 @@ func (s *State) persistNodeAndRefreshPolicy(node types.NodeView) (types.NodeView + } + + func (s *State) SaveNode(node types.NodeView) (types.NodeView, change.Change, error) { ++ defer s.lockTKA()() + // Update [NodeStore] first + nodePtr := node.AsStruct() + +@@ -614,6 +621,7 @@ func (s *State) SaveNode(node types.NodeView) (types.NodeView, change.Change, er + // must publish the changes before handling the error so live sessions are + // still torn down after a committed deletion. + func (s *State) DeleteNode(node types.NodeView) ([]change.Change, error) { ++ defer s.lockTKA()() + s.persistMu.Lock() + + err := s.db.DeleteNode(node.AsStruct()) +@@ -702,6 +710,7 @@ func (s *State) Connect(id types.NodeID) ([]change.Change, uint64) { + // [NodeStore.UpdateNode] closure, making them atomic against + // concurrent connects. epoch identifies the session for logging only. + func (s *State) Disconnect(id types.NodeID, epoch uint64) ([]change.Change, error) { ++ defer s.lockTKA()() + var wentOffline bool + + node, ok := s.nodeStore.UpdateNode(id, func(n *types.Node) { +@@ -912,6 +921,7 @@ func (s *State) ListEphemeralNodes() views.Slice[types.NodeView] { + // SetNodeExpiry updates the expiration time for a node. + // If expiry is nil, the node's expiry is disabled (node will never expire). + func (s *State) SetNodeExpiry(nodeID types.NodeID, expiry *time.Time) (types.NodeView, change.Change, error) { ++ defer s.lockTKA()() + var onlineChanged bool + + // Update [NodeStore] before database to ensure consistency. The [NodeStore] update +@@ -958,6 +968,7 @@ func (s *State) SetNodeExpiry(nodeID types.NodeID, expiry *time.Time) (types.Nod + // Once a node is tagged, it cannot be un-tagged (only tags can be changed). + // Setting tags clears UserID since tagged nodes are owned by their tags. + func (s *State) SetNodeTags(nodeID types.NodeID, tags []string) (types.NodeView, change.Change, error) { ++ defer s.lockTKA()() + if len(tags) == 0 { + return types.NodeView{}, change.Change{}, types.ErrCannotRemoveAllTags + } +@@ -1022,6 +1033,11 @@ func (s *State) SetNodeTags(nodeID types.NodeID, tags []string) (types.NodeView, + + // SetApprovedRoutes sets the network routes that a node is approved to advertise. + func (s *State) SetApprovedRoutes(nodeID types.NodeID, routes []netip.Prefix) (types.NodeView, change.Change, error) { ++ defer s.lockTKA()() ++ return s.setApprovedRoutes(nodeID, routes) ++} ++ ++func (s *State) setApprovedRoutes(nodeID types.NodeID, routes []netip.Prefix) (types.NodeView, change.Change, error) { + // TODO(kradalby): In principle we should call the AutoApprove logic here + // because even if the CLI removes an auto-approved route, it will be added + // back automatically. +@@ -1062,6 +1078,7 @@ func (s *State) SetApprovedRoutes(nodeID types.NodeID, routes []netip.Prefix) (t + // auto-sanitisation) and collisions error out rather than silently + // bumping a user-facing label. See HOSTNAME.md for the CLI contract. + func (s *State) RenameNode(nodeID types.NodeID, newName string) (types.NodeView, change.Change, error) { ++ defer s.lockTKA()() + // Validate the label AND that the resulting FQDN fits MaxHostnameLength: + // a valid 63-char label can still overflow under a long base_domain, and + // an unmappable name would break this node and its peers (issue #3346). +@@ -1653,6 +1670,8 @@ type newNodeParams struct { + User types.User + MachineKey key.MachinePublic + NodeKey key.NodePublic ++ TKAKey key.NLPublic ++ TKASignature []byte + DiscoKey key.DiscoPublic + Hostname string + Hostinfo *tailcfg.Hostinfo +@@ -1747,13 +1766,16 @@ func (s *State) applyAuthNodeUpdate(params authNodeUpdateParams) (types.NodeView + // re-authenticating node could rotate its key to a victim's and poison + // the NodeStore NodeKey index (denying the victim service). + if existing, ok := s.nodeStore.GetNodeByNodeKey(regData.NodeKey); ok && +- existing.MachineKey() != regData.MachineKey { ++ (existing.MachineKey() != regData.MachineKey || ++ (s.TKAReconcile != nil && existing.ID() != params.ExistingNode.ID())) { + return types.NodeView{}, false, ErrNodeKeyInUse + } + + // Update existing node in [NodeStore] - validation passed, safe to mutate + before, updatedNodeView, ok := s.nodeStore.UpdateNodeDiff(params.ExistingNode.ID(), func(node *types.Node) { + node.NodeKey = regData.NodeKey ++ node.TKAKey = regData.TKAKey ++ node.TKASignature = slices.Clone(regData.TKASignature) + node.DiscoKey = regData.DiscoKey + node.Hostname = params.Hostname + +@@ -1859,9 +1881,9 @@ func (s *State) applyAuthNodeUpdate(params authNodeUpdateParams) (types.NodeView + // is garbage-collected. Writing NULL can never cause an FK error, so include + // the column only in that clearing case; the other transitions keep the + // #2862-safe column set untouched. +- updateColumns := nodeUpdateColumns ++ updateColumns := append(slices.Clone(nodeUpdateColumns), "TKAKey", "TKASignature") + if !updatedNodeView.AuthKeyID().Valid() { +- updateColumns = append(slices.Clone(nodeUpdateColumns), "AuthKeyID") ++ updateColumns = append(updateColumns, "AuthKeyID") + } + + _, err := hsdb.Write(s.db.DB, func(tx *gorm.DB) (*types.Node, error) { +@@ -1873,6 +1895,7 @@ func (s *State) applyAuthNodeUpdate(params authNodeUpdateParams) (types.NodeView + return nil, nil //nolint:nilnil // side-effect only write + }) + if err != nil { ++ s.nodeStore.PutNode(*before.AsStruct()) + return types.NodeView{}, false, err + } + +@@ -1893,6 +1916,20 @@ func (s *State) applyAuthNodeUpdate(params authNodeUpdateParams) (types.NodeView + // createAndSaveNewNode creates a new node, allocates IPs, saves to DB, and adds to [NodeStore]. + // It preserves netinfo from an existing node if one is provided (for faster DERP connectivity). + func (s *State) createAndSaveNewNode(params newNodeParams) (types.NodeView, error) { ++ if s.TKAReconcile != nil { ++ nodes, err := s.TKACommittedNodes(context.Background()) ++ if err != nil { ++ return types.NodeView{}, err ++ } ++ if len(nodes) >= 64 || params.TKAKey.IsZero() { ++ return types.NodeView{}, errors.New("omnet registration requires NLKey and capacity below 64") ++ } ++ for _, n := range nodes { ++ if n.NodeKey == params.NodeKey { ++ return types.NodeView{}, ErrNodeKeyInUse ++ } ++ } ++ } + // Preserve NetInfo from existing node if available + if params.Hostinfo != nil { + params.Hostinfo.NetInfo = preserveNetInfo( +@@ -1921,6 +1958,8 @@ func (s *State) createAndSaveNewNode(params newNodeParams) (types.NodeView, erro + Hostname: params.Hostname, + MachineKey: params.MachineKey, + NodeKey: params.NodeKey, ++ TKAKey: params.TKAKey, ++ TKASignature: slices.Clone(params.TKASignature), + DiscoKey: params.DiscoKey, + Hostinfo: params.Hostinfo, + Endpoints: params.Endpoints, +@@ -2213,6 +2252,7 @@ func (s *State) HandleNodeFromAuthPath( + expiry *time.Time, + registrationMethod string, + ) (types.NodeView, change.Change, error) { ++ defer s.lockTKA()() + // Get the registration entry from cache + regEntry, ok := s.GetAuthCacheEntry(authID) + if !ok { +@@ -2342,12 +2382,6 @@ func (s *State) HandleNodeFromAuthPath( + } + } + +- // Signal to waiting clients +- regEntry.FinishAuth(types.AuthVerdict{Node: finalNode}) +- +- // Remove from registration cache +- s.authCache.Remove(authID) +- + // Update policy managers + usersChange, err := s.updatePolicyManagerUsers() + if err != nil { +@@ -2358,6 +2392,16 @@ func (s *State) HandleNodeFromAuthPath( + if err != nil { + return finalNode, change.NodeAdded(finalNode.ID()), fmt.Errorf("updating policy manager nodes: %w", err) + } ++ if err := s.reconcileTKA(finalNode.ID(), regData.TKASignature); err != nil { ++ regEntry.FinishAuth(types.AuthVerdict{Err: err}) ++ return types.NodeView{}, change.Change{}, err ++ } ++ ++ // Signal to waiting clients ++ regEntry.FinishAuth(types.AuthVerdict{Node: finalNode}) ++ ++ // Remove from registration cache ++ s.authCache.Remove(authID) + + policyChanged := !usersChange.IsEmpty() || !nodesChange.IsEmpty() + +@@ -2388,6 +2432,8 @@ func (s *State) createNewNodeFromAuth( + User: *user, + MachineKey: regData.MachineKey, + NodeKey: regData.NodeKey, ++ TKAKey: regData.TKAKey, ++ TKASignature: regData.TKASignature, + DiscoKey: regData.DiscoKey, + Hostname: hostname, + Hostinfo: validHostinfo, +@@ -2467,6 +2513,7 @@ func (s *State) HandleNodeFromPreAuthKey( + regReq tailcfg.RegisterRequest, + machineKey key.MachinePublic, + ) (types.NodeView, change.Change, error) { ++ defer s.lockTKA()() + // Serialise registration for this machine so concurrent restarts resolve + // to a single node rather than racing the find-then-create section. + defer s.lockRegistration(machineKey)() +@@ -2609,7 +2656,8 @@ func (s *State) HandleNodeFromPreAuthKey( + // re-registering node could rotate its key to a victim's and poison the + // NodeStore NodeKey index, denying the victim service. + if existing, ok := s.nodeStore.GetNodeByNodeKey(regReq.NodeKey); ok && +- existing.MachineKey() != machineKey { ++ (existing.MachineKey() != machineKey || ++ (s.TKAReconcile != nil && existing.ID() != existingNodeSameUser.ID())) { + return types.NodeView{}, change.Change{}, ErrNodeKeyInUse + } + +@@ -2622,6 +2670,8 @@ func (s *State) HandleNodeFromPreAuthKey( + // Update existing node - NodeStore first, then database + before, updatedNodeView, ok := s.nodeStore.UpdateNodeDiff(existingNodeSameUser.ID(), func(node *types.Node) { + node.NodeKey = regReq.NodeKey ++ node.TKAKey = regReq.NLKey ++ node.TKASignature = slices.Clone(regReq.NodeKeySignature) + node.Hostname = hostname + + // TODO(kradalby): We should ensure we use the same hostinfo and node merge semantics +@@ -2707,7 +2757,7 @@ func (s *State) HandleNodeFromPreAuthKey( + // (#2862), but re-registration presents a freshly-validated key, so + // its ID must be persisted here — otherwise a restart reloads the old + // key and any key-scoped property (e.g. Ephemeral) silently reverts. +- reregColumns := append(slices.Clone(nodeUpdateColumns), "AuthKeyID") ++ reregColumns := append(slices.Clone(nodeUpdateColumns), "AuthKeyID", "TKAKey", "TKASignature") + + err := tx.Select(reregColumns).Updates(updatedNodeView.AsStruct()).Error + if err != nil { +@@ -2817,6 +2867,8 @@ func (s *State) HandleNodeFromPreAuthKey( + User: pakUser, + MachineKey: machineKey, + NodeKey: regReq.NodeKey, ++ TKAKey: regReq.NLKey, ++ TKASignature: regReq.NodeKeySignature, + DiscoKey: key.DiscoPublic{}, // DiscoKey not available in RegisterRequest + Hostname: hostname, + Hostinfo: validHostinfo, +@@ -2841,6 +2893,9 @@ func (s *State) HandleNodeFromPreAuthKey( + if err != nil { + return finalNode, change.NodeAdded(finalNode.ID()), fmt.Errorf("updating policy manager nodes: %w", err) + } ++ if err := s.reconcileTKA(finalNode.ID(), regReq.NodeKeySignature); err != nil { ++ return types.NodeView{}, change.Change{}, err ++ } + + policyChanged := !usersChange.IsEmpty() || !nodesChange.IsEmpty() + +@@ -3076,6 +3131,13 @@ func isAutoDerivedGivenName(given, hostname string) bool { + // the mapRequestDelta classification, and (if the policy reads it) + // [types.NodeView.HasPolicyChange]. + func (s *State) UpdateNodeFromMapRequest(id types.NodeID, req tailcfg.MapRequest) (change.Change, error) { //nolint:gocyclo // central map-request reconciliation; the sequential branch flow reads clearer as one function than split across helpers ++ defer s.lockTKA()() ++ if s.TKAReconcile != nil { ++ current, ok := s.GetNodeByID(id) ++ if !ok || current.NodeKey() != req.NodeKey { ++ return change.Change{}, errors.New("stale map node identity") ++ } ++ } + log.Trace(). + Caller(). + Uint64(zf.NodeID, id.Uint64()). +@@ -3273,7 +3335,7 @@ func (s *State) UpdateNodeFromMapRequest(id types.NodeID, req tailcfg.MapRequest + // TODO(kradalby): approval should ride the map request write above. + // Writing it separately costs a second NodeStore write and a second + // peer-map rebuild for one request. +- _, c, err := s.SetApprovedRoutes(id, autoApprovedRoutes) ++ _, c, err := s.setApprovedRoutes(id, autoApprovedRoutes) + if err != nil { + return change.Change{}, fmt.Errorf("persisting auto-approved routes: %w", err) + } +diff --git a/hscontrol/state/tka.go b/hscontrol/state/tka.go +new file mode 100644 +index 0000000..898446b +--- /dev/null ++++ b/hscontrol/state/tka.go +@@ -0,0 +1,166 @@ ++package state ++ ++import ( ++ "bytes" ++ "context" ++ "errors" ++ "slices" ++ "time" ++ ++ "github.com/juanfont/headscale/hscontrol/types" ++ "gorm.io/gorm" ++ "tailscale.com/tailcfg" ++ "tailscale.com/types/key" ++) ++ ++// lockTKA is the publication barrier for identity-changing state operations. ++// The optional callback is configured once, before any server goroutines start. ++func (s *State) lockTKA() func() { ++ if s.TKAReconcile == nil { ++ return func() {} ++ } ++ s.TKAMu.Lock() ++ return s.TKAMu.Unlock ++} ++ ++func (s *State) reconcileTKA(id types.NodeID, signature []byte) error { ++ if s.TKAReconcile == nil { ++ return nil ++ } ++ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) ++ defer cancel() ++ return s.TKAReconcile(ctx, id, signature) ++} ++ ++// TKAAdmission resolves a Noise identity against committed SQL rows without ++// taking TKAMu, so unregistered clients cannot queue on the publication ++// barrier. The barrier repeats the authoritative lookup; this only rejects ++// identities the registry source does not have. ++func (s *State) TKAAdmission(ctx context.Context, machine key.MachinePublic, nodeKey key.NodePublic) (types.NodeID, bool, error) { ++ var ids []types.NodeID ++ err := s.db.DB.WithContext(ctx).Model(&types.Node{}). ++ Where("node_key = ? AND machine_key = ?", nodeKey.String(), machine.String()). ++ Limit(1).Pluck("id", &ids).Error ++ if err != nil { ++ return 0, false, err ++ } ++ if len(ids) == 0 { ++ return 0, false, nil ++ } ++ return ids[0], true, nil ++} ++ ++// TKAAdapterInstalled reports whether this database already depends on the ++// adapter: a recorded checkpoint or any node carrying a tailnet-lock key. ++// Startup must not silently fall back to stock maps once that is true. ++func (s *State) TKAAdapterInstalled(ctx context.Context) (bool, error) { ++ var checkpoints int64 ++ if err := s.db.DB.WithContext(ctx).Model(&types.OmnetCheckpoint{}).Count(&checkpoints).Error; err != nil { ++ return false, err ++ } ++ if checkpoints > 0 { ++ return true, nil ++ } ++ var nodes int64 ++ err := s.db.DB.WithContext(ctx).Model(&types.Node{}). ++ Where("tka_key IS NOT NULL").Count(&nodes).Error ++ if err != nil { ++ return false, err ++ } ++ return nodes > 0, nil ++} ++ ++// TKACheckRevision records the latest observed transport revision under TKAMu. ++// It catches empty/older snapshot replacement after restart. It cannot identify ++// an arbitrary different authority with a higher revision; same UID is trusted. ++func (s *State) TKACheckRevision(ctx context.Context, revision uint64) error { ++ var checkpoint types.OmnetCheckpoint ++ err := s.db.DB.WithContext(ctx).First(&checkpoint, 1).Error ++ if errors.Is(err, gorm.ErrRecordNotFound) { ++ return s.db.DB.WithContext(ctx).Create(&types.OmnetCheckpoint{ID: 1, Revision: revision}).Error ++ } ++ if err != nil { ++ return err ++ } ++ if revision < checkpoint.Revision { ++ return errors.New("omnet authority revision regressed") ++ } ++ if revision == checkpoint.Revision { ++ return nil ++ } ++ return s.db.DB.WithContext(ctx).Model(&checkpoint).Update("revision", revision).Error ++} ++ ++// TKACommittedNodes must be called under TKAMu. It deliberately reads SQL, ++// not NodeStore: upstream registration can update NodeStore before SQL commits. ++// Limit+1 detects capacity exhaustion without truncating the frozen roster. ++func (s *State) TKACommittedNodes(ctx context.Context) ([]types.Node, error) { ++ var nodes []types.Node ++ if err := s.db.DB.WithContext(ctx).Preload("User").Order("id").Limit(65).Find(&nodes).Error; err != nil { ++ return nil, err ++ } ++ if len(nodes) > 64 { ++ return nil, errors.New("omnet registry exceeds 64 nodes") ++ } ++ seen := make(map[key.NodePublic]bool, len(nodes)) ++ for _, n := range nodes { ++ if n.ID == 0 || n.ID > 1<<63-1 || seen[n.NodeKey] || n.NodeKey.IsZero() { ++ return nil, errors.New("omnet ambiguous committed identity") ++ } ++ seen[n.NodeKey] = true ++ cached, ok := s.GetNodeByID(n.ID) ++ if !ok || cached.NodeKey() != n.NodeKey || cached.MachineKey() != n.MachineKey || ++ cached.TypedUserID() != n.View().TypedUserID() || !slices.Equal(cached.Tags().AsSlice(), n.Tags) { ++ return nil, errors.New("omnet uncommitted node identity") ++ } ++ } ++ return nodes, nil ++} ++ ++// TKAAcknowledge clears only the durable forwarding outbox after Omega accepts ++// it, readback proves acceptance, or a definitive rejection is reconciled by a ++// successful unsigned upsert. Caller holds TKAMu; accepted signatures stay in Omega. ++func (s *State) TKAAcknowledge(ctx context.Context, n types.Node) error { ++ if len(n.TKASignature) == 0 { ++ return nil ++ } ++ if err := s.db.DB.WithContext(ctx).Model(&types.Node{}).Where("id = ?", n.ID). ++ Update("tka_signature", nil).Error; err != nil { ++ return err ++ } ++ s.nodeStore.UpdateNode(n.ID, func(current *types.Node) { current.TKASignature = nil }) ++ return nil ++} ++ ++// TKARegisterCurrent refreshes authenticated registration metadata, including ++// upstream's no-auth same-key restart fast path. It never grants ownership. ++func (s *State) TKARegisterCurrent(ctx context.Context, req tailcfg.RegisterRequest, machine key.MachinePublic) error { ++ defer s.lockTKA()() ++ nodes, err := s.TKACommittedNodes(ctx) ++ if err != nil { ++ return err ++ } ++ for _, n := range nodes { ++ if n.NodeKey != req.NodeKey { ++ continue ++ } ++ if n.MachineKey != machine || req.NLKey.IsZero() { ++ return errors.New("omnet registration identity mismatch") ++ } ++ if n.TKAKey != req.NLKey || (len(req.NodeKeySignature) != 0 && !bytes.Equal(n.TKASignature, req.NodeKeySignature)) { ++ n.TKAKey = req.NLKey ++ if len(req.NodeKeySignature) != 0 { ++ n.TKASignature = slices.Clone(req.NodeKeySignature) ++ } ++ if err := s.db.DB.WithContext(ctx).Select("TKAKey", "TKASignature").Updates(&n).Error; err != nil { ++ return err ++ } ++ s.nodeStore.UpdateNode(n.ID, func(current *types.Node) { ++ current.TKAKey = n.TKAKey ++ current.TKASignature = slices.Clone(n.TKASignature) ++ }) ++ } ++ return s.reconcileTKA(n.ID, req.NodeKeySignature) ++ } ++ return errors.New("omnet registered identity missing") ++} +diff --git a/hscontrol/state/tka_test.go b/hscontrol/state/tka_test.go +new file mode 100644 +index 0000000..d952634 +--- /dev/null ++++ b/hscontrol/state/tka_test.go +@@ -0,0 +1,283 @@ ++package state ++ ++import ( ++ "context" ++ "errors" ++ "fmt" ++ "testing" ++ ++ "github.com/juanfont/headscale/hscontrol/types" ++ "github.com/stretchr/testify/require" ++ "tailscale.com/tailcfg" ++ "tailscale.com/types/key" ++) ++ ++func TestOmnetRegistrationOutboxSurvivesReconcileFailureAndRestart(t *testing.T) { ++ path, s, id := persistTestSetup(t) ++ old, err := s.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ owner := types.UserID(*old.UserID) ++ pak, err := s.CreatePreAuthKey(&owner, true, false, nil, nil) ++ require.NoError(t, err) ++ req := tailcfg.RegisterRequest{ ++ NodeKey: key.NewNode().Public(), NLKey: key.NewNLPrivate().Public(), ++ NodeKeySignature: []byte("untrusted-pending-signature"), ++ Auth: &tailcfg.RegisterResponseAuth{AuthKey: pak.Key}, ++ Hostinfo: &tailcfg.Hostinfo{Hostname: "outbox-node"}, ++ } ++ outage := errors.New("injected daemon outage") ++ called := false ++ s.TKAReconcile = func(ctx context.Context, _ types.NodeID, _ []byte) error { ++ called = true ++ nodes, err := s.TKACommittedNodes(ctx) ++ require.NoError(t, err) ++ require.Len(t, nodes, 1) ++ require.Equal(t, req.NodeKey, nodes[0].NodeKey) ++ require.Equal(t, req.NLKey, nodes[0].TKAKey) ++ require.Equal(t, []byte(req.NodeKeySignature), nodes[0].TKASignature) ++ return outage ++ } ++ _, _, err = s.HandleNodeFromPreAuthKey(req, old.MachineKey) ++ require.ErrorIs(t, err, outage) ++ require.True(t, called) ++ require.NoError(t, s.Close()) ++ restarted := persistTestReopen(t, path) ++ durable, err := restarted.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ require.Equal(t, req.NLKey, durable.TKAKey) ++ require.Equal(t, req.NodeKey, durable.NodeKey) ++ require.Equal(t, []byte(req.NodeKeySignature), durable.TKASignature) ++ // Accepted readback or definitive rejection followed by unsigned upsert clears the outbox. ++ restarted.TKAMu.Lock() ++ require.NoError(t, restarted.TKAAcknowledge(context.Background(), *durable)) ++ restarted.TKAMu.Unlock() ++ durable, err = restarted.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ require.Empty(t, durable.TKASignature) ++} ++ ++func TestOmnetStaleMapCannotUndoRotation(t *testing.T) { ++ _, s, id := persistTestSetup(t) ++ defer s.Close() ++ old, err := s.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ s.TKAReconcile = func(context.Context, types.NodeID, []byte) error { return nil } ++ owner := types.UserID(*old.UserID) ++ pak, err := s.CreatePreAuthKey(&owner, true, false, nil, nil) ++ require.NoError(t, err) ++ req := tailcfg.RegisterRequest{ ++ NodeKey: key.NewNode().Public(), NLKey: key.NewNLPrivate().Public(), ++ Auth: &tailcfg.RegisterResponseAuth{AuthKey: pak.Key}, ++ Hostinfo: &tailcfg.Hostinfo{Hostname: old.Hostname}, ++ } ++ _, _, err = s.HandleNodeFromPreAuthKey(req, old.MachineKey) ++ require.NoError(t, err) ++ _, err = s.UpdateNodeFromMapRequest(id, tailcfg.MapRequest{NodeKey: old.NodeKey}) ++ require.ErrorContains(t, err, "stale map node identity") ++ current, err := s.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ require.Equal(t, req.NodeKey, current.NodeKey) ++} ++ ++func TestOmnetCommittedRosterRejectsSpeculativeIdentity(t *testing.T) { ++ _, s, id := persistTestSetup(t) ++ defer s.Close() ++ s.TKAReconcile = func(context.Context, types.NodeID, []byte) error { return nil } ++ s.nodeStore.UpdateNode(id, func(n *types.Node) { n.NodeKey = key.NewNode().Public() }) ++ s.TKAMu.Lock() ++ _, err := s.TKACommittedNodes(context.Background()) ++ s.TKAMu.Unlock() ++ require.ErrorContains(t, err, "uncommitted node identity") ++} ++ ++func TestOmnetCommittedRosterRejectsDuplicateNodeKeys(t *testing.T) { ++ _, s, id := persistTestSetup(t) ++ defer s.Close() ++ first, err := s.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ second := s.DB().CreateRegisteredNodeForTest(first.User, "duplicate-key") ++ second.NodeKey = first.NodeKey ++ require.NoError(t, s.DB().DB.Select("NodeKey").Updates(second).Error) ++ s.nodeStore.PutNode(*second) ++ s.TKAMu.Lock() ++ _, err = s.TKACommittedNodes(context.Background()) ++ s.TKAMu.Unlock() ++ require.ErrorContains(t, err, "ambiguous committed identity") ++} ++ ++func TestOmnetRevisionFloorSurvivesAdapterRestart(t *testing.T) { ++ path, s, _ := persistTestSetup(t) ++ s.TKAMu.Lock() ++ require.NoError(t, s.TKACheckRevision(context.Background(), 19)) ++ require.NoError(t, s.TKACheckRevision(context.Background(), 19)) ++ s.TKAMu.Unlock() ++ require.NoError(t, s.Close()) ++ restarted := persistTestReopen(t, path) ++ restarted.TKAMu.Lock() ++ defer restarted.TKAMu.Unlock() ++ require.ErrorContains(t, restarted.TKACheckRevision(context.Background(), 0), "revision regressed") ++ require.ErrorContains(t, restarted.TKACheckRevision(context.Background(), 18), "revision regressed") ++ require.NoError(t, restarted.TKACheckRevision(context.Background(), 20)) ++ var checkpoint types.OmnetCheckpoint ++ require.NoError(t, restarted.DB().DB.First(&checkpoint, 1).Error) ++ require.Equal(t, uint64(20), checkpoint.Revision) ++} ++ ++func TestOmnetInteractiveCallbackPersistsBeforeAuthCompletion(t *testing.T) { ++ _, s, id := persistTestSetup(t) ++ defer s.Close() ++ old, err := s.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ data := &types.RegistrationData{ ++ MachineKey: old.MachineKey, ++ NodeKey: key.NewNode().Public(), ++ TKAKey: key.NewNLPrivate().Public(), ++ TKASignature: []byte("interactive-pending-signature"), ++ Hostname: old.Hostname, ++ Hostinfo: &tailcfg.Hostinfo{Hostname: old.Hostname}, ++ } ++ authID := types.MustAuthID() ++ request := types.NewRegisterAuthRequest(data) ++ s.SetAuthCacheEntry(authID, request) ++ outage := errors.New("interactive forwarding outage") ++ s.TKAReconcile = func(ctx context.Context, _ types.NodeID, _ []byte) error { ++ // This is the real callback boundary, after SQL commit but before ++ // FinishAuth can report success to the waiting stock client. ++ nodes, err := s.TKACommittedNodes(ctx) ++ require.NoError(t, err) ++ require.Len(t, nodes, 1) ++ require.Equal(t, data.NodeKey, nodes[0].NodeKey) ++ require.Equal(t, data.TKAKey, nodes[0].TKAKey) ++ require.Equal(t, data.TKASignature, nodes[0].TKASignature) ++ select { ++ case <-request.WaitForAuth(): ++ t.Fatal("interactive authentication completed before reconciliation") ++ default: ++ } ++ return outage ++ } ++ _, _, err = s.HandleNodeFromAuthPath(authID, types.UserID(*old.UserID), nil, "oidc") ++ require.ErrorIs(t, err, outage) ++ verdict := <-request.WaitForAuth() ++ require.ErrorIs(t, verdict.Err, outage) ++ require.False(t, verdict.Node.Valid()) ++ stored, err := s.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ require.Equal(t, data.TKAKey, stored.TKAKey) ++ require.Equal(t, data.TKASignature, stored.TKASignature) ++} ++ ++func TestOmnetSameMachineCannotDuplicateNodeKeyAcrossUsers(t *testing.T) { ++ for _, interactive := range []bool{false, true} { ++ for _, existingTarget := range []bool{false, true} { ++ t.Run(fmt.Sprintf("interactive=%t/existing=%t", interactive, existingTarget), func(t *testing.T) { ++ _, s, id := persistTestSetup(t) ++ defer s.Close() ++ first, err := s.DB().GetNodeByID(id) ++ require.NoError(t, err) ++ first.TKAKey = key.NewNLPrivate().Public() ++ require.NoError(t, s.DB().DB.Save(first).Error) ++ s.nodeStore.PutNode(*first) ++ secondUser := s.CreateUserForTest("duplicate-target") ++ var second *types.Node ++ if existingTarget { ++ second = s.CreateRegisteredNodeForTest(secondUser, "existing-target") ++ second.MachineKey = first.MachineKey ++ second.TKAKey = key.NewNLPrivate().Public() ++ require.NoError(t, s.DB().DB.Save(second).Error) ++ s.nodeStore.PutNode(*second) ++ } ++ s.TKAReconcile = func(context.Context, types.NodeID, []byte) error { ++ t.Error("duplicate identity reached post-commit reconciliation") ++ return nil ++ } ++ if interactive { ++ id := types.MustAuthID() ++ s.SetAuthCacheEntry(id, types.NewRegisterAuthRequest(&types.RegistrationData{ ++ MachineKey: first.MachineKey, NodeKey: first.NodeKey, ++ TKAKey: key.NewNLPrivate().Public(), Hostname: "duplicate-target", ++ Hostinfo: &tailcfg.Hostinfo{Hostname: "duplicate-target"}, ++ })) ++ _, _, err = s.HandleNodeFromAuthPath(id, types.UserID(secondUser.ID), nil, "oidc") ++ } else { ++ pak, pakErr := s.CreatePreAuthKey(secondUser.TypedID(), true, false, nil, nil) ++ require.NoError(t, pakErr) ++ _, _, err = s.HandleNodeFromPreAuthKey(tailcfg.RegisterRequest{ ++ NodeKey: first.NodeKey, NLKey: key.NewNLPrivate().Public(), ++ Auth: &tailcfg.RegisterResponseAuth{AuthKey: pak.Key}, ++ Hostinfo: &tailcfg.Hostinfo{Hostname: "duplicate-target"}, ++ }, first.MachineKey) ++ } ++ require.ErrorIs(t, err, ErrNodeKeyInUse) ++ s.TKAMu.Lock() ++ nodes, err := s.TKACommittedNodes(context.Background()) ++ s.TKAMu.Unlock() ++ require.NoError(t, err, "refusal must leave a coherent unique roster") ++ wantCount := 1 ++ if existingTarget { ++ wantCount = 2 ++ stored, err := s.DB().GetNodeByID(second.ID) ++ require.NoError(t, err) ++ require.Equal(t, second.NodeKey, stored.NodeKey) ++ } ++ require.Len(t, nodes, wantCount) ++ stored, err := s.DB().GetNodeByID(first.ID) ++ require.NoError(t, err) ++ require.Equal(t, first.NodeKey, stored.NodeKey) ++ require.Equal(t, first.UserID, stored.UserID) ++ }) ++ } ++ } ++} ++ ++func TestOmnetReconcileFailureStillRefreshesCommittedPolicy(t *testing.T) { ++ for _, interactive := range []bool{false, true} { ++ t.Run(fmt.Sprintf("interactive=%t", interactive), func(t *testing.T) { ++ _, s, _ := persistTestSetup(t) ++ defer s.Close() ++ user := s.CreateUserForTest("outage-owner") ++ require.NoError(t, s.UpdatePolicyManagerUsersForTest()) ++ _, err := s.SetPolicy([]byte(`{"grants":[{"src":["outage-owner@"],"dst":["*"],"ip":["*"]}]}`)) ++ require.NoError(t, err) ++ before, _ := s.Filter() ++ outage := errors.New("injected post-commit outage") ++ var committedID types.NodeID ++ s.TKAReconcile = func(_ context.Context, id types.NodeID, _ []byte) error { ++ committedID = id ++ return outage ++ } ++ req := tailcfg.RegisterRequest{ ++ NodeKey: key.NewNode().Public(), NLKey: key.NewNLPrivate().Public(), ++ Hostinfo: &tailcfg.Hostinfo{Hostname: "policy-outage-node"}, ++ } ++ machine := key.NewMachine().Public() ++ if interactive { ++ id := types.MustAuthID() ++ request := types.NewRegisterAuthRequest(&types.RegistrationData{ ++ MachineKey: machine, NodeKey: req.NodeKey, TKAKey: req.NLKey, ++ Hostname: req.Hostinfo.Hostname, Hostinfo: req.Hostinfo, ++ }) ++ s.SetAuthCacheEntry(id, request) ++ _, _, err = s.HandleNodeFromAuthPath(id, types.UserID(user.ID), nil, "oidc") ++ require.ErrorIs(t, (<-request.WaitForAuth()).Err, outage) ++ } else { ++ pak, pakErr := s.CreatePreAuthKey(user.TypedID(), true, false, nil, nil) ++ require.NoError(t, pakErr) ++ req.Auth = &tailcfg.RegisterResponseAuth{AuthKey: pak.Key} ++ _, _, err = s.HandleNodeFromPreAuthKey(req, machine) ++ } ++ require.ErrorIs(t, err, outage) ++ stored, err := s.DB().GetNodeByID(committedID) ++ require.NoError(t, err) ++ require.Equal(t, req.NodeKey, stored.NodeKey) ++ after, _ := s.Filter() ++ require.NotEqual(t, before, after, "ACL sources must include the committed user node despite IPC failure") ++ usersChange, err := s.updatePolicyManagerUsers() ++ require.NoError(t, err) ++ nodesChange, err := s.updatePolicyManagerNodes() ++ require.NoError(t, err) ++ require.True(t, usersChange.IsEmpty()) ++ require.True(t, nodesChange.IsEmpty(), "an unrelated later event must not be needed to heal policy") ++ }) ++ } ++} +diff --git a/hscontrol/tkad.go b/hscontrol/tkad.go +new file mode 100644 +index 0000000..0592956 +--- /dev/null ++++ b/hscontrol/tkad.go +@@ -0,0 +1,680 @@ ++package hscontrol ++ ++import ( ++ "bytes" ++ "context" ++ "encoding/binary" ++ "encoding/json" ++ "errors" ++ "fmt" ++ "io" ++ "maps" ++ "net" ++ "net/http" ++ "os" ++ "path/filepath" ++ "slices" ++ "strconv" ++ "sync" ++ "time" ++ ++ "github.com/go-chi/chi/v5" ++ "github.com/juanfont/headscale/hscontrol/types" ++ "github.com/juanfont/headscale/hscontrol/types/change" ++ "github.com/rs/zerolog/log" ++ "tailscale.com/tailcfg" ++ "tailscale.com/types/key" ++) ++ ++const tkaBodyLimit = 65536 ++ ++// Reserve enough JSON space for the largest registry tuple and base64 expansion. ++const tkaSignatureLimit = (tkaBodyLimit - 512) / 4 * 3 ++const tkaTimeout = 8 * time.Second ++ ++// Unauthenticated Noise clients reach these paths before any identity check, so ++// the number of request goroutines waiting for the publication barrier is ++// bounded: a caller that cannot take a slot is told to retry instead of ++// queueing behind shared persistence work. ++const ( ++ tkaRegisterSlots = 4 ++ tkaMapSlots = 32 ++) ++ ++var errTKAUnavailable = errors.New("omnet authority unavailable or registration pending") ++var errTKABusy = errors.New("omnet publication busy; retry") ++ ++// This is transport glue. Omega alone parses TKA RPCs, verifies signatures, ++// chooses authority state and decides enablement/disablement. The local socket ++// profile trusts the same UID; it is not a separate-UID security boundary. ++type tkaAdapter struct { ++ h *Headscale ++ socket string ++ owner uint64 ++ revision uint64 // accessed under State.TKAMu ++ haveRevision bool ++ healthMu sync.Mutex ++ failed chan struct{} ++ healthy bool ++ registerSlots chan struct{} ++ mapSlots chan struct{} ++} ++ ++// admit takes an admission slot without waiting. Slots bound pre-barrier work; ++// they are not a rate limit and do not order publication. ++func admit(slots chan struct{}) bool { ++ select { ++ case slots <- struct{}{}: ++ return true ++ default: ++ return false ++ } ++} ++ ++func release(slots chan struct{}) { <-slots } ++ ++type tkaRegistryNode struct { ++ NodeID types.NodeID ++ NodePublic key.NodePublic ++ RotationPubkey []byte ++ KeySignature []byte ++} ++ ++type tkaSnapshot struct { ++ TKAInfo *tailcfg.TKAInfo ++ Revision uint64 ++ Nodes []tkaRegistryNode ++} ++ ++func (h *Headscale) initTKA() error { ++ socket, ownerText := os.Getenv("OMNET_TKAD_SOCKET"), os.Getenv("OMNET_TKAD_ADMIN_USER_ID") ++ if socket == "" && ownerText == "" { ++ // A database that already used the adapter must not start in stock ++ // mode: maps would carry nil TKAInfo and no signatures, which clients ++ // with Tailnet Lock enabled cannot recover from without local disable. ++ used, err := h.state.TKAAdapterInstalled(context.Background()) ++ if err != nil { ++ return fmt.Errorf("omnet adapter state unreadable: %w", err) ++ } ++ if used { ++ return errors.New("omnet adapter state exists; OMNET_TKAD_SOCKET and OMNET_TKAD_ADMIN_USER_ID are required") ++ } ++ return nil ++ } ++ owner, err := strconv.ParseUint(ownerText, 10, 64) ++ if err != nil || owner == 0 || !filepath.IsAbs(socket) { ++ return errors.New("OMNET_TKAD_SOCKET must be absolute and OMNET_TKAD_ADMIN_USER_ID must be positive") ++ } ++ a := &tkaAdapter{ ++ h: h, ++ socket: socket, ++ owner: owner, ++ failed: make(chan struct{}), ++ healthy: true, ++ registerSlots: make(chan struct{}, tkaRegisterSlots), ++ mapSlots: make(chan struct{}, tkaMapSlots), ++ } ++ h.tkad = a ++ h.state.TKAReconcile = a.reconcileRegistration ++ h.state.TKAMu.Lock() ++ defer h.state.TKAMu.Unlock() ++ ctx, cancel := context.WithTimeout(context.Background(), tkaTimeout) ++ defer cancel() ++ if _, err := a.readSnapshot(ctx); err != nil { ++ return err ++ } ++ if _, _, err := a.reconcile(ctx); err != nil { ++ // Keep control available for authenticated retries/admin deletion, ++ // but no map or TKA RPC may pass the reconciliation barrier. ++ log.Warn().Err(err).Msg("omnet registry pending; control publication blocked") ++ } ++ return nil ++} ++ ++func (a *tkaAdapter) health(ok bool) { ++ a.healthMu.Lock() ++ defer a.healthMu.Unlock() ++ if !ok && a.healthy { ++ close(a.failed) ++ } else if ok && !a.healthy { ++ a.failed = make(chan struct{}) ++ } ++ a.healthy = ok ++} ++ ++func (h *Headscale) tkaFailure() <-chan struct{} { ++ if h.tkad == nil { ++ return nil ++ } ++ h.tkad.healthMu.Lock() ++ defer h.tkad.healthMu.Unlock() ++ return h.tkad.failed ++} ++ ++// rpc exchanges one bounded, deadline-limited IPC frame. A lost reply is not ++// a rollback indication; durable registration outboxes are reconciled by read. ++func (a *tkaAdapter) rpc(ctx context.Context, route byte, admin bool, nodeID types.NodeID, body []byte) (_ int, _ []byte, retErr error) { ++ if len(body) > tkaBodyLimit { ++ return 0, nil, errors.New("omnet request too large") ++ } ++ parent := ctx ++ defer func() { ++ if retErr != nil && parent.Err() == nil { ++ a.health(false) ++ } ++ }() ++ ctx, cancel := context.WithTimeout(ctx, tkaTimeout) ++ defer cancel() ++ conn, err := (&net.Dialer{}).DialContext(ctx, "unix", a.socket) ++ if err != nil { ++ return 0, nil, errTKAUnavailable ++ } ++ defer conn.Close() ++ deadline, _ := ctx.Deadline() ++ if err := conn.SetDeadline(deadline); err != nil { ++ return 0, nil, errTKAUnavailable ++ } ++ var header [20]byte ++ copy(header[:4], "TKA\x01") ++ header[4] = route ++ if admin { ++ header[5] = 1 ++ } ++ binary.LittleEndian.PutUint64(header[8:16], uint64(nodeID)) ++ binary.LittleEndian.PutUint32(header[16:20], uint32(len(body))) ++ for _, part := range [][]byte{header[:], body} { ++ for len(part) > 0 { ++ n, err := conn.Write(part) ++ if err != nil || n == 0 { ++ return 0, nil, errTKAUnavailable ++ } ++ part = part[n:] ++ } ++ } ++ var response [12]byte ++ if _, err := io.ReadFull(conn, response[:]); err != nil { ++ return 0, nil, errTKAUnavailable ++ } ++ status := int(binary.LittleEndian.Uint16(response[4:6])) ++ length := binary.LittleEndian.Uint32(response[8:12]) ++ if string(response[:4]) != "TKA\x01" || response[6] != 0 || response[7] != 0 || ++ length > tkaBodyLimit || status < 200 || status > 599 { ++ return 0, nil, errTKAUnavailable ++ } ++ result := make([]byte, int(length)) ++ if _, err := io.ReadFull(conn, result); err != nil { ++ return 0, nil, errTKAUnavailable ++ } ++ return status, result, nil ++} ++ ++func (a *tkaAdapter) readSnapshot(ctx context.Context) (*tkaSnapshot, error) { ++ status, body, err := a.rpc(ctx, 11, true, 0, []byte("{}")) ++ if err != nil || status != http.StatusOK { ++ return nil, errTKAUnavailable ++ } ++ var wire struct { ++ TKAInfo json.RawMessage ++ Revision *uint64 ++ Nodes *[]tkaRegistryNode ++ } ++ if err := json.Unmarshal(body, &wire); err != nil || wire.Revision == nil || ++ wire.Nodes == nil || len(wire.TKAInfo) == 0 || len(*wire.Nodes) > 64 { ++ return nil, errTKAUnavailable ++ } ++ snap := tkaSnapshot{Revision: *wire.Revision, Nodes: *wire.Nodes} ++ if err := json.Unmarshal(wire.TKAInfo, &snap.TKAInfo); err != nil { ++ return nil, errTKAUnavailable ++ } ++ seen := make(map[types.NodeID]bool, len(snap.Nodes)) ++ keys := make(map[key.NodePublic]bool, len(snap.Nodes)) ++ for _, n := range snap.Nodes { ++ if n.NodeID == 0 || n.NodeID > 1<<63-1 || n.NodePublic.IsZero() || ++ len(n.RotationPubkey) != 32 || seen[n.NodeID] || keys[n.NodePublic] { ++ return nil, errTKAUnavailable ++ } ++ seen[n.NodeID], keys[n.NodePublic] = true, true ++ } ++ if a.haveRevision && snap.Revision < a.revision { ++ return nil, errors.New("omnet authority revision regressed") ++ } ++ if err := a.h.state.TKACheckRevision(ctx, snap.Revision); err != nil { ++ return nil, err ++ } ++ return &snap, nil ++} ++ ++// reconcile runs under the shared identity/publication barrier. SQL is the ++// desired registry; Omega is the only accepted-signature store. Exact reads ++// suppress unchanged writes, so adapter restart preserves pending init. ++func (a *tkaAdapter) reconcile(ctx context.Context) (_ *tkaSnapshot, _ []types.Node, retErr error) { ++ if err := ctx.Err(); err != nil { ++ return nil, nil, err ++ } ++ // A disconnected requester cannot cancel a shared persistence/publication ++ // barrier and thereby declare the daemon unhealthy for every other node. ++ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), tkaTimeout) ++ defer cancel() ++ defer func() { a.health(retErr == nil) }() ++ nodes, err := a.h.state.TKACommittedNodes(ctx) ++ if err != nil { ++ return nil, nil, err ++ } ++ snap, err := a.readSnapshot(ctx) ++ if err != nil { ++ return nil, nil, err ++ } ++ current := make(map[types.NodeID]tkaRegistryNode, len(snap.Nodes)) ++ desired := make(map[types.NodeID]key.NodePublic, len(nodes)) ++ for _, n := range snap.Nodes { ++ current[n.NodeID] = n ++ } ++ for _, n := range nodes { ++ desired[n.ID] = n.NodeKey ++ if n.TKAKey.IsZero() { ++ return nil, nil, errors.New("omnet node lacks authenticated NLKey; re-register it") ++ } ++ } ++ mutated := false ++ // Vacate all obsolete keys before claiming any desired key, including ++ // cycles after an outage. A changed key cannot retain its old signature. ++ for _, n := range snap.Nodes { ++ if desired[n.NodeID] == n.NodePublic { ++ continue ++ } ++ body, _ := json.Marshal(struct{ NodeID types.NodeID }{n.NodeID}) ++ status, _, err := a.rpc(ctx, 10, true, 0, body) ++ if err != nil || status != http.StatusOK { ++ return nil, nil, errTKAUnavailable ++ } ++ mutated = true ++ delete(current, n.NodeID) ++ } ++ for _, n := range nodes { ++ old, found := current[n.ID] ++ tupleMatches := found && old.NodePublic == n.NodeKey && bytes.Equal(old.RotationPubkey, n.TKAKey.Verifier()) ++ sigMatches := len(n.TKASignature) == 0 || bytes.Equal(old.KeySignature, n.TKASignature) ++ if !tupleMatches || !sigMatches { ++ upsert := struct { ++ NodeID types.NodeID ++ NodeKey key.NodePublic ++ RotationPubkey []byte ++ Signature []byte `json:",omitempty"` ++ }{n.ID, n.NodeKey, n.TKAKey.Verifier(), n.TKASignature} ++ body, err := json.Marshal(upsert) ++ if err != nil { ++ return nil, nil, err ++ } ++ status := http.StatusRequestEntityTooLarge ++ if len(body) <= tkaBodyLimit { ++ status, _, err = a.rpc(ctx, 9, true, 0, body) ++ } ++ if err != nil { ++ // A lost reply may have committed. Preserve the outbox until ++ // accepted readback or a definitive response resolves it. ++ return nil, nil, err ++ } ++ if len(upsert.Signature) != 0 && (status == http.StatusBadRequest || ++ status == http.StatusForbidden || status == http.StatusConflict || ++ (status == http.StatusRequestEntityTooLarge && len(body) > tkaBodyLimit)) { ++ // These are the pinned daemon's invalid/malformed/inactive ++ // signature responses. Require an unsigned upsert to succeed: ++ // an admin/identity rejection must not be reported as success. ++ // Same-key omission preserves Omega's accepted signature; ++ // a changed key becomes unsigned, never authorized by this glue. ++ upsert.Signature = nil ++ body, err = json.Marshal(upsert) ++ if err != nil { ++ return nil, nil, err ++ } ++ status, _, err = a.rpc(ctx, 9, true, 0, body) ++ } ++ if err != nil || status != http.StatusOK { ++ return nil, nil, errTKAUnavailable ++ } ++ mutated = true ++ } ++ if err := a.h.state.TKAAcknowledge(ctx, n); err != nil { ++ return nil, nil, err ++ } ++ } ++ if mutated { ++ snap, err = a.readSnapshot(ctx) ++ if err != nil { ++ return nil, nil, err ++ } ++ } ++ if !a.haveRevision || snap.Revision != a.revision { ++ a.revision, a.haveRevision = snap.Revision, true ++ if a.h.mapBatcher != nil { ++ a.h.Change(change.FullUpdate()) ++ } ++ } ++ return snap, nodes, nil ++} ++ ++// Registration success must not conceal a rejected submitted signature. An ++// unrelated node's rejected outbox does not fail this caller or global health. ++func (a *tkaAdapter) reconcileRegistration(ctx context.Context, id types.NodeID, signature []byte) error { ++ snap, _, err := a.reconcile(ctx) ++ if err != nil || len(signature) == 0 { ++ return err ++ } ++ for _, n := range snap.Nodes { ++ if n.NodeID == id && bytes.Equal(n.KeySignature, signature) { ++ return nil ++ } ++ } ++ // Authentication may already have committed ownership/policy changes even ++ // when the same-key unsigned retry leaves Omega's revision unchanged. ++ if a.h.mapBatcher != nil { ++ a.h.Change(change.FullUpdate()) ++ } ++ return errors.New("omnet rejected node key signature") ++} ++ ++func (h *Headscale) watchTKA(ctx context.Context) { ++ if h.tkad == nil { ++ return ++ } ++ ticker := time.NewTicker(time.Second) ++ defer ticker.Stop() ++ for { ++ select { ++ case <-ctx.Done(): ++ return ++ case <-ticker.C: ++ h.state.TKAMu.Lock() ++ checkCtx, cancel := context.WithTimeout(ctx, tkaTimeout) ++ _, _, _ = h.tkad.reconcile(checkCtx) ++ cancel() ++ h.state.TKAMu.Unlock() ++ } ++ } ++} ++ ++func (ns *noiseServer) tkaRoutes(r chi.Router) { ++ for route, path := range []string{"/init/begin", "/init/finish", "/bootstrap", "/sync/offer", "/sync/send", "/disable", "/sign", "/affected-sigs"} { ++ r.Get("/tka"+path, func(w http.ResponseWriter, req *http.Request) { ns.tkaRPC(w, req, byte(route+1)) }) ++ } ++} ++ ++func (ns *noiseServer) tkaRPC(w http.ResponseWriter, req *http.Request, route byte) { ++ a := ns.headscale.tkad ++ if a == nil { ++ http.Error(w, "omnet not configured", http.StatusServiceUnavailable) ++ return ++ } ++ controller := http.NewResponseController(w) ++ _ = controller.SetReadDeadline(time.Now().Add(tkaTimeout)) ++ body, err := io.ReadAll(io.LimitReader(req.Body, tkaBodyLimit+1)) ++ _ = controller.SetReadDeadline(time.Time{}) ++ if err != nil || len(body) > tkaBodyLimit { ++ http.Error(w, "invalid omnet body", http.StatusRequestEntityTooLarge) ++ return ++ } ++ // This decode selects an identity only. The original bytes are forwarded ++ // unchanged; Omega independently rejects duplicate fields and binds NodeKey. ++ var selector struct{ NodeKey key.NodePublic } ++ if json.Unmarshal(body, &selector) != nil || selector.NodeKey.IsZero() { ++ http.Error(w, "invalid omnet identity", http.StatusBadRequest) ++ return ++ } ++ // An unregistered Noise identity must not reach shared persistence work: ++ // committed SQL is the registry source, and the barrier repeats this check. ++ if _, ok, err := a.h.state.TKAAdmission(req.Context(), ns.machineKey, selector.NodeKey); err != nil { ++ http.Error(w, errTKAUnavailable.Error(), http.StatusServiceUnavailable) ++ return ++ } else if !ok { ++ http.Error(w, "unauthorized omnet identity", http.StatusUnauthorized) ++ return ++ } ++ status, reply, err := func() (int, []byte, error) { ++ a.h.state.TKAMu.Lock() ++ defer a.h.state.TKAMu.Unlock() ++ if err := req.Context().Err(); err != nil { ++ return http.StatusServiceUnavailable, nil, err ++ } ++ ctx, cancel := context.WithTimeout(context.WithoutCancel(req.Context()), tkaTimeout) ++ defer cancel() ++ _, nodes, err := a.reconcile(ctx) ++ if err != nil { ++ return http.StatusServiceUnavailable, nil, errTKAUnavailable ++ } ++ var caller *types.Node ++ for i := range nodes { ++ if nodes[i].NodeKey == selector.NodeKey && nodes[i].MachineKey == ns.machineKey { ++ caller = &nodes[i] ++ } ++ } ++ if caller == nil { ++ return http.StatusUnauthorized, nil, errors.New("unauthorized omnet identity") ++ } ++ admin := !caller.IsExpired() && !caller.IsTagged() && caller.UserID != nil && uint64(*caller.UserID) == a.owner ++ status, reply, err := a.rpc(ctx, route, admin, caller.ID, body) ++ if err != nil { ++ // This is our detached IPC deadline, not caller cancellation. ++ // A lost mutation reply must stop publication until readback. ++ a.health(false) ++ return http.StatusServiceUnavailable, nil, errTKAUnavailable ++ } ++ // A successful mutation is not retried because notification fails. ++ if status == http.StatusOK && a.h.mapBatcher != nil { ++ a.h.Change(change.FullUpdate()) ++ } ++ return status, reply, nil ++ }() ++ _ = controller.SetWriteDeadline(time.Now().Add(tkaTimeout)) ++ defer controller.SetWriteDeadline(time.Time{}) ++ if err != nil { ++ http.Error(w, err.Error(), status) ++ return ++ } ++ w.Header().Set("Content-Type", "application/json") ++ w.WriteHeader(status) ++ _, _ = w.Write(reply) ++} ++ ++// registrationPrelude supplies the stock client's two-step signature challenge ++// before upstream authentication. Possession of the old Noise identity never ++// substitutes for interactive reauthentication, including for unexpired nodes. ++func (h *Headscale) registrationPrelude(ctx context.Context, req tailcfg.RegisterRequest, machine key.MachinePublic) (*tailcfg.RegisterResponse, error) { ++ if h.tkad == nil { ++ return nil, nil ++ } ++ if req.NodeKey.IsZero() || req.NLKey.IsZero() || len(req.NodeKeySignature) > tkaSignatureLimit { ++ return nil, errors.New("omnet requires nonzero NodeKey, NLKey and bounded signature") ++ } ++ if err := ctx.Err(); err != nil { ++ return nil, err ++ } ++ // Registration is reachable with an unknown machine key. Bound how many ++ // such requests can wait for the shared barrier; clients retry instead of ++ // queueing behind persistence work. ++ if !admit(h.tkad.registerSlots) { ++ return nil, errTKABusy ++ } ++ defer release(h.tkad.registerSlots) ++ h.state.TKAMu.Lock() ++ defer h.state.TKAMu.Unlock() ++ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), tkaTimeout) ++ defer cancel() ++ snap, err := h.tkad.readSnapshot(ctx) ++ if err != nil { ++ h.tkad.health(false) ++ return nil, err ++ } ++ nodes, err := h.state.TKACommittedNodes(ctx) ++ if err != nil { ++ return nil, err ++ } ++ for _, n := range nodes { ++ if n.NodeKey != req.OldNodeKey || n.NodeKey == req.NodeKey { ++ continue ++ } ++ if n.MachineKey != machine { ++ return nil, errors.New("omnet old node belongs to another Noise identity") ++ } ++ for _, stored := range snap.Nodes { ++ if stored.NodeID == n.ID && stored.NodePublic == n.NodeKey && ++ len(stored.KeySignature) > 0 && len(req.NodeKeySignature) == 0 { ++ return &tailcfg.RegisterResponse{NodeKeySignature: stored.KeySignature}, nil ++ } ++ } ++ } ++ return nil, nil ++} ++ ++func (h *Headscale) tkaMapReady(ctx context.Context) error { ++ if h.tkad == nil { ++ return nil ++ } ++ if !admit(h.tkad.mapSlots) { ++ return errTKABusy ++ } ++ defer release(h.tkad.mapSlots) ++ h.state.TKAMu.Lock() ++ defer h.state.TKAMu.Unlock() ++ ctx, cancel := context.WithTimeout(ctx, tkaTimeout) ++ defer cancel() ++ _, _, err := h.tkad.reconcile(ctx) ++ return err ++} ++ ++// encodeTKAMap is the last publication barrier, including already queued maps. ++// A stale key or stale authenticated session closes the stream instead of ++// pairing an old identity with a current signature (or publishing a fallback). ++func (m *mapSession) encodeTKAMap(msg *tailcfg.MapResponse) ([]byte, error) { ++ a := m.h.tkad ++ m.h.state.TKAMu.Lock() ++ defer m.h.state.TKAMu.Unlock() ++ ctx, cancel := context.WithTimeout(m.ctx, tkaTimeout) ++ defer cancel() ++ snap, nodes, err := a.reconcile(ctx) ++ if err != nil { ++ return nil, err ++ } ++ validSession := false ++ for _, n := range nodes { ++ if n.ID == m.node.ID && n.NodeKey == m.req.NodeKey && n.MachineKey == m.node.MachineKey { ++ validSession = true ++ } ++ } ++ if !validSession { ++ return nil, errors.New("stale omnet map session") ++ } ++ // A PeerChange cannot clear a previous signature with nil. Rebuild key ++ // patches as full nodes, including an unsigned rotation, before publication. ++ for _, patch := range msg.PeersChangedPatch { ++ if patch.Key != nil { ++ full, err := m.h.mapBatcher.FullMapResponse(m.node.ID, m.capVer) ++ if err != nil { ++ return nil, err ++ } ++ full.PingRequest = msg.PingRequest ++ msg = full ++ break ++ } ++ } ++ copyNode := func(n *tailcfg.Node) *tailcfg.Node { ++ if n == nil { ++ return nil ++ } ++ copied := *n ++ return &copied ++ } ++ out := new(tailcfg.MapResponse) ++ *out = *msg ++ out.Node = copyNode(msg.Node) ++ out.Peers = slices.Clone(msg.Peers) ++ for i, n := range out.Peers { ++ out.Peers[i] = copyNode(n) ++ } ++ out.PeersChanged = slices.Clone(msg.PeersChanged) ++ for i, n := range out.PeersChanged { ++ out.PeersChanged[i] = copyNode(n) ++ } ++ out.PeersChangedPatch = slices.Clone(msg.PeersChangedPatch) ++ for i, patch := range out.PeersChangedPatch { ++ copied := *patch ++ out.PeersChangedPatch[i] = &copied ++ } ++ out.TKAInfo = snap.TKAInfo ++ registry := make(map[types.NodeID]tkaRegistryNode, len(snap.Nodes)) ++ for _, n := range snap.Nodes { ++ registry[n.NodeID] = n ++ } ++ decorate := func(n *tailcfg.Node) error { ++ if n == nil { ++ return nil ++ } ++ stored, ok := registry[types.NodeID(n.ID)] ++ if !ok || stored.NodePublic != n.Key { ++ return errors.New("stale omnet map node") ++ } ++ n.KeySignature = stored.KeySignature ++ return nil ++ } ++ if err := decorate(out.Node); err != nil { ++ return nil, err ++ } ++ if out.Node != nil { ++ out.Node.CapMap = maps.Clone(out.Node.CapMap) ++ if out.Node.CapMap == nil { ++ out.Node.CapMap = make(tailcfg.NodeCapMap) ++ } ++ out.Node.CapMap[tailcfg.CapabilityTailnetLock] = nil ++ } ++ for _, n := range out.Peers { ++ if err := decorate(n); err != nil { ++ return nil, err ++ } ++ } ++ for _, n := range out.PeersChanged { ++ if err := decorate(n); err != nil { ++ return nil, err ++ } ++ } ++ for _, patch := range out.PeersChangedPatch { ++ if _, ok := registry[types.NodeID(patch.NodeID)]; !ok { ++ return nil, errors.New("stale omnet map patch") ++ } ++ // A non-key patch may be queued behind a rotation. It cannot safely ++ // attach the new key's signature to the client's previous key. ++ patch.KeySignature = nil ++ } ++ return encodeMapResponse(m.req.Compress, out) ++} ++ ++// Each session's poll loop is a single writer, preserving frame order. The ++// coherent frame is frozen under TKAMu, but no client I/O holds the barrier. ++func (m *mapSession) writeTKAMap(msg *tailcfg.MapResponse) error { ++ if m.h.tkad == nil { ++ return writeMapResponse(m.w, m.req.Compress, m.isStreaming(), msg) ++ } ++ frame, err := m.encodeTKAMap(msg) ++ if err != nil { ++ return err ++ } ++ m.writeDeadlineMu.Lock() ++ if m.cancelChClosed.Load() { ++ m.writeDeadlineMu.Unlock() ++ return errMapSessionStopped ++ } ++ if err := m.ctx.Err(); err != nil { ++ m.writeDeadlineMu.Unlock() ++ return err ++ } ++ controller := http.NewResponseController(m.w) ++ err = controller.SetWriteDeadline(time.Now().Add(tkaTimeout)) ++ m.writeDeadlineMu.Unlock() ++ if err != nil && !errors.Is(err, http.ErrNotSupported) { ++ return fmt.Errorf("omnet write deadline: %w", err) ++ } ++ defer func() { ++ m.writeDeadlineMu.Lock() ++ defer m.writeDeadlineMu.Unlock() ++ _ = controller.SetWriteDeadline(time.Time{}) ++ }() ++ return writeMapFrame(m.w, m.isStreaming(), frame) ++} +diff --git a/hscontrol/tkad_test.go b/hscontrol/tkad_test.go +new file mode 100644 +index 0000000..7c65043 +--- /dev/null ++++ b/hscontrol/tkad_test.go +@@ -0,0 +1,794 @@ ++package hscontrol ++ ++import ( ++ "bytes" ++ "context" ++ "encoding/binary" ++ "encoding/json" ++ "fmt" ++ "io" ++ "net" ++ "net/http" ++ "net/http/httptest" ++ "path/filepath" ++ "slices" ++ "sync" ++ "testing" ++ "time" ++ ++ "github.com/go-chi/chi/v5" ++ "github.com/juanfont/headscale/hscontrol/types" ++ "github.com/stretchr/testify/require" ++ "tailscale.com/tailcfg" ++ "tailscale.com/types/key" ++) ++ ++// This fixture tests glue only. Real Omega protocol/security behavior is ++// exercised by Omnet's native daemon suite and stock-client E2E, not simulated. ++type omnetFixture struct { ++ mu sync.Mutex ++ snapshot tkaSnapshot ++ writes int ++ calls []byte ++ lastHeader [20]byte ++ badRead bool ++ rejectSignature int ++ rejectUnsigned int ++ dropReplyRoute byte ++ beforeReply func(byte) ++} ++ ++func omnetSocket(t *testing.T, f *omnetFixture) string { ++ t.Helper() ++ path := filepath.Join(t.TempDir(), "t.sock") ++ listener, err := net.Listen("unix", path) ++ require.NoError(t, err) ++ t.Cleanup(func() { _ = listener.Close() }) ++ go func() { ++ for { ++ conn, err := listener.Accept() ++ if err != nil { ++ return ++ } ++ func() { ++ defer conn.Close() ++ var hdr [20]byte ++ if _, err := io.ReadFull(conn, hdr[:]); err != nil { ++ return ++ } ++ length := binary.LittleEndian.Uint32(hdr[16:20]) ++ if length > tkaBodyLimit { ++ return ++ } ++ body := make([]byte, length) ++ if _, err := io.ReadFull(conn, body); err != nil { ++ return ++ } ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ f.calls = append(f.calls, hdr[4]) ++ reply := []byte("{\"opaque\":true}") ++ status := http.StatusOK ++ switch hdr[4] { ++ case 9: ++ var n struct { ++ NodeID types.NodeID ++ NodeKey key.NodePublic ++ RotationPubkey []byte ++ Signature []byte ++ } ++ if json.Unmarshal(body, &n) != nil { ++ return ++ } ++ if len(n.Signature) != 0 && f.rejectSignature != 0 { ++ status = f.rejectSignature ++ break ++ } ++ if len(n.Signature) == 0 && f.rejectUnsigned != 0 { ++ status = f.rejectUnsigned ++ break ++ } ++ if slices.ContainsFunc(f.snapshot.Nodes, func(x tkaRegistryNode) bool { ++ return x.NodeID != n.NodeID && x.NodePublic == n.NodeKey ++ }) { ++ status = http.StatusConflict ++ break ++ } ++ oldIndex := slices.IndexFunc(f.snapshot.Nodes, func(x tkaRegistryNode) bool { return x.NodeID == n.NodeID }) ++ newNode := tkaRegistryNode{n.NodeID, n.NodeKey, n.RotationPubkey, n.Signature} ++ if oldIndex >= 0 { ++ old := f.snapshot.Nodes[oldIndex] ++ if len(n.Signature) == 0 && old.NodePublic == n.NodeKey { ++ newNode.KeySignature = old.KeySignature ++ } ++ f.snapshot.Nodes[oldIndex] = newNode ++ } else { ++ f.snapshot.Nodes = append(f.snapshot.Nodes, newNode) ++ } ++ f.writes++ ++ f.snapshot.Revision++ ++ case 10: ++ var n struct{ NodeID types.NodeID } ++ if json.Unmarshal(body, &n) != nil { ++ return ++ } ++ f.snapshot.Nodes = slices.DeleteFunc(f.snapshot.Nodes, func(x tkaRegistryNode) bool { return x.NodeID == n.NodeID }) ++ f.writes++ ++ f.snapshot.Revision++ ++ case 11: ++ reply, _ = json.Marshal(f.snapshot) ++ if f.badRead { ++ reply = []byte("{}") ++ } ++ default: ++ f.lastHeader = hdr ++ if (hdr[4] == 1 || hdr[4] == 2 || hdr[4] == 6) && hdr[5] == 0 { ++ status = http.StatusForbidden ++ } ++ } ++ if f.beforeReply != nil { ++ f.beforeReply(hdr[4]) ++ } ++ if f.dropReplyRoute == hdr[4] { ++ f.dropReplyRoute = 0 ++ return ++ } ++ var response [12]byte ++ copy(response[:], "TKA\x01") ++ binary.LittleEndian.PutUint16(response[4:6], uint16(status)) ++ binary.LittleEndian.PutUint32(response[8:], uint32(len(reply))) ++ _, _ = conn.Write(response[:]) ++ _, _ = conn.Write(reply) ++ }() ++ } ++ }() ++ return path ++} ++ ++func omnetApp(t *testing.T) (*Headscale, types.Node, *omnetFixture) { ++ t.Helper() ++ h := createTestApp(t) ++ user := h.state.CreateUserForTest("omnet-owner") ++ n := h.state.CreateRegisteredNodeForTest(user, "omnet-node") ++ n.TKAKey = key.NewNLPrivate().Public() ++ require.NoError(t, h.state.DB().DB.Save(n).Error) ++ h.state.PutNodeInStoreForTest(*n) ++ f := &omnetFixture{snapshot: tkaSnapshot{Revision: 7, Nodes: []tkaRegistryNode{{n.ID, n.NodeKey, n.TKAKey.Verifier(), []byte("accepted-signature")}}}} ++ a := &tkaAdapter{ ++ h: h, ++ socket: omnetSocket(t, f), ++ owner: uint64(user.ID), ++ failed: make(chan struct{}), ++ healthy: true, ++ registerSlots: make(chan struct{}, tkaRegisterSlots), ++ mapSlots: make(chan struct{}, tkaMapSlots), ++ } ++ h.tkad = a ++ h.state.TKAReconcile = a.reconcileRegistration ++ return h, *n, f ++} ++ ++func TestOmnetRawRoutesIdentityAndAdmin(t *testing.T) { ++ h, n, f := omnetApp(t) ++ ns := &noiseServer{headscale: h, machineKey: n.MachineKey} ++ router := chi.NewRouter() ++ ns.tkaRoutes(router) ++ body := []byte(fmt.Sprintf(" { \"NodeKey\": %q, \"unknown\": [1,2] }\n", n.NodeKey.String())) ++ w := httptest.NewRecorder() ++ router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/tka/init/begin", bytes.NewReader(body))) ++ require.Equal(t, http.StatusOK, w.Code) ++ f.mu.Lock() ++ require.Equal(t, byte(1), f.lastHeader[5], "current owner receives admin assertion") ++ f.mu.Unlock() ++ ns.machineKey = key.NewMachine().Public() ++ w = httptest.NewRecorder() ++ ns.tkaRPC(w, httptest.NewRequest(http.MethodGet, "/", bytes.NewReader(body)), 1) ++ require.Equal(t, http.StatusUnauthorized, w.Code) ++ ns.machineKey = n.MachineKey ++ h.tkad.owner++ ++ w = httptest.NewRecorder() ++ ns.tkaRPC(w, httptest.NewRequest(http.MethodGet, "/", bytes.NewReader(body)), 1) ++ f.mu.Lock() ++ require.Zero(t, f.lastHeader[5], "non-owner cannot assert admin") ++ f.mu.Unlock() ++} ++ ++func TestOmnetUnregisteredNoiseIdentitySkipsAuthority(t *testing.T) { ++ h, n, f := omnetApp(t) ++ ns := &noiseServer{headscale: h, machineKey: key.NewMachine().Public()} ++ body := []byte(fmt.Sprintf("{\"NodeKey\":%q}", n.NodeKey.String())) ++ w := httptest.NewRecorder() ++ ns.tkaRPC(w, httptest.NewRequest(http.MethodGet, "/", bytes.NewReader(body)), 1) ++ require.Equal(t, http.StatusUnauthorized, w.Code, "machine key must match") ++ // A registered machine key with an unregistered node key is also refused. ++ ns.machineKey = n.MachineKey ++ body = []byte(fmt.Sprintf("{\"NodeKey\":%q}", key.NewNode().Public().String())) ++ w = httptest.NewRecorder() ++ ns.tkaRPC(w, httptest.NewRequest(http.MethodGet, "/", bytes.NewReader(body)), 1) ++ require.Equal(t, http.StatusUnauthorized, w.Code, "node key must be committed") ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ require.Empty(t, f.calls, "unregistered identities must not reach the authority") ++} ++ ++func TestOmnetBoundedAdmissionRejectsInsteadOfQueueing(t *testing.T) { ++ h, n, _ := omnetApp(t) ++ for range tkaRegisterSlots { ++ require.True(t, admit(h.tkad.registerSlots)) ++ } ++ _, err := h.registrationPrelude(context.Background(), tailcfg.RegisterRequest{ ++ NodeKey: key.NewNode().Public(), NLKey: key.NewNLPrivate().Public(), ++ }, n.MachineKey) ++ require.ErrorIs(t, err, errTKABusy, "saturated registration admission must fail fast") ++ for range tkaRegisterSlots { ++ release(h.tkad.registerSlots) ++ } ++ for range tkaMapSlots { ++ require.True(t, admit(h.tkad.mapSlots)) ++ } ++ require.ErrorIs(t, h.tkaMapReady(context.Background()), errTKABusy, "saturated map admission must fail fast") ++ for range tkaMapSlots { ++ release(h.tkad.mapSlots) ++ } ++ require.NoError(t, h.tkaMapReady(context.Background())) ++} ++ ++func TestOmnetAdapterSettingsRequiredAfterActivation(t *testing.T) { ++ h := createTestApp(t) ++ t.Setenv("OMNET_TKAD_SOCKET", "") ++ t.Setenv("OMNET_TKAD_ADMIN_USER_ID", "") ++ require.NoError(t, h.initTKA(), "unused adapter may stay off") ++ user := h.state.CreateUserForTest("omnet-owner") ++ n := h.state.CreateRegisteredNodeForTest(user, "omnet-node") ++ n.TKAKey = key.NewNLPrivate().Public() ++ require.NoError(t, h.state.DB().DB.Save(n).Error) ++ require.Error(t, h.initTKA(), "adapter state must not silently fall back to stock maps") ++} ++ ++func TestOmnetRestartDoesNotRewriteRegistry(t *testing.T) { ++ h, _, f := omnetApp(t) ++ for range 2 { ++ h.state.TKAMu.Lock() ++ snapshot, _, err := h.tkad.reconcile(context.Background()) ++ h.state.TKAMu.Unlock() ++ require.NoError(t, err) ++ require.Equal(t, uint64(7), snapshot.Revision) ++ // Drop adapter-only acknowledged revision state, as on restart. ++ h.tkad.haveRevision = false ++ } ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ require.Zero(t, f.writes, "unchanged registry must preserve a pending init") ++} ++ ++func TestOmnetHistoricalOutboxReadbackAndOrphanRemoval(t *testing.T) { ++ h, n, f := omnetApp(t) ++ n.TKASignature = []byte("accepted-signature") ++ require.NoError(t, h.state.DB().DB.Save(&n).Error) ++ h.state.PutNodeInStoreForTest(n) ++ f.mu.Lock() ++ f.snapshot.Nodes = append(f.snapshot.Nodes, tkaRegistryNode{99, key.NewNode().Public(), key.NewNLPrivate().Public().Verifier(), nil}) ++ f.mu.Unlock() ++ h.state.TKAMu.Lock() ++ _, _, err := h.tkad.reconcile(context.Background()) ++ h.state.TKAMu.Unlock() ++ require.NoError(t, err) ++ stored, err := h.state.DB().GetNodeByID(n.ID) ++ require.NoError(t, err) ++ require.Empty(t, stored.TKASignature) ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ require.Equal(t, 1, f.writes, "only orphan deletion; historical signature must not be replayed") ++ require.NotContains(t, f.calls, byte(9)) ++} ++ ++func TestOmnetRotationChallengePrecedesKeyChange(t *testing.T) { ++ h, n, _ := omnetApp(t) ++ req := tailcfg.RegisterRequest{NodeKey: key.NewNode().Public(), OldNodeKey: n.NodeKey, NLKey: n.TKAKey} ++ resp, err := h.registrationPrelude(context.Background(), req, n.MachineKey) ++ require.NoError(t, err) ++ require.Equal(t, []byte("accepted-signature"), []byte(resp.NodeKeySignature)) ++ stored, err := h.state.DB().GetNodeByID(n.ID) ++ require.NoError(t, err) ++ require.Equal(t, n.NodeKey, stored.NodeKey) ++ req.NodeKeySignature = []byte("resigned") ++ resp, err = h.registrationPrelude(context.Background(), req, n.MachineKey) ++ require.NoError(t, err) ++ require.Nil(t, resp, "signature challenge must fall through to upstream authentication") ++ resp, err = h.handleRegister(context.Background(), req, n.MachineKey) ++ require.NoError(t, err) ++ require.NotEmpty(t, resp.AuthURL) ++ require.False(t, resp.MachineAuthorized, "a re-signed key is not user authentication") ++ stored, err = h.state.DB().GetNodeByID(n.ID) ++ require.NoError(t, err) ++ require.Equal(t, n.NodeKey, stored.NodeKey, "key remains unchanged until upstream auth completes") ++ require.Empty(t, stored.TKASignature) ++} ++ ++func TestOmnetMapSnapshotAndOutageFailClosed(t *testing.T) { ++ h, n, f := omnetApp(t) ++ w := httptest.NewRecorder() ++ m := &mapSession{h: h, ctx: context.Background(), req: tailcfg.MapRequest{NodeKey: n.NodeKey}, node: &n, w: w} ++ msg := &tailcfg.MapResponse{Node: &tailcfg.Node{ID: n.ID.NodeID(), Key: n.NodeKey}} ++ require.NoError(t, m.writeTKAMap(msg)) ++ require.Empty(t, msg.Node.KeySignature, "wire decoration must not mutate shared mapper nodes") ++ wire := w.Body.Bytes() ++ var response tailcfg.MapResponse ++ require.NoError(t, json.Unmarshal(wire[4:], &response)) ++ require.Equal(t, []byte("accepted-signature"), []byte(response.Node.KeySignature)) ++ w.Body.Reset() ++ msg.Node.Key = key.NewNode().Public() ++ require.Error(t, m.writeTKAMap(msg)) ++ require.Zero(t, w.Body.Len()) ++ msg.Node.Key = n.NodeKey ++ failure := h.tkaFailure() ++ f.mu.Lock() ++ f.badRead = true ++ f.mu.Unlock() ++ require.Error(t, m.writeTKAMap(msg)) ++ require.Zero(t, w.Body.Len()) ++ select { ++ case <-failure: ++ default: ++ t.Fatal("daemon read failure must stop existing streams") ++ } ++} ++ ++func TestOmnetUnsignedKeyPatchBecomesFullPeer(t *testing.T) { ++ h, self, f := omnetApp(t) ++ peerUser := h.state.CreateUserForTest("omnet-peer") ++ peer := h.state.CreateRegisteredNodeForTest(peerUser, "unsigned-rotated-peer") ++ peer.TKAKey = key.NewNLPrivate().Public() ++ require.NoError(t, h.state.DB().DB.Save(peer).Error) ++ h.state.PutNodeInStoreForTest(*peer) ++ require.NoError(t, h.state.UpdatePolicyManagerUsersForTest()) ++ require.NoError(t, h.state.UpdatePolicyManagerNodesForTest()) ++ f.mu.Lock() ++ f.snapshot.Nodes = append(f.snapshot.Nodes, tkaRegistryNode{peer.ID, peer.NodeKey, peer.TKAKey.Verifier(), nil}) ++ f.mu.Unlock() ++ w := httptest.NewRecorder() ++ m := &mapSession{h: h, ctx: context.Background(), req: tailcfg.MapRequest{NodeKey: self.NodeKey}, node: &self, w: w} ++ msg := &tailcfg.MapResponse{PeersChangedPatch: []*tailcfg.PeerChange{{NodeID: peer.ID.NodeID(), Key: &peer.NodeKey}}} ++ require.NoError(t, m.writeTKAMap(msg)) ++ var response tailcfg.MapResponse ++ require.NoError(t, json.Unmarshal(w.Body.Bytes()[4:], &response)) ++ require.NotNil(t, response.Node) ++ require.Empty(t, response.PeersChangedPatch, "nil signature patch cannot clear prior signature") ++ found := false ++ for _, got := range response.Peers { ++ if got.ID == peer.ID.NodeID() { ++ found = true ++ require.Equal(t, peer.NodeKey, got.Key) ++ require.Empty(t, got.KeySignature) ++ } ++ } ++ require.True(t, found, "full unsigned node replaces prior signed peer") ++} ++ ++func TestOmnetDeletedNoiseIdentityCannotReachAuthority(t *testing.T) { ++ h, n, f := omnetApp(t) ++ node, ok := h.state.GetNodeByID(n.ID) ++ require.True(t, ok) ++ _, err := h.state.DeleteNode(node) ++ require.NoError(t, err) ++ ns := &noiseServer{headscale: h, machineKey: n.MachineKey} ++ body := []byte(fmt.Sprintf("{\"NodeKey\":%q}", n.NodeKey.String())) ++ w := httptest.NewRecorder() ++ ns.tkaRPC(w, httptest.NewRequest(http.MethodGet, "/", bytes.NewReader(body)), 1) ++ require.Equal(t, http.StatusUnauthorized, w.Code) ++ f.mu.Lock() ++ require.NotContains(t, f.calls, byte(1)) ++ f.mu.Unlock() ++ // A rejected identity no longer performs shared persistence work; orphan ++ // removal is the watcher's job, which the fixture drives directly. ++ h.state.TKAMu.Lock() ++ _, _, err = h.tkad.reconcile(context.Background()) ++ h.state.TKAMu.Unlock() ++ require.NoError(t, err) ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ require.Empty(t, f.snapshot.Nodes, "deleted registry identity must be reconciled") ++} ++ ++func TestOmnetRegistrationRejectsInvalidEnvelopeBeforePersistence(t *testing.T) { ++ for _, test := range []struct { ++ name string ++ zeroKey bool ++ signatureSize int ++ }{ ++ {"zero-node-key", true, 1}, ++ {"base64-overflow", false, tkaSignatureLimit + 1}, ++ } { ++ t.Run(test.name, func(t *testing.T) { ++ h, n, f := omnetApp(t) ++ req := tailcfg.RegisterRequest{ ++ OldNodeKey: n.NodeKey, NodeKey: key.NewNode().Public(), NLKey: n.TKAKey, ++ NodeKeySignature: make([]byte, test.signatureSize), ++ } ++ if test.zeroKey { ++ req.NodeKey = key.NodePublic{} ++ } ++ resp, err := h.registrationPrelude(context.Background(), req, n.MachineKey) ++ require.Error(t, err) ++ require.Nil(t, resp) ++ stored, err := h.state.DB().GetNodeByID(n.ID) ++ require.NoError(t, err) ++ require.Equal(t, n.NodeKey, stored.NodeKey) ++ require.Empty(t, stored.TKASignature) ++ f.mu.Lock() ++ require.Empty(t, f.calls, "invalid input is refused before IPC or SQL mutation") ++ f.mu.Unlock() ++ }) ++ } ++} ++ ++func TestOmnetExpiredOwnerCannotAdminister(t *testing.T) { ++ h, n, f := omnetApp(t) ++ expiry := time.Now().Add(-time.Minute) ++ n.Expiry = &expiry ++ require.NoError(t, h.state.DB().DB.Save(&n).Error) ++ h.state.PutNodeInStoreForTest(n) ++ ns := &noiseServer{headscale: h, machineKey: n.MachineKey} ++ body := []byte(fmt.Sprintf("{\"NodeKey\":%q}", n.NodeKey.String())) ++ for _, route := range []byte{1, 2, 6} { ++ w := httptest.NewRecorder() ++ ns.tkaRPC(w, httptest.NewRequest(http.MethodGet, "/", bytes.NewReader(body)), route) ++ require.Equal(t, http.StatusForbidden, w.Code) ++ f.mu.Lock() ++ require.Zero(t, f.lastHeader[5], "expired owner must not assert admin") ++ f.mu.Unlock() ++ } ++} ++ ++func TestOmnetDefinitiveRejectedOutboxIsLocal(t *testing.T) { ++ for _, status := range []int{http.StatusBadRequest, http.StatusForbidden, http.StatusConflict, http.StatusRequestEntityTooLarge} { ++ for _, rotated := range []bool{false, true} { ++ t.Run(fmt.Sprintf("%d/rotated=%t", status, rotated), func(t *testing.T) { ++ h, n, f := omnetApp(t) ++ if rotated { ++ n.NodeKey = key.NewNode().Public() ++ } ++ n.TKASignature = []byte("rejected-pending-signature") ++ if status == http.StatusRequestEntityTooLarge { ++ // Legacy persisted data from before encoded-envelope validation. ++ n.TKASignature = make([]byte, tkaBodyLimit) ++ } ++ require.NoError(t, h.state.DB().DB.Save(&n).Error) ++ h.state.PutNodeInStoreForTest(n) ++ f.mu.Lock() ++ f.rejectSignature = status ++ f.mu.Unlock() ++ failure := h.tkaFailure() ++ h.state.TKAMu.Lock() ++ err := h.tkad.reconcileRegistration(context.Background(), n.ID, n.TKASignature) ++ h.state.TKAMu.Unlock() ++ require.ErrorContains(t, err, "rejected node key signature") ++ stored, err := h.state.DB().GetNodeByID(n.ID) ++ require.NoError(t, err) ++ require.Empty(t, stored.TKASignature, "clear only the rejected forwarding outbox") ++ cached, ok := h.state.GetNodeByID(n.ID) ++ require.True(t, ok) ++ require.Empty(t, cached.AsStruct().TKASignature) ++ require.NoError(t, h.tkaMapReady(context.Background())) ++ select { ++ case <-failure: ++ t.Fatal("a rejected node signature stopped unrelated streams") ++ default: ++ } ++ f.mu.Lock() ++ require.Len(t, f.snapshot.Nodes, 1) ++ require.Equal(t, n.NodeKey, f.snapshot.Nodes[0].NodePublic) ++ if rotated { ++ require.Empty(t, f.snapshot.Nodes[0].KeySignature) ++ } else { ++ require.Equal(t, []byte("accepted-signature"), f.snapshot.Nodes[0].KeySignature) ++ } ++ f.mu.Unlock() ++ w := httptest.NewRecorder() ++ m := &mapSession{h: h, ctx: context.Background(), req: tailcfg.MapRequest{NodeKey: n.NodeKey}, node: &n, w: w} ++ require.NoError(t, m.writeTKAMap(&tailcfg.MapResponse{Node: &tailcfg.Node{ID: n.ID.NodeID(), Key: n.NodeKey}})) ++ }) ++ } ++ } ++} ++ ++func TestOmnetRejectedRegistrationReportsErrorWithoutPoisoningPeers(t *testing.T) { ++ h, n, f := omnetApp(t) ++ peerUser := h.state.CreateUserForTest("unaffected-peer") ++ peer := h.state.CreateRegisteredNodeForTest(peerUser, "unaffected-peer") ++ peer.TKAKey = key.NewNLPrivate().Public() ++ require.NoError(t, h.state.DB().DB.Save(peer).Error) ++ h.state.PutNodeInStoreForTest(*peer) ++ f.mu.Lock() ++ f.rejectSignature = http.StatusForbidden ++ f.snapshot.Nodes = append(f.snapshot.Nodes, tkaRegistryNode{peer.ID, peer.NodeKey, peer.TKAKey.Verifier(), []byte("peer-accepted")}) ++ f.mu.Unlock() ++ req := tailcfg.RegisterRequest{NodeKey: n.NodeKey, NLKey: n.TKAKey, NodeKeySignature: []byte("bad-signature")} ++ err := h.state.TKARegisterCurrent(context.Background(), req, n.MachineKey) ++ require.ErrorContains(t, err, "rejected node key signature") ++ require.NoError(t, h.tkaMapReady(context.Background())) ++ req.NodeKeySignature = nil ++ require.NoError(t, h.state.TKARegisterCurrent(context.Background(), req, n.MachineKey)) ++ require.NoError(t, h.state.TKARegisterCurrent(context.Background(), tailcfg.RegisterRequest{ ++ NodeKey: peer.NodeKey, NLKey: peer.TKAKey, ++ }, peer.MachineKey)) ++ w := httptest.NewRecorder() ++ m := &mapSession{h: h, ctx: context.Background(), req: tailcfg.MapRequest{NodeKey: peer.NodeKey}, node: peer, w: w} ++ require.NoError(t, m.writeTKAMap(&tailcfg.MapResponse{Node: &tailcfg.Node{ID: peer.ID.NodeID(), Key: peer.NodeKey}})) ++ var response tailcfg.MapResponse ++ require.NoError(t, json.Unmarshal(w.Body.Bytes()[4:], &response)) ++ require.Equal(t, []byte("peer-accepted"), []byte(response.Node.KeySignature)) ++} ++ ++func TestOmnetAmbiguousAndUnauthorizedOutboxesRemainFailClosed(t *testing.T) { ++ for _, test := range []struct { ++ name string ++ signedStatus int ++ unsignedStatus int ++ drop bool ++ }{ ++ {"lost-accepted-reply", 0, 0, true}, ++ {"server-error", http.StatusInternalServerError, 0, false}, ++ {"unauthenticated-ipc", http.StatusUnauthorized, 0, false}, ++ {"admin-denied-even-unsigned", http.StatusForbidden, http.StatusForbidden, false}, ++ } { ++ t.Run(test.name, func(t *testing.T) { ++ h, n, f := omnetApp(t) ++ n.TKASignature = []byte("pending") ++ require.NoError(t, h.state.DB().DB.Save(&n).Error) ++ h.state.PutNodeInStoreForTest(n) ++ f.mu.Lock() ++ f.rejectSignature, f.rejectUnsigned = test.signedStatus, test.unsignedStatus ++ if test.drop { ++ f.dropReplyRoute = 9 ++ } ++ f.mu.Unlock() ++ failure := h.tkaFailure() ++ require.Error(t, h.tkaMapReady(context.Background())) ++ stored, err := h.state.DB().GetNodeByID(n.ID) ++ require.NoError(t, err) ++ require.Equal(t, n.TKASignature, stored.TKASignature) ++ select { ++ case <-failure: ++ default: ++ t.Fatal("unresolved transport/auth failure must block publication") ++ } ++ if test.drop { ++ require.NoError(t, h.tkaMapReady(context.Background()), "readback resolves a lost successful reply") ++ stored, err = h.state.DB().GetNodeByID(n.ID) ++ require.NoError(t, err) ++ require.Empty(t, stored.TKASignature) ++ f.mu.Lock() ++ require.Equal(t, 1, f.writes, "accepted readback must not replay") ++ f.mu.Unlock() ++ } ++ }) ++ } ++} ++ ++func TestOmnetCancelledClientDoesNotFailGlobalHealth(t *testing.T) { ++ h, n, f := omnetApp(t) ++ failure := h.tkaFailure() ++ ctx, cancel := context.WithCancel(context.Background()) ++ cancel() ++ w := httptest.NewRecorder() ++ m := &mapSession{h: h, ctx: ctx, req: tailcfg.MapRequest{NodeKey: n.NodeKey}, node: &n, w: w} ++ require.ErrorIs(t, m.writeTKAMap(&tailcfg.MapResponse{KeepAlive: true}), context.Canceled) ++ require.ErrorIs(t, h.tkaMapReady(ctx), context.Canceled) ++ _, _, err := h.tkad.rpc(ctx, 11, true, 0, []byte("{}")) ++ require.Error(t, err) ++ // Also disconnect after reconciliation has started a live daemon read. ++ ctx, cancel = context.WithCancel(context.Background()) ++ m.ctx = ctx ++ started, release := make(chan struct{}), make(chan struct{}) ++ var once sync.Once ++ f.mu.Lock() ++ f.beforeReply = func(route byte) { ++ if route == 11 { ++ once.Do(func() { close(started); <-release }) ++ } ++ } ++ f.mu.Unlock() ++ done := make(chan error, 1) ++ go func() { done <- m.writeTKAMap(&tailcfg.MapResponse{KeepAlive: true}) }() ++ <-started ++ cancel() ++ close(release) ++ require.ErrorIs(t, <-done, context.Canceled) ++ require.Empty(t, w.Body.Bytes()) ++ select { ++ case <-failure: ++ t.Fatal("client cancellation closed another client's failure channel") ++ default: ++ } ++ require.NoError(t, h.tkaMapReady(context.Background())) ++} ++ ++func TestOmnetNonKeyPatchNeverCarriesCurrentSignature(t *testing.T) { ++ h, n, f := omnetApp(t) ++ f.mu.Lock() ++ f.snapshot.Nodes[0].KeySignature = []byte("new-key-signature") ++ f.mu.Unlock() ++ w := httptest.NewRecorder() ++ m := &mapSession{h: h, ctx: context.Background(), req: tailcfg.MapRequest{NodeKey: n.NodeKey}, node: &n, w: w} ++ msg := &tailcfg.MapResponse{PeersChangedPatch: []*tailcfg.PeerChange{{ ++ NodeID: n.ID.NodeID(), KeySignature: []byte("queued-old-signature"), ++ }}} ++ require.NoError(t, m.writeTKAMap(msg)) ++ var response tailcfg.MapResponse ++ require.NoError(t, json.Unmarshal(w.Body.Bytes()[4:], &response)) ++ require.Len(t, response.PeersChangedPatch, 1) ++ require.Empty(t, response.PeersChangedPatch[0].KeySignature) ++ require.Equal(t, []byte("queued-old-signature"), []byte(msg.PeersChangedPatch[0].KeySignature)) ++} ++ ++type omnetBlockedWriter struct { ++ *httptest.ResponseRecorder ++ started chan struct{} ++ release chan struct{} ++ once sync.Once ++ mu sync.Mutex ++ deadlines []time.Time ++} ++ ++func (w *omnetBlockedWriter) Write(p []byte) (int, error) { ++ w.once.Do(func() { close(w.started); <-w.release }) ++ return w.ResponseRecorder.Write(p) ++} ++ ++func (w *omnetBlockedWriter) SetWriteDeadline(deadline time.Time) error { ++ w.mu.Lock() ++ defer w.mu.Unlock() ++ w.deadlines = append(w.deadlines, deadline) ++ return nil ++} ++ ++func TestOmnetSlowWriterReleasesBarrierAndKeepsFrameOrder(t *testing.T) { ++ h, n, f := omnetApp(t) ++ w := &omnetBlockedWriter{ResponseRecorder: httptest.NewRecorder(), started: make(chan struct{}), release: make(chan struct{})} ++ m := &mapSession{h: h, ctx: context.Background(), req: tailcfg.MapRequest{NodeKey: n.NodeKey}, node: &n, w: w} ++ msg := &tailcfg.MapResponse{Node: &tailcfg.Node{ID: n.ID.NodeID(), Key: n.NodeKey}} ++ done := make(chan error, 1) ++ go func() { done <- m.writeTKAMap(msg) }() ++ <-w.started ++ locked := h.state.TKAMu.TryLock() ++ if !locked { ++ close(w.release) ++ <-done ++ t.Fatal("client write holds the global publication barrier") ++ } ++ f.mu.Lock() ++ f.snapshot.Nodes[0].KeySignature = []byte("new-snapshot") ++ f.snapshot.Revision++ ++ f.mu.Unlock() ++ h.state.TKAMu.Unlock() ++ other := httptest.NewRecorder() ++ peer := &mapSession{h: h, ctx: context.Background(), req: tailcfg.MapRequest{NodeKey: n.NodeKey}, node: &n, w: other} ++ err := peer.writeTKAMap(msg) ++ close(w.release) ++ require.NoError(t, <-done) ++ require.NoError(t, err, "another client's write must complete while the first is blocked") ++ require.NoError(t, m.writeTKAMap(msg)) ++ wire := w.Body.Bytes() ++ for _, signature := range []string{"accepted-signature", "new-snapshot"} { ++ require.GreaterOrEqual(t, len(wire), 4) ++ size := int(binary.LittleEndian.Uint32(wire[:4])) ++ require.GreaterOrEqual(t, len(wire), 4+size) ++ var response tailcfg.MapResponse ++ require.NoError(t, json.Unmarshal(wire[4:4+size], &response)) ++ require.Equal(t, []byte(signature), []byte(response.Node.KeySignature)) ++ wire = wire[4+size:] ++ } ++ require.Empty(t, wire) ++} ++ ++func TestOmnetStoppedQueuedWriteCannotExtendStopDeadline(t *testing.T) { ++ h, n, _ := omnetApp(t) ++ w := &omnetBlockedWriter{ResponseRecorder: httptest.NewRecorder(), started: make(chan struct{}), release: make(chan struct{})} ++ close(w.release) ++ m := &mapSession{h: h, ctx: context.Background(), req: tailcfg.MapRequest{NodeKey: n.NodeKey}, node: &n, w: w, cancelCh: make(chan struct{})} ++ h.state.TKAMu.Lock() ++ done := make(chan error, 1) ++ go func() { done <- m.writeMap(&tailcfg.MapResponse{KeepAlive: true}) }() ++ require.Eventually(t, m.writing.Load, time.Second, time.Millisecond) ++ m.stopFromBatcher() ++ h.state.TKAMu.Unlock() ++ require.ErrorIs(t, <-done, errMapSessionStopped) ++ w.mu.Lock() ++ defer w.mu.Unlock() ++ require.Len(t, w.deadlines, 1, "no later write may replace the stop deadline") ++ require.Empty(t, w.Body.Bytes()) ++} ++ ++func TestOmnetKeyReuseRecoveryVacatesAllKeysFirst(t *testing.T) { ++ for _, lostRemovalReply := range []bool{false, true} { ++ t.Run(fmt.Sprintf("lost-removal=%t", lostRemovalReply), func(t *testing.T) { ++ h, first, f := omnetApp(t) ++ otherUser := h.state.CreateUserForTest("reuse-peer") ++ second := h.state.CreateRegisteredNodeForTest(otherUser, "reuse-peer") ++ second.TKAKey = key.NewNLPrivate().Public() ++ oldFirst, oldSecond := first.NodeKey, second.NodeKey ++ f.mu.Lock() ++ f.snapshot.Nodes = append(f.snapshot.Nodes, tkaRegistryNode{second.ID, oldSecond, second.TKAKey.Verifier(), nil}) ++ if lostRemovalReply { ++ f.dropReplyRoute = 10 ++ } ++ f.mu.Unlock() ++ // A cycle is stronger than row ordering: neither key can be claimed ++ // until both old holders have been removed. ++ first.NodeKey, second.NodeKey = oldSecond, oldFirst ++ first.TKASignature, second.TKASignature = []byte("first-new"), []byte("second-new") ++ require.NoError(t, h.state.DB().DB.Save(&first).Error) ++ require.NoError(t, h.state.DB().DB.Save(second).Error) ++ h.state.PutNodeInStoreForTest(first) ++ h.state.PutNodeInStoreForTest(*second) ++ if lostRemovalReply { ++ require.Error(t, h.tkaMapReady(context.Background())) ++ stored, err := h.state.DB().GetNodeByID(first.ID) ++ require.NoError(t, err) ++ require.Equal(t, first.TKASignature, stored.TKASignature) ++ } ++ require.NoError(t, h.tkaMapReady(context.Background())) ++ f.mu.Lock() ++ require.Len(t, f.snapshot.Nodes, 2) ++ for _, got := range f.snapshot.Nodes { ++ want := first ++ if got.NodeID == second.ID { ++ want = *second ++ } ++ require.Equal(t, want.NodeKey, got.NodePublic) ++ require.Equal(t, want.TKASignature, got.KeySignature) ++ } ++ mutations := slices.DeleteFunc(slices.Clone(f.calls), func(route byte) bool { return route == 11 }) ++ require.Equal(t, []byte{10, 10, 9, 9}, mutations, "vacate before claim, even after an ambiguous removal") ++ f.mu.Unlock() ++ }) ++ } ++} ++ ++func TestOmnetFollowupReturnsAuthenticationFailure(t *testing.T) { ++ h, n, _ := omnetApp(t) ++ id := types.MustAuthID() ++ request := types.NewRegisterAuthRequest(&types.RegistrationData{MachineKey: n.MachineKey, NodeKey: n.NodeKey}) ++ h.state.SetAuthCacheEntry(id, request) ++ rejection := fmt.Errorf("omnet rejected node key signature") ++ request.FinishAuth(types.AuthVerdict{Err: rejection}) ++ resp, err := h.waitForFollowup(context.Background(), tailcfg.RegisterRequest{ ++ NodeKey: n.NodeKey, Followup: "http://localhost/register/" + id.String(), ++ }, n.MachineKey) ++ require.ErrorIs(t, err, rejection) ++ require.Nil(t, resp, "rejection must not become a fresh login or authorized response") ++} ++ ++func TestOmnetRPCWritesOutsidePublicationBarrier(t *testing.T) { ++ for _, authorized := range []bool{false, true} { ++ t.Run(fmt.Sprintf("authorized=%t", authorized), func(t *testing.T) { ++ h, n, _ := omnetApp(t) ++ machine := n.MachineKey ++ if !authorized { ++ machine = key.NewMachine().Public() ++ } ++ ns := &noiseServer{headscale: h, machineKey: machine} ++ w := &omnetBlockedWriter{ResponseRecorder: httptest.NewRecorder(), started: make(chan struct{}), release: make(chan struct{})} ++ body := []byte(fmt.Sprintf("{\"NodeKey\":%q}", n.NodeKey.String())) ++ done := make(chan struct{}) ++ go func() { ++ ns.tkaRPC(w, httptest.NewRequest(http.MethodGet, "/", bytes.NewReader(body)), 1) ++ close(done) ++ }() ++ <-w.started ++ locked := h.state.TKAMu.TryLock() ++ if locked { ++ h.state.TKAMu.Unlock() ++ } ++ close(w.release) ++ <-done ++ require.True(t, locked, "both success and error writes must release the barrier") ++ want := http.StatusUnauthorized ++ if authorized { ++ want = http.StatusOK ++ } ++ require.Equal(t, want, w.Code) ++ }) ++ } ++} +diff --git a/hscontrol/types/node.go b/hscontrol/types/node.go +index 4d65e4b..22ab2eb 100644 +--- a/hscontrol/types/node.go ++++ b/hscontrol/types/node.go +@@ -121,6 +121,11 @@ type Node struct { + NodeKey key.NodePublic `gorm:"serializer:text"` + DiscoKey key.DiscoPublic `gorm:"serializer:text"` + ++ // TKAKey is authenticated registration metadata, not a trusted authority key. ++ // TKASignature is a durable forwarding outbox, never a map-ready signature. ++ TKAKey key.NLPublic `gorm:"serializer:text"` ++ TKASignature []byte ++ + Endpoints AddrPorts `gorm:"serializer:json"` + + Hostinfo *tailcfg.Hostinfo `gorm:"column:host_info;serializer:json"` +diff --git a/hscontrol/types/registration.go b/hscontrol/types/registration.go +index 669114d..839620f 100644 +--- a/hscontrol/types/registration.go ++++ b/hscontrol/types/registration.go +@@ -25,7 +25,9 @@ type RegistrationData struct { + + // NodeKey is the cryptographic identity of the node session. + // Required. +- NodeKey key.NodePublic ++ NodeKey key.NodePublic ++ TKAKey key.NLPublic ++ TKASignature []byte + + // DiscoKey is the disco public key for peer-to-peer connections. + DiscoKey key.DiscoPublic +diff --git a/hscontrol/types/tka.go b/hscontrol/types/tka.go +new file mode 100644 +index 0000000..5eda25e +--- /dev/null ++++ b/hscontrol/types/tka.go +@@ -0,0 +1,9 @@ ++package types ++ ++// OmnetCheckpoint prevents a restarted adapter from silently accepting an older ++// or empty daemon snapshot. Headscale and tkad must be backed up as one pair. ++// This is an observed transport revision, not replicated authority state. ++type OmnetCheckpoint struct { ++ ID uint `gorm:"primary_key"` ++ Revision uint64 ++} +diff --git a/hscontrol/types/types_clone.go b/hscontrol/types/types_clone.go +index 315cabf..6696770 100644 +--- a/hscontrol/types/types_clone.go ++++ b/hscontrol/types/types_clone.go +@@ -45,6 +45,7 @@ func (src *Node) Clone() *Node { + } + dst := new(Node) + *dst = *src ++ dst.TKASignature = append(src.TKASignature[:0:0], src.TKASignature...) + dst.Endpoints = append(src.Endpoints[:0:0], src.Endpoints...) + dst.Hostinfo = src.Hostinfo.Clone() + if dst.IPv4 != nil { +@@ -86,6 +87,8 @@ var _NodeCloneNeedsRegeneration = Node(struct { + MachineKey key.MachinePublic + NodeKey key.NodePublic + DiscoKey key.DiscoPublic ++ TKAKey key.NLPublic ++ TKASignature []byte + Endpoints AddrPorts + Hostinfo *tailcfg.Hostinfo + IPv4 *netip.Addr +diff --git a/hscontrol/types/types_view.go b/hscontrol/types/types_view.go +index 35fffee..9e8c6a4 100644 +--- a/hscontrol/types/types_view.go ++++ b/hscontrol/types/types_view.go +@@ -193,10 +193,15 @@ func (v *NodeView) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + return nil + } + +-func (v NodeView) ID() NodeID { return v.ж.ID } +-func (v NodeView) MachineKey() key.MachinePublic { return v.ж.MachineKey } +-func (v NodeView) NodeKey() key.NodePublic { return v.ж.NodeKey } +-func (v NodeView) DiscoKey() key.DiscoPublic { return v.ж.DiscoKey } ++func (v NodeView) ID() NodeID { return v.ж.ID } ++func (v NodeView) MachineKey() key.MachinePublic { return v.ж.MachineKey } ++func (v NodeView) NodeKey() key.NodePublic { return v.ж.NodeKey } ++func (v NodeView) DiscoKey() key.DiscoPublic { return v.ж.DiscoKey } ++ ++// TKAKey is authenticated registration metadata, not a trusted authority key. ++// TKASignature is a durable forwarding outbox, never a map-ready signature. ++func (v NodeView) TKAKey() key.NLPublic { return v.ж.TKAKey } ++func (v NodeView) TKASignature() views.ByteSlice[[]byte] { return views.ByteSliceOf(v.ж.TKASignature) } + func (v NodeView) Endpoints() views.Slice[netip.AddrPort] { return views.SliceOf(v.ж.Endpoints) } + func (v NodeView) Hostinfo() tailcfg.HostinfoView { return v.ж.Hostinfo.View() } + func (v NodeView) IPv4() views.ValuePointer[netip.Addr] { return views.ValuePointerOf(v.ж.IPv4) } +@@ -287,6 +292,8 @@ var _NodeViewNeedsRegeneration = Node(struct { + MachineKey key.MachinePublic + NodeKey key.NodePublic + DiscoKey key.DiscoPublic ++ TKAKey key.NLPublic ++ TKASignature []byte + Endpoints AddrPorts + Hostinfo *tailcfg.Hostinfo + IPv4 *netip.Addr diff --git a/integration/headscale/headscale.pin b/integration/headscale/headscale.pin new file mode 100644 index 0000000..dedfe92 --- /dev/null +++ b/integration/headscale/headscale.pin @@ -0,0 +1,4 @@ +HEADSCALE_URL=https://github.com/juanfont/headscale.git +HEADSCALE_VERSION=v0.29.6 +HEADSCALE_COMMIT=a2b1d7863926834e94479dcdd91ab344a9356bd0 +HEADSCALE_GO_TOOLCHAIN=go1.27.3 diff --git a/integration/headscale/tailscale.LICENSE b/integration/headscale/tailscale.LICENSE new file mode 100644 index 0000000..ed6e4bb --- /dev/null +++ b/integration/headscale/tailscale.LICENSE @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2020 Tailscale Inc & contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 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..d087046 --- /dev/null +++ b/om/json/test/run.py @@ -0,0 +1,111 @@ +#!/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") +# Output is compared byte for byte, and Go 1.27 changed encoding/json escaping +# of invalid UTF-8. Pin the release the committed corpus was generated with; +# an explicit GOTOOLCHAIN still wins. +oracle_env = dict(os.environ) +oracle_env.setdefault("GOTOOLCHAIN", "go1.26.8") +subprocess.run([go, "build", "-mod=mod", "-o", str(OUT / "oracle"), "."], cwd=HERE / "oracle", env=oracle_env, 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/om/tka/README.md b/om/tka/README.md new file mode 100644 index 0000000..38b7fbf --- /dev/null +++ b/om/tka/README.md @@ -0,0 +1,129 @@ +# Bounded Tailnet Key Authority + +Omega implementation of the typed AUM, Key, State and AUM Signature models, signature authorization, +state transitions, and an in-memory authority DAG. Behavior is pinned to +[Tailscale v1.102.0](https://github.com/tailscale/tailscale/tree/v1.102.0/tka), particularly `aum.go`, +`key.go`, `state.go`, `tka.go`, and `sync.go`. No production Go code or node-key-signature implementation +is included here. Node-key signatures belong to `om/tkasig`. + +## Composition + +Concatenate `om/blake2s/blake2s.om`, `om/sha512/sha512.om`, `om/ed25519/ed25519.om`, +`om/cbor/cbor.om`, `tka.om`, `tkastate.om`, and, for the authority API, `tkapool.om`, before the caller. +The first two TKA files are global-free functions. Include the pool companion only once. +There is no filesystem, daemon, persistence, compaction, network configuration, or concurrency in +this unit. Callers serialize pool access and persist a successful transaction before publishing it. + +## Model API + +Unless stated otherwise, byte buffers have capacity 65536 and lengths are `ulong`. +Lengths 0–65536 are successful; errors are 65537 (typed CBOR), 65538 (resource limit), +65539 (static validation), 65540 (signature), 65541 (parent/key/state), 65542 (not initialized, +transaction misuse, or no sync intersection). Success/error must be checked before consuming output. + +* `tkamodel(input,n,schema,out,keep)` decodes a complete typed object and reconstructs its encoding. + Schemas: 1 AUM, 2 Key, 3 State, 4 AUM signature. `keep=0` gives canonical serialization; + `keep=1` is an internal typed representation retaining empty-but-non-nil optional values. + In particular an empty metadata map is not interchangeable with nil during UpdateKey validation. + The output is unchanged on failure. Input and output must be distinct arrays. +* `tkadec(input,n,out)` is canonical AUM reconstruction. Unknown fields are checked for CBOR + well-formedness then dropped; non-shortest encodings, reordered maps, decimal field-name text keys, + and integer arrays for byte slices are accepted as upstream accepts them. Duplicates and typed + errors reject. Hashing never uses received bytes directly. +* `tkahash(input,n,sig,out32)` returns 0 or an error. `sig=0` computes AUM Hash, `sig=1` SigHash. +* `tkavalid(input,n)` returns 0 or an error for upstream StaticValidate, separate from authorization. + Unknown AUM kinds are valid forward-compatible no-ops, not an unsupported-version error. +* `tkatrans(aum,n,state,sn,out,genesis)` verifies and applies to a typed State, returning its new + encoded length. `genesis=1` is only for bootstrap, and skips parent matching. On failure the caller + must discard `out`; the input state is never changed. All signatures must name trusted keys and + verify under ZIP-215, even when another signature is valid. Duplicate signatures are valid but + count once for fork weight. The last key cannot be removed. Checkpoints preserve both StateIDs. + +Internal token helpers require a successfully normalized model and successful `cbrdec`; they are +not hostile-byte entry points. Public lengths are checked before CBOR or cryptographic calls. +The cryptographic implementation is variable-time and has not been constant-time audited. + +## Authority API + +Two independent authority slots permit bounded in-process synchronization. `tkaselect(slot)` selects +0 or 1 (returns 0 or resource error). `tkareset()` explicitly clears the selected slot. A slot holds +128 immutable AUM nodes, each with up to 65536 encoded AUM bytes and 65536 state bytes. The two slots +reserve approximately 32 MiB plus metadata globally; fixed-size per-operation scratch lives on the +Omega stack. State keys are bounded at 512 (including AddKey), disablement values at 32, and key +metadata at 512 UTF-8 bytes. Input CBOR retains its existing depth16/array4096/map1024 limits. +These are resource errors where tighter than upstream; no eviction or hidden history truncation occurs. + +* `tkaboot(input,n)` accepts a signed checkpoint into an empty authority, returning 0 or error. + Later checkpoints with a non-nil parent may bootstrap, just as upstream permits. +* `tkainform(input,spans,count)` accepts a batch atomically. `spans` is `ulong[256]`, alternating + offset,length for at most128 messages in one input buffer. Parents precede children. On any error, + the visible node count, head, states and key table remain unchanged. Already-stored canonical hashes + are idempotent and skip static/signature revalidation, matching upstream. +* For a batch larger than one input buffer, `tkabegin()`, successive `tkastage(input,n)`, and + `tkacommit()` provide the same transaction. A failed stage automatically aborts the entire batch; + explicit `tkaabort()` is also available. The caller must not query or interleave other operations + while staging. +* `tkahead(out32)` returns 0 or error. `tkacurrent(out)` and `tkastate(hash32,out)` return the encoded + current state or a state at any retained branch node; canonicalize with schema3 for wire output. +* `tkakeys(out16384)` returns the count of concatenated 32-byte Ed25519 public keys, or error. + This is the trusted-key table for `nksauth`; regenerate after a committed head change. Keys with + malformed public lengths (which upstream static validation allows) cannot authorize signatures + and are not exported. +* `tkaoffer(out)` writes head followed by ancestor hashes and returns the total hash count. + Samples occur at absolute depths4,16,64; oldest is appended unconditionally, including an oldest + already sampled at an exact sampling boundary. A 128-node DAG cannot reach the next sample256. +* `tkainter(offer,count,mode1)` returns the intersecting node index or error. `mode1[0]` is0 for + up-to-date,1 for head intersection,2 for tail intersection. Offers contain at most2048 hashes. +* `tkamissing(offer,count,nodes128)` returns a count of ordered local node indices. Fetch each AUM + using `tkaget(index,0,out)`, then canonicalize with schema1 for transport. Only the chosen primary + continuation is sent, not every off-chain branch. An equal head returns no updates. + +The fork rule is highest unique signer vote sum, then RemoveKey over non-RemoveKey, then lowest +canonical AUM hash bytewise. Cached state at every node makes arbitrary retained-branch state lookup +bounded, and avoids replay during signature verification. A checkpoint can replace keys and disablement +values but cannot change the authority IDs. + +## Tests + +Run `TKA_GO=/path/to/go1.26.8 sh om/tka/test/run.sh /path/to/pinned/omc` from the repository. +`tools/omc.sh` supplies the pinned compiler when omitted. Requirements: ARM64 Linux, Python3, +POSIX shell, Go>=1.26.5, and dependencies pinned in `test/oracle/go.mod` and `go.sum`. + +The Go oracle imports the real pinned `tailscale.com/tka` and emits deterministic commands and expected +records. The Omega driver executes those same commands. Scenarios cover bootstrap and later-checkpoint +bootstrap, add/update/remove/checkpoint, state lookup, StateID rejection, unknown kinds, untrusted and +invalid signatures, unknown parents, batch rollback, duplicates, vote and hash fork ties, last-key +removal, sync intersections, exact ancestor sampling boundaries, and convergence. Explicit bounded-profile +cases check 128-node exhaustion, capacity-failure rollback, and rejection of a 513th key. Existing CBOR +structure/hostile/fuzz AUM and State corpora are re-judged through the typed model (not merely generic +CBOR well-formedness). A signature-verification mutant must run to normal completion with the same +record count and at least one changed result; traps, signals, or an incomplete run fail the harness. +The focused suite was executed with Go1.26.8 and the pinned compiler: **PASS, 10,691 differential +records**, and the signature mutant completed all 10,691 records with four differences. The separate +cross-unit revocation driver also completed successfully: a direct node signature authorizes after +bootstrap and rejects after its trusted key is removed by a signed AUM. + +`test/revocation.om` is compiled with both authority and node-signature units by the harness. +The oracle's `--fixture` mode emits JSON with hex `genesis`, `removal`, `signature`, and raw32-byte +`node` fields. It constructs the signed pubkey through upstream NodePublic.MarshalBinary (including +the `np` prefix) and asserts upstream authorization before, and rejection after, revocation. +For standalone use: run `go run -mod=readonly . --fixture` in `test/oracle`. + +Fixed-array hash decoding follows upstream padding/truncation semantics, while byte slices preserve +nil versus empty for serialization. Static key-ID equality follows Go bytes.Equal, which treats nil +and empty as equal; these semantics have dedicated typed-model cases. +An empty-but-present update metadata map is exercised through explicit wire bytes: it clears +metadata, then replay of its canonically omitted form is accepted by the already-stored hash without +revalidating the now-missing update field. +The corpus also exercises all 256 simple-number encodings in seven typed destinations. As upstream +fxamacker `fillPositiveInt` specifies, major7 simple values with additional-information0–19 or24 +populate unsigned fields and byte-array elements; Boolean values remain type errors, and null or +undefined leave zero values. + +### Third-party material and notices + +Protocol behavior and translated algorithms derive from Tailscale v1.102.0, commit +`35283c95445fb198af1ce708dac05714bdfaa037`, fetched2026-10-25. Copyright Tailscale Inc & contributors, +BSD-3-Clause; the upstream notice is shipped verbatim in `tailscale.LICENSE`. The Go decoder options +are transcribed from `tka/tka.go` and covered by that notice. Other Go code is only an external test +oracle. Shared CBOR vectors retain their provenance and notices in `om/cbor`. diff --git a/om/tka/tailscale.LICENSE b/om/tka/tailscale.LICENSE new file mode 100644 index 0000000..ed6e4bb --- /dev/null +++ b/om/tka/tailscale.LICENSE @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2020 Tailscale Inc & contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/om/tka/test/check.py b/om/tka/test/check.py new file mode 100755 index 0000000..31ccae5 --- /dev/null +++ b/om/tka/test/check.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""A mutant must complete normally with exactly the expected record count.""" +import pathlib +import sys + +want = pathlib.Path(sys.argv[1]).read_text().splitlines() +got = pathlib.Path(sys.argv[2]).read_text().splitlines() +if len(want) != len(got): + for i, (a, b) in enumerate(zip(want, got)): + if a != b: + print(f"first difference record {i + 1}: expected {a[:240]}, got {b[:240]}") + break + raise SystemExit(f"FAIL record count: expected {len(want)}, got {len(got)}") +bad = [i for i, pair in enumerate(zip(want, got)) if pair[0] != pair[1]] +if sys.argv[3] == "mutant": + if not bad: + raise SystemExit("FAIL mutant survived") + print(f"PASS mutant: completed {len(got)} records, {len(bad)} differ") +else: + if bad: + for i in bad[:10]: + print(f"record {i + 1}: expected {want[i][:240]}, got {got[i][:240]}") + raise SystemExit(f"FAIL {len(bad)} differing records") + print(f"PASS {len(got)} differential records") diff --git a/om/tka/test/driver.om b/om/tka/test/driver.om new file mode 100644 index 0000000..7424caa --- /dev/null +++ b/om/tka/test/driver.om @@ -0,0 +1,207 @@ +note SPDX-License-Identifier: Apache-2.0 +note Binary commands: opcode, authority slot, uint32 LE payload length, payload. +global tki uchar 65536 +global tkn ulong 2 +fn tdgetc to long +if eq get tkn 0 get tkn 1 +r = read 0 tki 0 65536 +if le r 0 +ret -1 +end +put tkn 0 0 +put tkn 1 ulong r +end +p = get tkn 0 +put tkn 0 add p 1 +ret long get tki p +end +fn tdhex v ulong to uchar +if lt v 10 +ret uchar add v 48 +end +ret uchar add v 87 +end +fn tdout d view uchar 65536 n ulong to void +h = new uchar 131073 0 +for i ulong n +v = ulong get d i +put h mul i 2 tdhex shr v 4 +put h add mul i 2 1 tdhex and v 15 +end +put h mul n 2 10 +r = write 1 h 0 add mul n 2 1 +end +fn tdhash h view uchar 32 to void +b = new uchar 65536 0 +for i ulong 32 +put b i get h i +end +tdout b 32 +end +fn tdstatus z ulong to void +b = new uchar 65536 0 +put b 0 0 +if ge z 65537 +put b 0 1 +end +tdout b 1 +end +fn tdbatch d view uchar 65536 n ulong to ulong +if eq n 0 +ret 65538 +end +cnt = ulong get d 0 +spans = new ulong 256 0 +p = ulong 1 +if gt cnt 128 +ret 65538 +end +for i ulong cnt +if gt add p 4 n +ret 65538 +end +z = ulong 0 +for j ulong 4 +z = or z shl ulong get d add p j mul j 8 +end +p = add p 4 +if gt z sub n p +ret 65538 +end +put spans mul i 2 p +put spans add mul i 2 1 z +p = add p z +end +ret tkainform d spans cnt +end +fn tdmodel d view uchar 65536 n ulong schema ulong to void +b = new uchar 65536 0 +z = tkamodel d n schema b 0 +tdstatus z +if gt z 65536 +ret +end +tdout b z +h = new uchar 32 0 +if eq schema 1 +v = tkahash d n 0 h +tdhash h +v = tkahash d n 1 h +tdhash h +tdstatus tkavalid d n +end +end +fn tdhcopy h view uchar 32 b edit uchar 65536 p ulong to void +for i ulong 32 +put b add p i get h i +end +end + +fn tdcommand cmd ulong d view uchar 65536 n ulong to void +h = new uchar 32 0 +b = new uchar 65536 0 +c = new uchar 65536 0 +nodes = new ulong 128 0 +keys = new uchar 16384 0 +if eq cmd 1 +tdmodel d n 1 +ret +end +if and ge cmd 11 le cmd 14 +tdmodel d n sub cmd 10 +ret +end +if eq cmd 4 +tkareset +tdstatus 0 +ret +end +if or eq cmd 2 eq cmd 3 +z = ulong 0 +if eq cmd 2 +z = tkaboot d n +else +z = tdbatch d n +end +tdstatus z +v = tkahead h +tdhash h +ret +end +if eq cmd 5 +z = tkaoffer b +tdstatus z +if lt z 65537 +tdout b mul z 32 +end +ret +end +if eq cmd 6 +z = tkamissing d div n 32 nodes +tdstatus z +if lt z 65537 +for i ulong z +tkahget get nodes i h +tdhcopy h b mul i 32 +end +tdout b mul z 32 +end +ret +end +if eq cmd 7 +for j ulong 32 +put h j get d j +end +z = tkastate h b +tdstatus z +if lt z 65537 +v = tkamodel b z 3 c 0 +tdout c v +end +ret +end +if eq cmd 8 +z = tkakeys keys +tdstatus z +if lt z 65537 +for i ulong mul z 32 +put b i get keys i +end +tdout b mul z 32 +end +end +end +fn main to int +b = new uchar 65536 0 +while true bound 100000 +cmd = tdgetc +if lt cmd 0 +ret 0 +end +slot = tdgetc +if or lt slot 0 gt slot 1 +ret 2 +end +x = tkaselect ulong slot +n = ulong 0 +for j ulong 4 +v = tdgetc +if lt v 0 +ret 2 +end +n = or n shl ulong v mul j 8 +end +if gt n 65536 +ret 2 +end +for j ulong n +v = tdgetc +if lt v 0 +ret 2 +end +put b j uchar v +end +tdcommand ulong cmd b n +end +ret 2 +end diff --git a/om/tka/test/oracle/go.mod b/om/tka/test/oracle/go.mod new file mode 100644 index 0000000..f4b4e3d --- /dev/null +++ b/om/tka/test/oracle/go.mod @@ -0,0 +1,19 @@ +module omnet/tka-oracle + +go 1.26.5 + +require ( + github.com/fxamacker/cbor/v2 v2.9.0 + golang.org/x/crypto v0.54.0 + tailscale.com v1.102.0 +) + +require ( + filippo.io/edwards25519 v1.2.0 // indirect + github.com/go-json-experiment/json v0.0.0-20260214004413-d219187c3433 // indirect + github.com/hdevalence/ed25519consensus v0.2.0 // indirect + github.com/x448/float16 v0.8.4 // indirect + go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect + golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect + golang.org/x/sys v0.47.0 // indirect +) diff --git a/om/tka/test/oracle/go.sum b/om/tka/test/oracle/go.sum new file mode 100644 index 0000000..4ab405b --- /dev/null +++ b/om/tka/test/oracle/go.sum @@ -0,0 +1,32 @@ +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= +github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +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= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/hdevalence/ed25519consensus v0.2.0 h1:37ICyZqdyj0lAZ8P4D1d1id3HqbbG1N3iBb1Tb4rdcU= +github.com/hdevalence/ed25519consensus v0.2.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +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= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +tailscale.com v1.102.0 h1:yAYrykMZWlgp7Qq2ECDrDnxeySWBhNXNMkXdDmVMyrE= +tailscale.com v1.102.0/go.mod h1:NdndXfkSklVPbRUZMAzzRuDNaR5B+YWGbAyE1HpSQZg= diff --git a/om/tka/test/oracle/main.go b/om/tka/test/oracle/main.go new file mode 100644 index 0000000..edbbf48 --- /dev/null +++ b/om/tka/test/oracle/main.go @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: Apache-2.0 +// Test-only oracle. Protocol decisions come from the pinned tailscale.com/tka. +package main + +import ( + "bufio" + "bytes" + "crypto/ed25519" + "encoding/json" + "encoding/binary" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/fxamacker/cbor/v2" + "tailscale.com/tka" + "tailscale.com/types/tkatype" + "tailscale.com/types/key" +) + +var input, expected *os.File +var auth [2]*tka.Authority +var store [2]*tka.Mem +var enc cbor.EncMode +var dec cbor.DecMode +func must(err error) { if err != nil { panic(err) } } +func emit(cmd, slot byte, data []byte) { input.Write([]byte{cmd,slot}); must(binary.Write(input,binary.LittleEndian,uint32(len(data)))); input.Write(data) } +func line(b []byte) { fmt.Fprintf(expected,"%x\n",b) } +func status(err error) { if err != nil { line([]byte{1}) } else { line([]byte{0}) } } +func marshal(v any) []byte { b,e:=enc.Marshal(v); must(e); return b } +func model(b []byte, schema byte) { + emit(10+schema,0,b) + var a tka.AUM + var value any + var err error + switch schema {case 1: err=a.Unserialize(b); value=a; case 2: var k tka.Key; err=dec.Unmarshal(b,&k); value=k; case 3: var s tka.State; err=dec.Unmarshal(b,&s); value=s; case 4: var s tkatype.Signature; err=dec.Unmarshal(b,&s); value=s} + status(err); if err!=nil{return}; line(marshal(value)) + if schema==1 { h:=a.Hash(); line(h[:]); sh:=a.SigHash(); line(sh[:]); status(a.StaticValidate()) } +} +func reset(slot byte) { emit(4,slot,nil); status(nil); store[slot]=tka.ChonkMem(); auth[slot]=nil } +func head(slot byte) { var h tka.AUMHash; if auth[slot]!=nil {h=auth[slot].Head()}; line(h[:]) } +func boot(slot byte,a tka.AUM) { emit(2,slot,a.Serialize()); v,e:=tka.Bootstrap(store[slot],a); if e==nil{auth[slot]=v}; status(e); head(slot) } +func inform(slot byte, updates ...tka.AUM) { + var b bytes.Buffer; b.WriteByte(byte(len(updates))) + for _,a:=range updates { raw:=a.Serialize(); binary.Write(&b,binary.LittleEndian,uint32(len(raw))); b.Write(raw) } + emit(3,slot,b.Bytes()); err:=auth[slot].Inform(store[slot],updates); status(err); head(slot) +} +func informRaw(slot byte, raw []byte) { + var a tka.AUM;must(a.Unserialize(raw)) + var b bytes.Buffer;b.WriteByte(1);binary.Write(&b,binary.LittleEndian,uint32(len(raw)));b.Write(raw) + emit(3,slot,b.Bytes());status(auth[slot].Inform(store[slot],[]tka.AUM{a}));head(slot) +} +func keys(slot byte) { emit(8,slot,nil); status(nil); var b []byte; for _,k:=range auth[slot].Keys(){ if k.Kind==tka.Key25519&&len(k.Public)==32{b=append(b,k.Public...)} }; line(b) } +func offer(slot byte) tka.SyncOffer { o,e:=auth[slot].SyncOffer(store[slot]); must(e); emit(5,slot,nil); status(nil); line(offerBytes(o)); return o } +func offerBytes(o tka.SyncOffer) []byte { b:=append([]byte{},o.Head[:]...);for _,h:=range o.Ancestors{b=append(b,h[:]...)};return b } +func missing(slot byte,o tka.SyncOffer) []tka.AUM { emit(6,slot,offerBytes(o)); a,e:=auth[slot].MissingAUMs(store[slot],o);status(e);if e==nil{var b []byte;for _,x:=range a{h:=x.Hash();b=append(b,h[:]...)};line(b)};return a } +func stateAt(slot byte,h tka.AUMHash,s tka.State) { emit(7,slot,h[:]);status(nil);s.LastAUMHash=&h;line(marshal(s)) } +func sign(a tka.AUM, privs ...ed25519.PrivateKey) tka.AUM { a.Signatures=nil; h:=a.SigHash();for _,p:=range privs{a.Signatures=append(a.Signatures,tkatype.Signature{KeyID:tkatype.KeyID(p.Public().(ed25519.PublicKey)),Signature:ed25519.Sign(p,h[:])})};return a } +func child(a tka.AUM, p tka.AUM, privs ...ed25519.PrivateKey) tka.AUM {h:=p.Hash();a.PrevAUMHash=h[:];return sign(a,privs...) } +func corpus(root string) { + for _,name:=range []string{"hostile.txt","fuzz.txt","tka-structs.txt"} { + f,e:=os.Open(filepath.Join(root,name));must(e);scan:=bufio.NewScanner(f);scan.Buffer(make([]byte,65536),2<<20) + for scan.Scan(){s:=strings.Fields(scan.Text());if len(s)==0||strings.HasPrefix(s[0],"#"){continue};var raw string;schema:=byte(1) + if name=="tka-structs.txt" {if s[0]=="aum"{raw=s[1]}else if s[0]=="state"{raw=s[1];schema=3}else{continue}} else {if s[1]!="aum"{continue};raw=s[5]} + var b []byte;if raw!="-"{b,e=hex.DecodeString(raw);must(e)};model(b,schema) + };must(scan.Err());f.Close() + } +} +func scenarios() { + p:=ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1},32));q:=ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2},32));r:=ed25519.NewKeyFromSeed(bytes.Repeat([]byte{3},32)) + k:=tka.Key{Kind:tka.Key25519,Votes:1,Public:p.Public().(ed25519.PublicKey)}; k2:=tka.Key{Kind:tka.Key25519,Votes:2,Public:q.Public().(ed25519.PublicKey)}; k3:=tka.Key{Kind:tka.Key25519,Votes:3,Public:r.Public().(ed25519.PublicKey)} + state:=tka.State{DisablementValues:[][]byte{bytes.Repeat([]byte{7},32)},Keys:[]tka.Key{k,k2},StateID1:11,StateID2:22} + g:=sign(tka.AUM{MessageKind:tka.AUMCheckpoint,State:&state},p) + reset(0);reset(1);boot(0,g);boot(1,g);boot(0,g);keys(0);stateAt(0,g.Hash(),state) + add:=child(tka.AUM{MessageKind:tka.AUMAddKey,Key:&k3},g,p);inform(0,add);keys(0) + st1:=state.Clone();st1.Keys=append(st1.Keys,k3);stateAt(0,add.Hash(),st1) + votes:=uint(4);up:=child(tka.AUM{MessageKind:tka.AUMUpdateKey,KeyID:k.Public,Votes:&votes,Meta:map[string]string{"name":"alpha"}},add,p) + inform(0,up);st2:=st1.Clone();st2.Keys[0].Votes=4;st2.Keys[0].Meta=map[string]string{"name":"alpha"};stateAt(0,up.Hash(),st2) + cp:=child(tka.AUM{MessageKind:tka.AUMCheckpoint,State:&st2},up,p);inform(0,cp);stateAt(0,cp.Hash(),st2) + badstate:=st2.Clone();badstate.StateID2++;badcp:=child(tka.AUM{MessageKind:tka.AUMCheckpoint,State:&badstate},cp,p);inform(0,badcp) + rm:=child(tka.AUM{MessageKind:tka.AUMRemoveKey,KeyID:k2.Public},cp,p);inform(0,rm);keys(0) + off:=offer(1);miss:=missing(0,off);inform(1,miss...);offer(0);offer(1);keys(1) + unknown:=child(tka.AUM{MessageKind:255,KeyID:[]byte{42}},rm,p);inform(0,unknown) + invalid:=child(tka.AUM{MessageKind:tka.AUMNoOp},unknown,q);inform(0,invalid) + badparent:=sign(tka.AUM{MessageKind:tka.AUMNoOp,PrevAUMHash:bytes.Repeat([]byte{99},32)},p);inform(0,badparent) + good:=child(tka.AUM{MessageKind:tka.AUMNoOp},unknown,p);inform(0,good,badparent);inform(0,good);inform(0,good) + unsigned:=child(tka.AUM{MessageKind:tka.AUMNoOp},good);inform(0,unsigned) + badsig:=child(tka.AUM{MessageKind:tka.AUMNoOp},good,p);badsig.Signatures[0].Signature[0]^=1;inform(0,badsig) + adddup:=child(tka.AUM{MessageKind:tka.AUMAddKey,Key:&k3},good,p);inform(0,adddup) + zero:=uint(0);badup:=child(tka.AUM{MessageKind:tka.AUMUpdateKey,KeyID:k.Public,Votes:&zero},good,p);inform(0,badup) + missing(0,tka.SyncOffer{Head:tka.AUMHash{99},Ancestors:[]tka.AUMHash{{98}}}) + // Fork choice: duplicate signatures contribute votes once; remove wins a weight tie. + reset(0);reset(1);boot(0,g);boot(1,g) + dup:=child(tka.AUM{MessageKind:tka.AUMNoOp,KeyID:[]byte{1}},g,p,p,p) + heavy:=child(tka.AUM{MessageKind:tka.AUMNoOp,KeyID:[]byte{2}},g,q) + inform(0,dup,heavy);inform(1,heavy,dup);offer(0);offer(1) + remove:=child(tka.AUM{MessageKind:tka.AUMRemoveKey,KeyID:k.Public},g,q);inform(0,remove);keys(0);inform(1,remove);keys(1) + // Hash tie breaker among equal-weight siblings; different arrival orders converge. + a:=child(tka.AUM{MessageKind:tka.AUMNoOp,KeyID:[]byte{3}},remove,q) + b:=child(tka.AUM{MessageKind:tka.AUMNoOp,KeyID:[]byte{4}},remove,q) + inform(0,a);inform(1,b);o0:=offer(0);o1:=offer(1);m0:=missing(0,o1);m1:=missing(1,o0);inform(0,m1...);inform(1,m0...);offer(0);offer(1) + last:=a;if b.Hash().String()<a.Hash().String(){last=b};if auth[0].Head()!=last.Hash(){last=b} + lastRemove:=child(tka.AUM{MessageKind:tka.AUMRemoveKey,KeyID:k2.Public},last,q);inform(0,lastRemove) + // Preserve original bootstrap at a later checkpoint, including non-nil parent. + reset(1);boot(1,cp);keys(1);offer(1) + // Exact sampled oldest duplicates at depth4,16,64; bounded long-chain synchronization. + reset(0);reset(1);boot(0,g);boot(1,g);last=g + for i:=range 70{last=child(tka.AUM{MessageKind:tka.AUMNoOp,KeyID:[]byte{byte(i)}},last,p);inform(0,last);if i==3||i==15||i==63{offer(0)}} + o1=offer(1);m0=missing(0,o1);inform(1,m0...);offer(0);offer(1) + // Bounded-profile resource tests are deliberately distinct from upstream acceptance. + for i:=70;i<126;i++{last=child(tka.AUM{MessageKind:tka.AUMNoOp,KeyID:[]byte{byte(i)}},last,p);inform(0,last)} + next:=child(tka.AUM{MessageKind:tka.AUMNoOp,KeyID:[]byte{126}},last,p) + overflow:=child(tka.AUM{MessageKind:tka.AUMNoOp,KeyID:[]byte{127}},next,p) + rejectBatch(0,next,overflow);offer(0);keys(0);inform(0,next);rejectBatch(0,overflow);offer(0) + // The 512-key checkpoint fits; AddKey must reject a 513th without mutation. + big:=state.Clone();big.Keys=[]tka.Key{k} + for i:=range 511{pub:=bytes.Repeat([]byte{42},32);binary.LittleEndian.PutUint64(pub,uint64(i));big.Keys=append(big.Keys,tka.Key{Kind:tka.Key25519,Votes:1,Public:pub})} + bg:=sign(tka.AUM{MessageKind:tka.AUMCheckpoint,State:&big},p);reset(0);boot(0,bg) + rejectBatch(0,child(tka.AUM{MessageKind:tka.AUMAddKey,Key:&k3},bg,p));keys(0);offer(0) + // Static validation boundaries and typed forms. + for _,v:=range []uint{0,1,4096,4097}{kk:=k.Clone();kk.Votes=v;model(marshal(kk),2);a:=tka.AUM{MessageKind:tka.AUMAddKey,Key:&kk};model(a.Serialize(),1)} + for _,s:=range []string{"a201180302f6","a261310361328100","a3010302f6181861ff","a3010302f607a1f6f6","a3010302f607a2606161f66162","a3010302f60460","a3010302f60380","a3010302f606f6","f6","a2010302f7"}{b,e:=hex.DecodeString(s);must(e);model(b,1)} + for _,raw:=range []string{"a1014101","a1018101","a10158200000000000000000000000000000000000000000000000000000000000000000","a10180","a101f6","a10380","a103f6"}{b,e:=hex.DecodeString(raw);must(e);model(b,3)} + for _,raw:=range []string{"a101190100","a3010102010340","a30101020103f6","a40101020103400ca1f6f6"}{b,e:=hex.DecodeString(raw);must(e);model(b,2)} + for _,raw:=range []string{"a201810102820001","a2014002f6","a2016002f6","a201f60280"}{b,e:=hex.DecodeString(raw);must(e);model(b,4)} + nilkey:=k.Clone();nilkey.Public=nil;emptykey:=k.Clone();emptykey.Public=[]byte{} + ns:=state.Clone();ns.Keys=[]tka.Key{k,nilkey,emptykey};na:=tka.AUM{MessageKind:tka.AUMCheckpoint,State:&ns};model(na.Serialize(),1) + ns.Keys=[]tka.Key{k,nilkey};na.State=&ns;model(na.Serialize(),1) + // Empty-but-present Meta clears metadata even though canonical reserialization omits it. + reset(0);boot(0,g) + named:=child(tka.AUM{MessageKind:tka.AUMUpdateKey,KeyID:k.Public,Meta:map[string]string{"name":"temporary"}},g,p);inform(0,named) + clear:=child(tka.AUM{MessageKind:tka.AUMUpdateKey,KeyID:k.Public,Meta:map[string]string{}},named,p) + wire:=marshal(map[uint64]any{1:clear.MessageKind,2:clear.PrevAUMHash,4:clear.KeyID,7:map[string]string{},23:clear.Signatures}) + model(wire,1);informRaw(0,wire);stateAt(0,clear.Hash(),state) + // Replaying its canonical (now statically invalid) encoding must skip revalidation by hash. + informRaw(0,clear.Serialize());stateAt(0,clear.Hash(),state) + // fxamacker treats non-Boolean simple values as unsigned integers in typed destinations. + for v:=range 256 { + value:=[]byte{0xf8,byte(v)};if v<24{value=[]byte{0xe0+byte(v)}} + for _,schema:=range []byte{1,2}{model(append([]byte{0xa1,1},value...),schema)} + model(append([]byte{0xa1,6},value...),1) + model(append([]byte{0xa1,4},value...),3) + model(append([]byte{0xa1,2,0x81},value...),1) + model(append([]byte{0xa1,1,0x81},value...),3) + model(append([]byte{0xa1,1,0x81},value...),4) + } +} +func rejectBatch(slot byte,updates ...tka.AUM) { + var b bytes.Buffer;b.WriteByte(byte(len(updates))) + for _,a:=range updates{raw:=a.Serialize();binary.Write(&b,binary.LittleEndian,uint32(len(raw)));b.Write(raw)} + emit(3,slot,b.Bytes());status(fmt.Errorf("explicit bounded-profile resource rejection"));head(slot) +} +func fixture() { + p:=ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1},32));q:=ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2},32)) + k:=tka.Key{Kind:tka.Key25519,Votes:1,Public:p.Public().(ed25519.PublicKey)} + k2:=tka.Key{Kind:tka.Key25519,Votes:1,Public:q.Public().(ed25519.PublicKey)} + s:=tka.State{Keys:[]tka.Key{k,k2},DisablementValues:[][]byte{bytes.Repeat([]byte{7},32)}} + g:=sign(tka.AUM{MessageKind:tka.AUMCheckpoint,State:&s},p) + rm:=child(tka.AUM{MessageKind:tka.AUMRemoveKey,KeyID:k2.Public},g,p) + node:=bytes.Repeat([]byte{9},32) + var np key.NodePublic;must(np.UnmarshalBinary(append([]byte{'n','p'},node...))) + pub,e:=np.MarshalBinary();must(e) + sig:=tka.NodeKeySignature{SigKind:tka.SigDirect,Pubkey:pub,KeyID:k2.Public} + h:=sig.SigHash();sig.Signature=ed25519.Sign(q,h[:]) + ch:=tka.ChonkMem();a,e:=tka.Bootstrap(ch,g);must(e) + must(a.NodeKeyAuthorized(np,sig.Serialize())) + must(a.Inform(ch,[]tka.AUM{rm})) + if a.NodeKeyAuthorized(np,sig.Serialize())==nil{panic("fixture remains authorized after removal")} + must(json.NewEncoder(os.Stdout).Encode(map[string]string{"genesis":hex.EncodeToString(g.Serialize()),"removal":hex.EncodeToString(rm.Serialize()),"signature":hex.EncodeToString(sig.Serialize()),"node":hex.EncodeToString(node)})) +} +func main(){if len(os.Args)==2&&os.Args[1]=="--fixture"{fixture();return};if len(os.Args)!=4{panic("oracle INPUT EXPECTED CBOR_VECTOR_DIR")};var e error;input,e=os.Create(os.Args[1]);must(e);defer input.Close();expected,e=os.Create(os.Args[2]);must(e);defer expected.Close();enc,e=cbor.CTAP2EncOptions().EncMode();must(e) + // Derived options from tka/tka.go; Tailscale BSD-3-Clause, notice in ../../tailscale.LICENSE. + dec,e=(cbor.DecOptions{DupMapKey:cbor.DupMapKeyEnforcedAPF,IndefLength:cbor.IndefLengthForbidden,TagsMd:cbor.TagsForbidden,MaxNestedLevels:16,MaxArrayElements:4096,MaxMapPairs:1024}).DecMode();must(e) + scenarios();corpus(os.Args[3]) +} diff --git a/om/tka/test/revocation.om b/om/tka/test/revocation.om new file mode 100644 index 0000000..253ed83 --- /dev/null +++ b/om/tka/test/revocation.om @@ -0,0 +1,90 @@ +note SPDX-License-Identifier: Apache-2.0 +note Cross-unit regression: trusted authority removal revokes a direct node signature. +fn smread d edit uchar 65536 n ulong to ulong +p = ulong 0 +while lt p n bound 65536 +z = read int 0 d p sub n p +if le z 0 +ret 1 +end +p = add p ulong z +end +ret 0 +end +fn smlen to ulong +b = new uchar 65536 0 +if ne smread b 4 0 +ret 65537 +end +n = ulong 0 +for i ulong 4 +n = or n shl ulong get b i mul i 8 +end +ret n +end +fn main to int +a = new uchar 65536 0 +s = new uchar 65536 0 +t = new ulong 131074 0 +m = new ulong 132 0 +node = new uchar 32 0 +keys = new uchar 16384 0 +spans = new ulong 256 0 +if ne tkaselect 0 0 +ret 1 +end +tkareset +n = smlen +if gt n 65536 +ret 2 +end +if ne smread a n 0 +ret 3 +end +if ne tkaboot a n 0 +ret 4 +end +n = smlen +if gt n 65536 +ret 5 +end +if ne smread s n 0 +ret 6 +end +if ne nksdec s n t m 0 +ret 7 +end +if ne smread a 32 0 +ret 8 +end +for i ulong 32 +put node i get a i +end +count = tkakeys keys +if gt count 512 +ret 9 +end +if ne nksauth s t m node keys count 1 +ret 10 +end +n = smlen +if gt n 65536 +ret 11 +end +if ne smread a n 0 +ret 12 +end +put spans 0 0 +put spans 1 n +if ne tkainform a spans 1 0 +ret 13 +end +count = tkakeys keys +if gt count 512 +ret 14 +end +if ne nksauth s t m node keys count 0 +ret 15 +end +ret 0 +end diff --git a/om/tka/test/run.sh b/om/tka/test/run.sh new file mode 100755 index 0000000..466fabb --- /dev/null +++ b/om/tka/test/run.sh @@ -0,0 +1,46 @@ +#!/bin/sh +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/../../.." && pwd) +OMC=${1:-} +if [ -z "$OMC" ]; then OMC=$("$ROOT/tools/omc.sh"); fi +GO=${TKA_GO:-${GO:-go}} +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT HUP INT TERM +cd "$ROOT/om/tka/test/oracle" +GOTOOLCHAIN=local "$GO" build -mod=readonly -o "$TMP/oracle" . +"$TMP/oracle" "$TMP/input" "$TMP/expected" "$ROOT/om/cbor/test/vectors" +cat "$ROOT/om/blake2s/blake2s.om" "$ROOT/om/sha512/sha512.om" "$ROOT/om/ed25519/ed25519.om" "$ROOT/om/cbor/cbor.om" > "$TMP/base.om" +cat "$TMP/base.om" "$ROOT/om/tka/tka.om" "$ROOT/om/tka/tkastate.om" "$ROOT/om/tka/tkapool.om" "$ROOT/om/tka/test/driver.om" > "$TMP/driver.om" +"$OMC" < "$TMP/driver.om" > "$TMP/driver" +chmod +x "$TMP/driver" +"$TMP/driver" < "$TMP/input" > "$TMP/actual" +python3 "$ROOT/om/tka/test/check.py" "$TMP/expected" "$TMP/actual" exact +python3 - "$TMP/driver.om" "$TMP/mutant.om" <<'PY' +import pathlib,sys +s=pathlib.Path(sys.argv[1]).read_text() +old='ret edverify pk msg 32 sg 1' +assert s.count(old)==1 +pathlib.Path(sys.argv[2]).write_text(s.replace(old,'ret 1')) +PY +"$OMC" < "$TMP/mutant.om" > "$TMP/mutant" +chmod +x "$TMP/mutant" +"$TMP/mutant" < "$TMP/input" > "$TMP/mutant.actual" +python3 "$ROOT/om/tka/test/check.py" "$TMP/expected" "$TMP/mutant.actual" mutant +"$TMP/oracle" --fixture > "$TMP/fixture.json" +python3 - "$TMP/fixture.json" "$TMP/revocation.input" <<'PY' +import json,pathlib,struct,sys +v=json.loads(pathlib.Path(sys.argv[1]).read_text()) +b=bytearray() +for key in ("genesis","signature","node","removal"): + data=bytes.fromhex(v[key]) + if key != "node": + b.extend(struct.pack("<I",len(data))) + b.extend(data) +pathlib.Path(sys.argv[2]).write_bytes(b) +PY +cat "$TMP/base.om" "$ROOT/om/tka/tka.om" "$ROOT/om/tka/tkastate.om" "$ROOT/om/tka/tkapool.om" "$ROOT/om/tkasig/tkasig.om" "$ROOT/om/tka/test/revocation.om" > "$TMP/revocation.om" +"$OMC" < "$TMP/revocation.om" > "$TMP/revocation" +chmod +x "$TMP/revocation" +"$TMP/revocation" < "$TMP/revocation.input" +printf '%s\n' 'tka: PASS cross-unit node-signature revocation' +printf '%s\n' 'tka: PASS (differential model, authority, sync, signature mutant)' diff --git a/om/tka/tka.om b/om/tka/tka.om new file mode 100644 index 0000000..35a42d2 --- /dev/null +++ b/om/tka/tka.om @@ -0,0 +1,651 @@ +note SPDX-License-Identifier: BSD-3-Clause +note Derived behavior: Tailscale v1.102.0 tka/{aum,key,state,tka,sync}.go. +note Copyright (c) Tailscale Inc & contributors. See tailscale.LICENSE.