From a317ce46f4a1bc691047dc55dead776851bef269 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 25 Oct 2026 14:56:23 -0500 Subject: [PATCH 1/4] feat(tkad): preserve idempotent registry reconciliation --- cmd/tkad/README.md | 19 +++++++++------- cmd/tkad/adapter.om | 51 ++++++++++++++++++++++++++++++++++++++++++ cmd/tkad/test/smoke.py | 29 ++++++++++++++++++++---- 3 files changed, 87 insertions(+), 12 deletions(-) diff --git a/cmd/tkad/README.md b/cmd/tkad/README.md index fe05290..1a63bf5 100644 --- a/cmd/tkad/README.md +++ b/cmd/tkad/README.md @@ -77,19 +77,22 @@ nonempty signatures require an active authority and valid authorization. A key change clears the old signature. Omitting Signature preserves it only when the key is unchanged. Unsigned nodes may be registered and signed later; this does not itself authorize them to peers. Remove takes `{NodeID}`. Map/list takes `{}` -and returns `{TKAInfo,Revision,Nodes:[{NodeID,NodePublic,KeySignature}]}`. Inactive -and pending authority produce `TKAInfo:null`; active produces `{Head}`; disabled +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. A future adapter must propagate -these full values to initial/delta map responses and arrange notifications. -No notification transport or Headscale integration is claimed here. +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. Every registry update invalidates pending initialization. Finish -requires exactly one valid direct signature for every frozen node, including its -registered wrapping public key. A different initiator, partial roster, stale +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. diff --git a/cmd/tkad/adapter.om b/cmd/tkad/adapter.om index 3a95480..73c1c16 100644 --- a/cmd/tkad/adapter.om +++ b/cmd/tkad/adapter.om @@ -22,12 +22,58 @@ 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 @@ -118,6 +164,11 @@ 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 diff --git a/cmd/tkad/test/smoke.py b/cmd/tkad/test/smoke.py index 607b338..5da3626 100755 --- a/cmd/tkad/test/smoke.py +++ b/cmd/tkad/test/smoke.py @@ -133,11 +133,16 @@ with tempfile.TemporaryDirectory(prefix="omnet-tkad-") as top: d.rpc(2, d.req(Signatures={"9223372036854775808":FIX["signatures"][0],"2":FIX["signatures"][1]}), admin=True, expected=400) d.rpc(2, d.req(Signatures={"-0":FIX["signatures"][0],"2":FIX["signatures"][1]}), admin=True, expected=409) d.stop(); d = Daemon(state) - check(d.map()["TKAInfo"] is None, "pending recovered but invisible") - d.register(1) # Any roster update invalidates pending init, even same bytes. - d.rpc(2, d.req(Signatures={"1":FIX["signatures"][0],"2":FIX["signatures"][1]}), admin=True, expected=409) - d.rpc(1, d.req(GenesisAUM=FIX["genesis"]), admin=True) + 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") @@ -168,6 +173,9 @@ with tempfile.TemporaryDirectory(prefix="omnet-tkad-") as top: 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) @@ -203,6 +211,19 @@ with tempfile.TemporaryDirectory(prefix="omnet-tkad-") as top: 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) From d071fae0f9ff44c528d6096a0ffd1d36f4f5e277 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 25 Oct 2026 15:28:24 -0500 Subject: [PATCH 2/4] fix(tkad): check interactive sync head before applying updates --- cmd/tkad/README.md | 8 +++++--- cmd/tkad/rpc.om | 10 +++++----- cmd/tkad/test/smoke.py | 9 ++++++--- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/cmd/tkad/README.md b/cmd/tkad/README.md index 1a63bf5..0168acc 100644 --- a/cmd/tkad/README.md +++ b/cmd/tkad/README.md @@ -98,9 +98,11 @@ SupportDisablement is retained separately and never disables the authority. Pending genesis is not visible in map or bootstrap responses. Sync uses the authority unit's fork choice, offer sampling and intersection. -Interactive sync additionally requires the supplied Head to equal the resulting -chosen head; mismatch rejects the candidate. Noninteractive sync validates the -head encoding but permits a divergent remote head. Disable requires admin, the +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. diff --git a/cmd/tkad/rpc.om b/cmd/tkad/rpc.om index 567964b..b4ce9b8 100644 --- a/cmd/tkad/rpc.om +++ b/cmd/tkad/rpc.om @@ -305,6 +305,11 @@ 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 @@ -330,11 +335,6 @@ end if ne tkacommit 0 ret 400 end -if eq dskind t dsfield t d 8 5 -if eq dsheadmatch t d 0 -ret 409 -end -end p = dslit out 0 10 p = dsputhead out p put ds_ctl 6 dslit out p 5 diff --git a/cmd/tkad/test/smoke.py b/cmd/tkad/test/smoke.py index 5da3626..9b21998 100755 --- a/cmd/tkad/test/smoke.py +++ b/cmd/tkad/test/smoke.py @@ -153,7 +153,10 @@ with tempfile.TemporaryDirectory(prefix="omnet-tkad-") as top: d.rpc(5, d.req(Head=FIX["head"], **{"MiſſingAUMs": []})) d.rpc(5, d.req(Head=FIX["head"], MissingAUMs=[], **{"MiſſingAUMs": []}), expected=400) d.rpc(4, d.req(Head=FIX["head"], Ancestors=[])) - d.rpc(5, d.req(Head=FIX["updatedHead"], MissingAUMs=[FIX["update"]], Interactive=True)) + 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) @@ -165,11 +168,11 @@ with tempfile.TemporaryDirectory(prefix="omnet-tkad-") as top: d.rpc(7, d.req(Signature=base64.b64encode(bad).decode()), expected=403) affected = d.rpc(8, d.req(KeyID=FIX["keyID"])) check(affected["Signatures"] == FIX["signatures"], "affected raw signature array") - d.rpc(5, d.req(Head=FIX["emptyHead"], MissingAUMs=[FIX["emptyMeta"]], Interactive=True)) + 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["removedHead"], MissingAUMs=[FIX["removal"]], Interactive=True)) + 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") From 789779a9e85636235256ba3218357887b87acdae Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 25 Oct 2026 15:50:54 -0500 Subject: [PATCH 3/4] feat(integration): connect Omega TKA to Headscale and stock clients --- README.md | 14 +- docs/design/tailnet-lock.md | 51 +- integration/e2e/build-clients.sh | 44 + integration/e2e/lifecycle.py | 534 +++++ integration/e2e/run.sh | 38 + integration/headscale/README.md | 164 ++ integration/headscale/build.sh | 28 + integration/headscale/headscale.LICENSE | 29 + integration/headscale/headscale.patch | 2595 +++++++++++++++++++++++ integration/headscale/headscale.pin | 4 + integration/headscale/tailscale.LICENSE | 28 + 11 files changed, 3520 insertions(+), 9 deletions(-) create mode 100755 integration/e2e/build-clients.sh create mode 100755 integration/e2e/lifecycle.py create mode 100755 integration/e2e/run.sh create mode 100644 integration/headscale/README.md create mode 100755 integration/headscale/build.sh create mode 100644 integration/headscale/headscale.LICENSE create mode 100644 integration/headscale/headscale.patch create mode 100644 integration/headscale/headscale.pin create mode 100644 integration/headscale/tailscale.LICENSE diff --git a/README.md b/README.md index eaffcf0..1f976ba 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,8 @@ denial-of-service bug. | `om//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 library and daemon suites | @@ -71,7 +73,8 @@ denial-of-service bug. ## Build and test 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. Go is test-only; shipped logic is Omega. +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 @@ -84,9 +87,12 @@ snapshots, and validated restart recovery over a private Unix socket. Its local and must run as the same UID; the daemon does not authenticate remote Tailscale clients. The current profile supports one tailnet, 64 nodes, 128 authority updates and 64-KiB JSON messages. -Headscale integration and stock-client end-to-end qualification remain pending. This is not yet -deployed tailnet protection. Build with `tools/build-tkad.sh`; see -[`cmd/tkad/README.md`](cmd/tkad/README.md) before running it. +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. diff --git a/docs/design/tailnet-lock.md b/docs/design/tailnet-lock.md index eb30b20..bf8f1b7 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: bounded local Omega daemon, durable snapshots, JSON RPCs and TKA authority implemented. Headscale integration remains pending. 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 @@ -164,7 +164,7 @@ that way. That is a client issue outside this project; tkad's error bodies are s | JSON (`om/json`) and eight RPC handlers (`cmd/tkad`) | Omega | implemented: bounded parsing, trusted adapter identity binding | | Snapshot storage (`om/store`) | Omega | implemented: descriptor validation, writer exclusion, atomic publication, recovery | | tkad service (`cmd/tkad`) | Omega | implemented: private Unix socket, registry/map commands, controlled self-exec | -| headscale glue | Go (fork) | planned | +| headscale glue | Go (pinned patch) | implemented and exercised with unmodified Tailscale v1.102.0 | ## Verification plan @@ -219,6 +219,46 @@ The compiler pin was unchanged. New results: 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. + ## Plan and status 1. Crypto primitives: BLAKE2s, SHA-512, Ed25519. **Done.** @@ -227,6 +267,7 @@ stock-client compatibility beyond the tested profile, or production deployment s 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. -6. Review by a second implementer before any production use. Until then this is pre-alpha and does - not protect a tailnet. +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 production-readiness review and deployment planning remain. Source reviews found + and drove fixes during stage five, but are not a production audit. No live deployment is implied. 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..b844ddf --- /dev/null +++ b/integration/headscale/README.md @@ -0,0 +1,164 @@ +# 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. + +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. 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. + +## 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..6255d38 --- /dev/null +++ b/integration/headscale/headscale.patch @@ -0,0 +1,2595 @@ +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..0c2454a +--- /dev/null ++++ b/hscontrol/state/tka.go +@@ -0,0 +1,128 @@ ++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) ++} ++ ++// 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..307282f +--- /dev/null ++++ b/hscontrol/tkad.go +@@ -0,0 +1,617 @@ ++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 ++ ++var errTKAUnavailable = errors.New("omnet authority unavailable or registration pending") ++ ++// 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 ++} ++ ++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 == "" { ++ 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} ++ 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 ++ } ++ 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 ++ } ++ 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 ++ } ++ 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..37497a0 +--- /dev/null ++++ b/hscontrol/tkad_test.go +@@ -0,0 +1,726 @@ ++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} ++ 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 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() ++ defer f.mu.Unlock() ++ require.NotContains(t, f.calls, byte(1)) ++ 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. From 9b3fea1df80737c6e72734401fcb09fba2860322 Mon Sep 17 00:00:00 2001 From: AIEN Date: Sun, 25 Oct 2026 16:15:41 -0500 Subject: [PATCH 4/4] fix(tkad): keep every committed registry servable and bound adapter admission Store accepted node-key signatures in canonical typed form and reject any candidate whose registry snapshot would not fit the 64-KiB map response, so a verified signature with ignored CBOR fields can no longer make the durable registry unreadable. Regression tests cover canonical storage across restart and a test-only raw-storage variant proving the over-limit mutation returns 413 without committing. In the Headscale glue, resolve TKA callers against committed SQL before taking the publication barrier, bound registration/map admission so unknown Noise clients cannot queue on shared persistence work, and refuse startup when both adapter settings are absent on a database that already used the adapter. The JSON differential now pins its oracle toolchain, since Go 1.27 changed encoding/json escaping of invalid UTF-8 and the suite compares bytes. Readiness gates, paired restore ordering and the one-way migration limits are documented in integration/headscale/README.md and docs/design/tailnet-lock.md. --- cmd/tkad/README.md | 8 +- cmd/tkad/adapter.om | 20 ++- cmd/tkad/rpc.om | 27 +++- cmd/tkad/test/faults.py | 56 +++++++ cmd/tkad/test/smoke.py | 27 ++++ docs/design/tailnet-lock.md | 59 +++++++- integration/headscale/README.md | 143 +++++++++++++++++- integration/headscale/headscale.patch | 203 +++++++++++++++++++++++--- om/json/test/run.py | 7 +- 9 files changed, 523 insertions(+), 27 deletions(-) diff --git a/cmd/tkad/README.md b/cmd/tkad/README.md index 0168acc..43e2028 100644 --- a/cmd/tkad/README.md +++ b/cmd/tkad/README.md @@ -108,8 +108,12 @@ for bootstrap's disablement secret and cannot be reinitialized in this profile. Each mutating request operates on an inactive candidate slot, including registry, signatures, pending state, support/disablement secrets and authority. The complete -response is encoded and checked against capacity **before** persistence. Only -then is a complete snapshot streamed to storage, synced, atomically renamed and +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 diff --git a/cmd/tkad/adapter.om b/cmd/tkad/adapter.om index 73c1c16..5d42953 100644 --- a/cmd/tkad/adapter.om +++ b/cmd/tkad/adapter.om @@ -116,7 +116,9 @@ if eq dsauthsig b n i tkacget 1 0 ret 403 end end -dssetsig i b n tkacget 1 +if ne dssetcanon i b n tkacget 1 0 +ret 400 +end end dsunpend put ds_ctl 6 dslit out 0 0 @@ -181,6 +183,18 @@ 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 @@ -259,6 +273,9 @@ 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 @@ -271,6 +288,7 @@ 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 diff --git a/cmd/tkad/rpc.om b/cmd/tkad/rpc.om index b4ce9b8..08111c4 100644 --- a/cmd/tkad/rpc.om +++ b/cmd/tkad/rpc.om @@ -17,6 +17,29 @@ 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 @@ -411,7 +434,9 @@ end if eq dsauthsig b n i tkacget 1 0 ret 403 end -dssetsig i b n tkacget 1 +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 diff --git a/cmd/tkad/test/faults.py b/cmd/tkad/test/faults.py index d0b22e9..43e5b98 100755 --- a/cmd/tkad/test/faults.py +++ b/cmd/tkad/test/faults.py @@ -1,6 +1,7 @@ #!/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 @@ -149,3 +150,58 @@ with tempfile.TemporaryDirectory(prefix="tkad-semantic-recovery-") as name: 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/smoke.py b/cmd/tkad/test/smoke.py index 9b21998..eb3f2ee 100755 --- a/cmd/tkad/test/smoke.py +++ b/cmd/tkad/test/smoke.py @@ -92,6 +92,15 @@ def refused_start(directory, *args): 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) @@ -235,4 +244,22 @@ with tempfile.TemporaryDirectory(prefix="omnet-tkad-") as top: 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 bf8f1b7..595b57b 100644 --- a/docs/design/tailnet-lock.md +++ b/docs/design/tailnet-lock.md @@ -259,8 +259,58 @@ still shares the daemon UID. Its durable revision floor is not authenticated rol These checks prove control-plane behavior, not packet delivery, power-loss durability, constant-time cryptography, or production security. -## Plan and status +### 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 bounded in-memory chain logic, differential against `tka`. **Implemented.** @@ -269,5 +319,8 @@ constant-time cryptography, or production security. 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 production-readiness review and deployment planning remain. Source reviews found - and drove fixes during stage five, but are not a production audit. No live deployment is implied. +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/headscale/README.md b/integration/headscale/README.md index b844ddf..28bbf9e 100644 --- a/integration/headscale/README.md +++ b/integration/headscale/README.md @@ -44,7 +44,10 @@ 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. +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 @@ -104,7 +107,13 @@ 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. IPC and +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 @@ -156,6 +165,136 @@ 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 diff --git a/integration/headscale/headscale.patch b/integration/headscale/headscale.patch index 6255d38..183cd8f 100644 --- a/integration/headscale/headscale.patch +++ b/integration/headscale/headscale.patch @@ -717,10 +717,10 @@ index 293e6ba..2f43e70 100644 } diff --git a/hscontrol/state/tka.go b/hscontrol/state/tka.go new file mode 100644 -index 0000000..0c2454a +index 0000000..898446b --- /dev/null +++ b/hscontrol/state/tka.go -@@ -0,0 +1,128 @@ +@@ -0,0 +1,166 @@ +package state + +import ( @@ -755,6 +755,44 @@ index 0000000..0c2454a + 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. @@ -1140,10 +1178,10 @@ index 0000000..d952634 +} diff --git a/hscontrol/tkad.go b/hscontrol/tkad.go new file mode 100644 -index 0000000..307282f +index 0000000..0592956 --- /dev/null +++ b/hscontrol/tkad.go -@@ -0,0 +1,617 @@ +@@ -0,0 +1,680 @@ +package hscontrol + +import ( @@ -1178,22 +1216,47 @@ index 0000000..307282f +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 ++ 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 @@ -1210,13 +1273,31 @@ index 0000000..307282f +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} ++ 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() @@ -1523,6 +1604,15 @@ index 0000000..307282f + 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() @@ -1582,6 +1672,13 @@ index 0000000..307282f + 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) @@ -1616,6 +1713,10 @@ index 0000000..307282f + 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) @@ -1763,10 +1864,10 @@ index 0000000..307282f +} diff --git a/hscontrol/tkad_test.go b/hscontrol/tkad_test.go new file mode 100644 -index 0000000..37497a0 +index 0000000..7c65043 --- /dev/null +++ b/hscontrol/tkad_test.go -@@ -0,0 +1,726 @@ +@@ -0,0 +1,794 @@ +package hscontrol + +import ( @@ -1923,7 +2024,15 @@ index 0000000..37497a0 + 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} ++ 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 @@ -1954,6 +2063,58 @@ index 0000000..37497a0 + 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 { @@ -2086,8 +2247,16 @@ index 0000000..37497a0 + ns.tkaRPC(w, httptest.NewRequest(http.MethodGet, "/", bytes.NewReader(body)), 1) + require.Equal(t, http.StatusUnauthorized, w.Code) + f.mu.Lock() -+ defer f.mu.Unlock() + 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") +} + diff --git a/om/json/test/run.py b/om/json/test/run.py index 2b68298..d087046 100755 --- a/om/json/test/run.py +++ b/om/json/test/run.py @@ -40,7 +40,12 @@ def execute(binary, data, expected): go = os.environ.get("GO", "go") -subprocess.run([go, "build", "-mod=mod", "-o", str(OUT / "oracle"), "."], cwd=HERE / "oracle", check=True) +# 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()]