diff --git a/cmd/tkad/README.md b/cmd/tkad/README.md index 4d56d5d..bfa4031 100644 --- a/cmd/tkad/README.md +++ b/cmd/tkad/README.md @@ -77,7 +77,7 @@ nonempty signatures require an active authority and valid authorization. A key change clears the old signature. Omitting Signature preserves it only when the key is unchanged. Unsigned nodes may be registered and signed later; this does not itself authorize them to peers. Remove takes `{NodeID}`. Map/list takes `{}` -and returns `{TKAInfo,Revision,Nodes:[{NodeID,NodePublic,RotationPubkey,KeySignature}]}`. +and returns `{TKAInfo,Revision,StoreID,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`. @@ -85,7 +85,14 @@ Revision advances after each durable mutation. An exact registry upsert retry (s 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. +`StoreID` is the 128-bit identity of the store, 32 lowercase hex digits, drawn once from the +kernel CSPRNG by initialization and never changed afterwards. It names the store and not the +path: it survives restarts, an epoch boundary, and a rename of the store directory, and two +independent stores never share one. A client that follows a path can therefore tell a +replacement apart from the store it was talking to: the directory may be swapped under it and +the identity is the only thing that reports it. Adapters must propagate these full values to initial/delta map responses and arrange notifications. +No notification transport or Headscale integration is claimed here. ## State transitions and durable publication @@ -126,11 +133,33 @@ The semantic snapshot is version1: one128byte little-endian metadata frame, then each node's88byte record and optional signature frame, optional support and disablement secret frames, then each retained typed AUM frame in insertion order. Metadata holds status, node count, pending initiator, secret lengths, revision, -authority count and a version marker. Node records contain ID, signature length, +authority count, a version marker, the header schema word and the store identity, +listed in the word table below. Node records contain ID, signature length, authorization-state index, raw node key and raw rotation key. Storage adds its own framing, version, ordered BLAKE2s integrity chain and strict permission/type checks; see `om/store/README.md`. +The 128-byte metadata frame is sixteen little-endian 64-bit words: + +|Word|Meaning|Rule| +|---|---|---| +|0|state status|0 pending init through 3 disabled| +|1|registered node count|at most 64| +|2|pending initiator NodeID|0 when none, otherwise a registered node| +|3|support-disablement secret length|at most 1024| +|4|disablement secret length|at most 1024, stored only when disabled| +|5|reserved|must be 0| +|6|Revision|saturates, never wraps| +|7|retained authority count|at most 128| +|8|header schema|must be exactly 1| +|9,10|store identity, low then high word|128 random bits from init, never both 0| +|11..14|reserved|must be 0| +|15|marker|must be 1| + +A header whose schema word, identity or reserved words were altered is refused +rather than served or repaired. There is no migration from a header without a +schema word: no build that writes one has been released. + AUMs retain typed reconstruction (`tkamodel keep=1`), not merely canonical wire serialization: an empty-but-present update metadata map must survive restart. Recovery reboots/replays and verifies every AUM, registry uniqueness, structural diff --git a/cmd/tkad/adapter.om b/cmd/tkad/adapter.om index 5d42953..37c4635 100644 --- a/cmd/tkad/adapter.om +++ b/cmd/tkad/adapter.om @@ -156,6 +156,10 @@ end end p = dslit out p 19 p = jsonu64 out p dsget 6 +p = dslit out p 21 +p = dsputhex out p dsget 9 +p = dsputhex out p dsget 10 +p = dslit out p 22 p = dslit out p 17 b = new uchar 65536 0 for i ulong dsget 1 diff --git a/cmd/tkad/helpers.om b/cmd/tkad/helpers.om index 14e0517..c3c21d5 100644 --- a/cmd/tkad/helpers.om +++ b/cmd/tkad/helpers.om @@ -1,6 +1,6 @@ note SPDX-License-Identifier: Apache-2.0 text ds_names "Version|NodeKey|GenesisAUM|Signatures|SupportDisablement|Head|Ancestors|MissingAUMs|Interactive|DisablementSecret|Signature|KeyID|NodeID|RotationPubkey|Remove|" -text ds_text "{}|{\"NeedSignatures\":[|{\"NodeID\":|,\"NodePublic\":|,\"RotationPubkey\":|}|,|]}|{\"GenesisAUM\":|{\"DisablementSecret\":|{\"Head\":|,\"Ancestors\":[|],\"MissingAUMs\":[|{\"Signatures\":[|{\"TKAInfo\":|null|{\"Disabled\":true}|,\"Nodes\":[|,\"KeySignature\":|,\"Revision\":|{\"Error\":\"request rejected\"}|" +text ds_text "{}|{\"NeedSignatures\":[|{\"NodeID\":|,\"NodePublic\":|,\"RotationPubkey\":|}|,|]}|{\"GenesisAUM\":|{\"DisablementSecret\":|{\"Head\":|,\"Ancestors\":[|],\"MissingAUMs\":[|{\"Signatures\":[|{\"TKAInfo\":|null|{\"Disabled\":true}|,\"Nodes\":[|,\"KeySignature\":|,\"Revision\":|{\"Error\":\"request rejected\"}|,\"StoreID\":\"|\"|" fn dslower c uchar to uchar if and ge c 65 le c 90 ret add c 32 @@ -178,6 +178,20 @@ end z = cdb64enc src n b ret jsonstr out p b z end +fn dsputhex out edit uchar 65536 p ulong v ulong to ulong +note 16 lowercase hex digits, high nibble first, for a 64-bit header word. +q = p +for i ulong 16 +n = and shr v mul 4 sub 15 i 15 +c = add n 48 +if gt n 9 +c = add n 87 +end +put out q uchar c +q = add q 1 +end +ret q +end fn dsputnode out edit uchar 65536 p ulong i ulong to ulong k = new uchar 32 0 b = new uchar 65536 0 diff --git a/cmd/tkad/main.om b/cmd/tkad/main.om index cd31598..f81382f 100644 --- a/cmd/tkad/main.om +++ b/cmd/tkad/main.om @@ -125,6 +125,9 @@ ret -1 end if ne init 0 dsselect 0 +if ne dsident 0 +ret -1 +end s = dssave if eq s 2 exit 74 diff --git a/cmd/tkad/state.om b/cmd/tkad/state.om index 068a4ac..2636828 100644 --- a/cmd/tkad/state.om +++ b/cmd/tkad/state.om @@ -126,6 +126,24 @@ if ne stabort 0 exit 74 end end +note Store identity: 128 bits from the kernel CSPRNG, written once by init and never +note changed. Words 9 and 10; word 8 is the header schema, which must be exactly 1. +fn dsident to int +b = new uchar 65536 0 +r = random b 0 16 0 +if ne r 16 +ret 1 +end +lo = stget64 b ulong 0 +hi = stget64 b ulong 8 +if and eq lo 0 eq hi 0 +ret 1 +end +dsset 8 1 +dsset 9 lo +dsset 10 hi +ret 0 +end fn dssave to int b = new uchar 65536 0 dsset 7 tkacget 0 @@ -300,8 +318,14 @@ if ne dsget 2 0 ret 1 end end -for i ulong 7 -if ne dsget add i 8 0 +if ne dsget 8 1 +ret 1 +end +if and eq dsget 9 0 eq dsget 10 0 +ret 1 +end +for i ulong 4 +if ne dsget add i 11 0 ret 1 end end diff --git a/cmd/tkad/test/directory.py b/cmd/tkad/test/directory.py index 915bd61..c18ae21 100755 --- a/cmd/tkad/test/directory.py +++ b/cmd/tkad/test/directory.py @@ -75,6 +75,9 @@ class Daemon: def revision(self): return self.rpc(11, node=0, admin=True)["Revision"] + def storeid(self): + return self.rpc(11, node=0, admin=True)["StoreID"] + def files(directory): return sorted(p.name for p in pathlib.Path(directory).iterdir()) @@ -118,13 +121,13 @@ with tempfile.TemporaryDirectory(prefix="tkad-replaced-") as top: check(refused(live) == 73, "resume in the replacement directory refused") check(files(live) == [], "refused resume wrote nothing into the replacement") - # Observed, not endorsed: the store carries no identity word, so the same - # path can host an unrelated store with its own Revision 0 while the - # opened one is still live. Nothing here tells a reconnecting client that - # the path it follows now names a different store; see the R5 frame. + # The same path can host an unrelated store while the opened one is still + # live. Its identity is what tells a reconnecting client that the path it + # follows now names a different store. other = Daemon(live, initialize=True) try: check(other.revision() == 0, "replacement path accepted an independent empty store") + check(other.storeid() != daemon.storeid(), "replacement store is distinguishable by identity") finally: other.stop() finally: diff --git a/cmd/tkad/test/identity.py b/cmd/tkad/test/identity.py new file mode 100755 index 0000000..9dbe31f --- /dev/null +++ b/cmd/tkad/test/identity.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Store identity and header schema. + +The daemon header carries one schema word and a 128-bit store identity, so a +client that follows a path can tell whether the store behind it is still the +same store it was talking to. This pins the four properties that make the +identity usable, and the header validation that keeps it honest: + + * init draws a fresh identity, from the kernel CSPRNG, once; + * the identity survives a restart and follows the directory when it is + renamed, so it names the store and not the path; + * two independent stores never share an identity, so the A6 replacement case + is detectable rather than silent; + * a header whose schema, identity or reserved words were altered is refused + instead of being served. +""" +import base64 +import hashlib +import json +import pathlib +import socket +import struct +import subprocess +import sys +import tempfile +import time + +PROBE = "--probe" in sys.argv +BIN = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "build/tkad") +if not BIN.is_absolute(): + BIN = pathlib.Path.cwd() / BIN +checks = 0 + + +def check(value, message): + global checks + assert value, message + checks += 1 + + +def exact(sock, count): + result = b"" + while len(result) < count: + part = sock.recv(count - len(result)) + if not part: + raise AssertionError("truncated daemon reply") + result += part + return result + + +class Daemon: + def __init__(self, directory, initialize=False): + self.directory = pathlib.Path(directory) + self.path = str(self.directory / "tkad.sock") + self.p = subprocess.Popen( + [str(BIN), str(self.directory)] + (["--init"] if initialize else []), + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + if self.p.poll() is not None: + raise AssertionError(f"startup rc={self.p.returncode}: {self.p.communicate()}") + try: + with socket.socket(socket.AF_UNIX) as s: + s.settimeout(.2) + s.connect(self.path) + return + except (FileNotFoundError, ConnectionRefusedError, TimeoutError): + time.sleep(.02) + raise AssertionError("socket readiness timeout") + + def stop(self): + if self.p.poll() is None: + self.p.kill() + self.p.communicate(timeout=10) + + def map(self): + return self.rpc(11, {}) + + def rpc(self, route, body, admin=1): + payload = json.dumps(body, separators=(",", ":")).encode() + frame = struct.pack("<4sBBHQI", b"TKA\x01", route, admin, 0, 0, len(payload)) + payload + with socket.socket(socket.AF_UNIX) as s: + s.settimeout(30) + s.connect(self.path) + s.sendall(frame) + magic, status, reserved, size = struct.unpack("<4sHHI", exact(s, 12)) + check(magic == b"TKA\x01" and reserved == 0 and size <= 65536, "reply header") + answer = json.loads(exact(s, size)) + check(status == 200, f"route {route} status {status}: {answer}") + return answer + + +def store(state): + state.mkdir(mode=0o700) + d = Daemon(state, initialize=True) + try: + return d.map()["StoreID"] + finally: + d.stop() + + +def restart(state): + d = Daemon(state) + try: + return d.map()["StoreID"] + finally: + d.stop() + + +def header(state, word, value): + """Rewrite one header word with the framing and checksums recomputed.""" + snapshot = (state / "snapshot").read_bytes() + payloads = frames(snapshot) + struct.pack_into("