interplane.Get Omega
Read in your language

omnet

aien-dev/omnet

Brought by drakestapleton

GitHub aien-dev/omnet#11 (code only)

closed derived 4841e3a5df8115bf #11

Imported from GitHub aien-dev/omnet#11 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 565c87e8f6806e27fa8a99540e33172e6aabee97 · Head 39562b5196817c610e3767bd3834698926088bda

Apply it

git checkout -b patch-4841e3a5df8115bf 565c87e8f6806e27fa8a99540e33172e6aabee97
curl -fsSL https://interplane.io/drakestapleton/omnet/patches/4841e3a5df8115bf.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/omnet
11
39562b5196817c610e3767bd3834698926088bda
{"kind":"github-import","owner":"aien-dev","repo":"omnet","number":11,"url":"https://github.com/aien-dev/omnet/pull/11","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:42Z","metadata":"unavailable","state_derived":true}

Changes

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("<Q", payloads[0], word * 8, value)
+    (state / "snapshot").write_bytes(reseal(snapshot[:16], payloads))
+
+
+def frames(snapshot):
+    result = []
+    p = 16
+    while True:
+        n = struct.unpack_from("<Q", snapshot, p)[0]
+        if n == 0:
+            return result
+        result.append(bytearray(snapshot[p + 40:p + 40 + n]))
+        p += 40 + n
+
+
+def reseal(magic, payloads):
+    # Independent Python implementation of the documented store framing.
+    out = bytearray(magic)
+    chain = bytes(32)
+    total = 0
+    for count, payload in enumerate(payloads, 1):
+        digest = hashlib.blake2s(payload).digest()
+        total += len(payload)
+        out += struct.pack("<Q", len(payload)) + digest + payload
+        chain = hashlib.blake2s(chain + digest + struct.pack("<QQQ", len(payload), total, count)).digest()
+    out += bytes(8) + chain + struct.pack("<QQ", total, len(payloads))
+    return out
+
+
+def resumes(state):
+    """None when the daemon served the store, else its exit code."""
+    p = subprocess.Popen([str(BIN), str(state)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    try:
+        code = p.wait(timeout=1.5)
+    except subprocess.TimeoutExpired:
+        p.kill()
+        p.communicate()
+        return None
+    p.communicate()
+    return code
+
+
+def refused(state):
+    return resumes(state) == 73
+
+
+with tempfile.TemporaryDirectory(prefix="tkad-identity-") as top:
+    root = pathlib.Path(top)
+
+    if PROBE:
+        # Negative control: against a daemon without the identity guard this
+        # must exit 0 (the guard is gone, a zero identity is served) and
+        # against the production binary it must exit 3. run.sh requires both.
+        probe = root / "probe"
+        store(probe)
+        header(probe, 9, 0)
+        header(probe, 10, 0)
+        sys.exit(0 if resumes(probe) is None else 3)
+
+    # A fresh identity per store, and the same identity after a restart.
+    first = store(root / "one")
+    check(len(first) == 32 and all(c in "0123456789abcdef" for c in first), f"identity hex32: {first}")
+    check(first != "0" * 32, "identity drawn, not absent")
+    check(restart(root / "one") == first, "identity survives restart")
+
+    # Independent stores never share an identity, so the A6 replacement case is
+    # detectable: the path is the same, the identity is not.
+    second = store(root / "two")
+    check(second != first, "independent stores have distinct identities")
+
+    # A durable mutation rewrites the header; the identity must not move.
+    nodekey = "nodekey:" + "11" * 32
+    rotation = base64.b64encode(bytes(range(1, 33))).decode()
+    with tempfile.TemporaryDirectory(prefix="tkad-identity-commit-") as name:
+        committed = pathlib.Path(name) / "commit"
+        live = store(committed)
+        d = Daemon(committed)
+        try:
+            d.rpc(9, {"NodeID": 1, "NodeKey": nodekey, "RotationPubkey": rotation}, admin=True)
+            check(d.map()["StoreID"] == live, "identity unchanged by a durable mutation")
+            after = d.map()
+            check(after["Revision"] == 1 and len(after["Nodes"]) == 1, "mutation committed and durable")
+        finally:
+            d.stop()
+        check(restart(committed) == live, "identity unchanged after a committed restart")
+
+    # The identity names the store, not the path: rename and it is unchanged.
+    (root / "one").rename(root / "one-moved")
+    check(restart(root / "one-moved") == first, "identity follows the directory rename")
+    check(store(root / "one") != first, "a new store at the vacated path has its own identity")
+
+    # Header validation: schema, identity and reserved words are all enforced,
+    # and each refusal is a refusal to serve, not a silent repair.
+    for label, word, value in [
+        ("schema absent", 8, 0),
+        ("schema unknown", 8, 2),
+        ("identity zero", 9, 0),
+        ("reserved word", 12, 1),
+    ]:
+        mutated = root / label.replace(" ", "-")
+        store(mutated)
+        if word == 9:
+            header(mutated, 9, 0)
+            header(mutated, 10, 0)
+        else:
+            header(mutated, word, value)
+        check(refused(mutated), f"{label} refused")
+        check((mutated / "snapshot").exists(), f"{label}: refused without rewriting the snapshot")
+print(f"PASS tkad store identity: {checks} checks, header schema and reserved words enforced, identity drawn once, follows the store across rename and restart")
diff --git a/cmd/tkad/test/mutant.py b/cmd/tkad/test/mutant.py
index 722e6cf..807d9da 100755
--- a/cmd/tkad/test/mutant.py
+++ b/cmd/tkad/test/mutant.py
@@ -27,3 +27,16 @@ for label, replacement in variants.items():
     else:
         assert run.returncode != 0 and not completed_mismatch and "truncated daemon reply" in run.stderr, (run.returncode, run.stdout, run.stderr)
         print("PASS tkad trapping mutant rejected, not counted as detection")
+
+note_guard = "if and eq dsget 9 0 eq dsget 10 0\nret 1\nend\n"
+assert source.count(note_guard) == 1
+path = root / "build" / "tkad-mutant-no-identity"
+build = subprocess.run([omc], input=source.replace(note_guard, "").encode(), capture_output=True)
+assert build.returncode == 0, build.stderr.decode()
+path.write_bytes(build.stdout)
+path.chmod(0o700)
+probe = subprocess.run([sys.executable, str(root / "cmd/tkad/test/identity.py"), str(path), "--probe"], capture_output=True, text=True, timeout=120)
+assert probe.returncode == 0, ("mutant without the identity guard was not caught", probe.returncode, probe.stdout, probe.stderr)
+probe = subprocess.run([sys.executable, str(root / "cmd/tkad/test/identity.py"), str(binary), "--probe"], capture_output=True, text=True, timeout=120)
+assert probe.returncode == 3, ("production binary must refuse a zero identity", probe.returncode, probe.stdout, probe.stderr)
+print("PASS tkad identity guard mutant detected, and the production guard refuses")
diff --git a/cmd/tkad/test/rollover.py b/cmd/tkad/test/rollover.py
index e8d535c..6a5bd3b 100755
--- a/cmd/tkad/test/rollover.py
+++ b/cmd/tkad/test/rollover.py
@@ -31,11 +31,18 @@ def exact(s, n):
     return out
 
 
+seen = {}
+
+
 def response(s):
     magic, status, reserved, n = struct.unpack("<4sHHI", exact(s, 12))
     assert magic == b"TKA\x01" and status == 200 and reserved == 0
     result = json.loads(exact(s, n)); s.close()
-    assert result == {"TKAInfo":None,"Revision":0,"Nodes":[]}, result
+    assert (result["TKAInfo"], result["Revision"], result["Nodes"]) == (None, 0, []), result
+    ident = result["StoreID"]
+    assert len(ident) == 32, result
+    # The epoch exec replaces the process image; the store identity must not move.
+    assert seen.setdefault("id", ident) == ident, "identity changed across the epoch boundary"
 
 
 with tempfile.TemporaryDirectory(prefix="tkad-rollover-") as name:
diff --git a/cmd/tkad/test/run.sh b/cmd/tkad/test/run.sh
index 4d409a8..0b7dc50 100755
--- a/cmd/tkad/test/run.sh
+++ b/cmd/tkad/test/run.sh
@@ -10,4 +10,5 @@ python3 "$root/cmd/tkad/test/smoke.py" "$bin"
 python3 "$root/cmd/tkad/test/mutant.py" "$root" "$bin"
 python3 "$root/cmd/tkad/test/rollover.py" "$root" "$bin"
 python3 "$root/cmd/tkad/test/directory.py" "$bin"
+python3 "$root/cmd/tkad/test/identity.py" "$bin"
 python3 "$root/cmd/tkad/test/faults.py" "$root" "$bin"