Skip to main content

ts_runtime/
tka_sync.rs

1//! Tailnet-Lock (TKA) chain-sync orchestration: the runtime-layer driver that ties the transport
2//! RPCs (`ts_control::{tka_bootstrap, tka_sync_offer, tka_sync_send}`) to the chain logic
3//! (`ts_tka::{Aum, Authority, MemAumStore, VerifiedAumChain}`), mirroring Go's `tkaSyncIfNeeded`
4//! (`ipn/ipnlocal/tailnet-lock.go`, v1.100.0).
5//!
6//! This lives in `ts_runtime` because it is the only layer that depends on **both** the wire crate
7//! (`ts_control`, which deliberately knows nothing of `ts_tka`) and the chain crate (`ts_tka`). It
8//! converts between the wire forms (base32 head strings, base64'd raw-CBOR AUM bytes) and the domain
9//! types, and drives the two-phase flow:
10//!
11//! 1. **Bootstrap** (only when we hold no chain yet): `tka_bootstrap` fetches the genesis AUM; we
12//!    `Aum::from_cbor` it, build the initial [`Authority`] via the **un-bypassable trust boundary**
13//!    `VerifiedAumChain::verify` → `Authority::from_verified_chain`, and seed a [`MemAumStore`].
14//! 2. **Sync** (offer → send): compute our [`SyncOffer`], send it, decode the AUMs control says we're
15//!    missing, `Inform`-equivalent (verify + fold into a fresh Authority over the grown store), then
16//!    tell control the AUMs *it* is missing. The order matches Go exactly — we compute what to *send*
17//!    from the pre-Inform store, then advance.
18//!
19//! **Posture (this module fails open; the published `Authority` is then ENFORCED).** This is two
20//! distinct claims, kept distinct:
21//!
22//! - *Sync failure is fail-open here*: every failure path in **this** module (a transport error, a
23//!   malformed AUM, a verify failure) returns `Ok(None)` or an `Err` that the caller treats as "no
24//!   new Authority obtained this round" — a failed *sync* never blocks the netmap and leaves the
25//!   prior enforcement state untouched (see `control_runner`'s apply step). It does NOT mean TKA is
26//!   observe-only.
27//! - *A successfully synced `Authority` is actively enforced*: once this module returns an
28//!   `Authority`, the control runner publishes it to the peer tracker's enforcement cell and the
29//!   peer-trust chokepoint fails **closed** — a peer presenting a missing or unauthorized
30//!   `key_signature` is **dropped** at the peer-db upsert path (`peer_tracker::tka_snapshot_admits`,
31//!   matching Go's `tkaFilterNetmapLocked`). Installing the `Authority` also re-filters the peers
32//!   **already** in the db (`peer_tracker::tka_reevaluate_peer_db`), because this sync is
33//!   asynchronous: the netmap that announced the lock was applied before the `Authority` existed,
34//!   whereas Go filters that same netmap in the pass that synced it. With no lock synced, every peer
35//!   is admitted (Go's `b.tka == nil` early return); a control-signalled *disable* clears
36//!   enforcement back to admit-all.
37//!
38//! The chain always passes through the **un-bypassable trust boundary** `VerifiedAumChain::verify`
39//! before it can reach enforcement, so a malicious control plane cannot forge a trusted key to admit
40//! an unauthorized peer — it can only toggle the lock's enable/disable state. The authoritative
41//! description of the enforcement posture, threat model, and the remaining deferred gaps
42//! (disablement-secret verification, rotation-obsolete/clone-replay dropping) lives in `SECURITY.md`;
43//! keep this doc consistent with it.
44//!
45//! **Do not "simplify" by removing enforcement to match an outdated "observe-only" reading** — that
46//! would silently downgrade a working, fail-closed security control to verify-only.
47
48use std::sync::Arc;
49
50use ts_control::{
51    TkaSyncError, TkaSyncOfferRequest, TkaSyncSendRequest, tka_bootstrap, tka_sync_offer,
52    tka_sync_send,
53};
54use ts_tka::{Aum, AumHash, Authority, MemAumStore, SyncOffer, VerifiedAumChain};
55
56/// The synced TKA state a successful [`sync_tka`] produces: the verified [`Authority`] (for the
57/// verify-and-log consumer) plus the [`MemAumStore`] of AUMs gathered so far (so the next sync can
58/// compute offers/missing-sets without re-bootstrapping).
59pub(crate) struct SyncedTka {
60    pub authority: Arc<Authority>,
61    pub store: MemAumStore,
62    /// The genesis/oldest AUM hash, needed as the `oldest` argument to subsequent `sync_offer`s.
63    pub oldest: AumHash,
64}
65
66/// One entry of the Tailnet-Lock update-chain log, mirroring Go `ipnstate.NetworkLockUpdate` (the
67/// rows `tailscale lock log` prints). Produced by [`Device::tka_log`](crate::Runtime::tka_log) from
68/// the locally-synced AUM chain — a pure local read, no control round-trip.
69///
70/// `aum_hash` + `change` + `raw` are the exact Go `NetworkLockUpdate` fields (`Hash`, `Change`,
71/// `Raw`). `signer_key_ids` is an extra convenience this engine extracts from the decoded AUM —
72/// Go's struct has no `Signatures` field and recovers the signer only by decoding `Raw`; we surface
73/// the signer key ids directly so a daemon need not re-decode, while still carrying `raw` for a
74/// faithful full decode.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct TkaLogEntry {
77    /// The AUM's chain-link hash (Go `NetworkLockUpdate.Hash`): `BLAKE2s-256` of its serialization.
78    pub aum_hash: [u8; 32],
79    /// The human-readable change kind (Go `NetworkLockUpdate.Change`), e.g. `"add-key"` /
80    /// `"remove-key"` / `"checkpoint"` — [`AumKind::as_str`](ts_tka::AumKind::as_str).
81    pub change: String,
82    /// The id of each trusted key that signed this AUM (each
83    /// [`AumSignature::key_id`](ts_tka::AumSignature::key_id), the signer's 32-byte ed25519 public
84    /// key for an Ed25519 key). Convenience extraction; absent from Go's struct.
85    pub signer_key_ids: Vec<Vec<u8>>,
86    /// The AUM's canonical CBOR serialization (Go `NetworkLockUpdate.Raw` = `AUM.Serialize()`), so a
87    /// consumer can decode the full AUM (incl. signatures) faithfully.
88    pub raw: Vec<u8>,
89}
90
91/// Read up to `limit` entries of the TKA update-chain log from a synced AUM `store`, **head-first**
92/// (newest → oldest), mirroring Go `NetworkLockLog` which walks `Head` back toward genesis.
93///
94/// The store holds the chain genesis→head; [`MemAumStore::linear_chain_from`] yields that
95/// genesis→head order, which we **reverse** to match Go's head→genesis walk before truncating to
96/// `limit`. A pure function over the synced state (no crypto, no mutation, no RPC) so it is unit
97/// testable without standing up an actor. An unwalkable store (genesis missing / cycle) yields an
98/// empty log rather than erroring — the caller's "no readable chain" is an empty history, matching
99/// the no-lock-synced case.
100pub(crate) fn tka_log_entries(
101    store: &MemAumStore,
102    oldest: AumHash,
103    limit: usize,
104) -> Vec<TkaLogEntry> {
105    // genesis→head; an unwalkable store (missing genesis / cycle) → empty log.
106    let chain = store.linear_chain_from(oldest).unwrap_or_default();
107    chain
108        .iter()
109        .rev() // Go walks head→genesis; the store walk is genesis→head.
110        .take(limit)
111        .map(|aum| TkaLogEntry {
112            aum_hash: aum.hash().0,
113            change: aum.message_kind.as_str().to_string(),
114            signer_key_ids: aum.signatures.iter().map(|s| s.key_id.clone()).collect(),
115            raw: aum.serialize(),
116        })
117        .collect()
118}
119
120/// Errors internal to the sync driver. All map to "no Authority obtained" at the caller — the netmap
121/// is never errored and peers are never dropped on any of these.
122#[derive(Debug, thiserror::Error)]
123pub(crate) enum TkaSyncDriverError {
124    /// A transport RPC failed (network / unsupported / HTTP). `Unsupported` means control has no TKA
125    /// endpoint — treat as "inert", not a hard error.
126    #[error("TKA sync RPC failed: {0}")]
127    Rpc(#[from] TkaSyncError),
128    /// An AUM from control failed to decode or verify. Fail-closed: we do NOT advance the Authority.
129    #[error("TKA chain verification failed: {0}")]
130    Chain(#[from] ts_tka::TkaError),
131}
132
133/// Decode a base64-of-CBOR AUM batch (the wire form of `MissingAUMs`) into domain [`Aum`]s.
134/// Fail-closed: a single undecodable AUM rejects the whole batch (we never partially trust).
135fn decode_aums(marshaled: &[Vec<u8>]) -> Result<Vec<Aum>, ts_tka::TkaError> {
136    marshaled.iter().map(|b| Aum::from_cbor(b)).collect()
137}
138
139/// Re-verify a chain (existing store contents + newly-received AUMs) into a fresh [`Authority`],
140/// the `Inform` analog. We replay the full known AUM set through the trust boundary rather than
141/// mutating in place, so the resulting Authority is always one `VerifiedAumChain::verify` proved.
142///
143/// The store's AUMs in linear genesis→head order are what `verify` expects; we reconstruct that order
144/// by walking from the genesis (`oldest`) forward via the store's child links.
145fn rebuild_authority(store: &MemAumStore, oldest: AumHash) -> Result<Authority, ts_tka::TkaError> {
146    let chain = store.linear_chain_from(oldest)?;
147    let verified = VerifiedAumChain::verify(&chain)?;
148    Ok(Authority::from_verified_chain(verified))
149}
150
151/// Run a TKA bootstrap+sync cycle against control.
152///
153/// `current` is our existing synced state (`None` on first run → bootstrap first). Returns
154/// `Ok(Some(SyncedTka))` with the advanced Authority on success, `Ok(None)` when control has no lock
155/// for us (inert), or `Err` on a transport/verify failure (caller stays inert).
156pub(crate) async fn sync_tka(
157    config: &ts_control::Config,
158    keys: &ts_keys::NodeState,
159    current: Option<SyncedTka>,
160) -> Result<Option<SyncedTka>, TkaSyncDriverError> {
161    let control_url = &config.server_url;
162    let allow_http_key_fetch = config.allow_http_key_fetch;
163
164    // Phase 1: bootstrap if we have no chain yet.
165    let (mut store, oldest, mut authority) = match current {
166        Some(s) => (s.store, s.oldest, (*s.authority).clone()),
167        None => {
168            let resp = tka_bootstrap(
169                control_url,
170                keys,
171                String::new(), // no local head yet
172                allow_http_key_fetch,
173            )
174            .await?;
175            if resp.genesis_aum.is_empty() {
176                // Control returned no genesis: TKA is not enabled for us. Stay inert (not an error).
177                return Ok(None);
178            }
179            let genesis = Aum::from_cbor(&resp.genesis_aum)?;
180            let oldest = genesis.hash();
181            let mut store = MemAumStore::new();
182            store.insert(genesis);
183            let authority = rebuild_authority(&store, oldest)?;
184            (store, oldest, authority)
185        }
186    };
187
188    // Phase 2: offer → (decode + inform) → send. Mirror Go's order exactly.
189    let local_offer = authority.sync_offer(&store, oldest)?;
190    let offer_req = TkaSyncOfferRequest {
191        version: Default::default(), // overwritten by the RPC with CURRENT
192        node_key: keys.node_keys.public,
193        head: local_offer.head.to_base32(),
194        ancestors: local_offer
195            .ancestors
196            .iter()
197            .map(|a| a.to_base32())
198            .collect(),
199    };
200    let offer_resp = tka_sync_offer(control_url, keys, offer_req, allow_http_key_fetch).await?;
201
202    // Reconstruct control's offer from the response so we can compute what *control* is missing —
203    // BEFORE we Inform ourselves with control's AUMs (Go computes missing-to-send pre-Inform).
204    let control_offer = parse_offer(&offer_resp.head, &offer_resp.ancestors)?;
205
206    // Decode + insert the AUMs control sent, then rebuild (verify) the advanced Authority.
207    let received = decode_aums(&offer_resp.missing_aums)?;
208    for aum in &received {
209        store.insert(aum.clone());
210    }
211    // Compute what control is missing from the store as it stands (post-insert is fine: missing_aums
212    // is computed against control's offer, and the gather is from our head — inserting control's own
213    // AUMs cannot make us think it lacks them).
214    let to_send = authority
215        .missing_aums(&store, &control_offer, oldest)
216        .unwrap_or_default();
217    // Advance our Authority over the grown store (the Inform analog) — through the trust boundary.
218    authority = rebuild_authority(&store, oldest)?;
219
220    // Phase 3: send control the AUMs it lacks (best-effort; a failure here doesn't undo our advance).
221    let send_req = TkaSyncSendRequest {
222        version: Default::default(),
223        node_key: keys.node_keys.public,
224        head: authority.head().to_base32(),
225        missing_aums: to_send.iter().map(Aum::serialize).collect(),
226        interactive: false,
227    };
228    if let Err(e) = tka_sync_send(control_url, keys, send_req, allow_http_key_fetch).await {
229        // We already advanced locally; control not accepting our AUMs is logged, not fatal.
230        tracing::warn!(error = ?e, "TKA sync/send failed (local Authority already advanced)");
231    }
232
233    Ok(Some(SyncedTka {
234        authority: Arc::new(authority),
235        store,
236        oldest,
237    }))
238}
239
240/// Parse a wire offer (base32 head + ancestors) into a domain [`SyncOffer`]. A malformed base32 hash
241/// is a decode error (fail-closed).
242fn parse_offer(head: &str, ancestors: &[String]) -> Result<SyncOffer, ts_tka::TkaError> {
243    let head = AumHash::from_base32(head).ok_or(ts_tka::TkaError::Decode("bad base32 head"))?;
244    let ancestors = ancestors
245        .iter()
246        .map(|a| AumHash::from_base32(a).ok_or(ts_tka::TkaError::Decode("bad base32 ancestor")))
247        .collect::<Result<Vec<_>, _>>()?;
248    Ok(SyncOffer { head, ancestors })
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn parse_offer_roundtrips_base32() {
257        // A head + two ancestors as base32 (no-pad) of 32-byte hashes parse back to those hashes.
258        let h0 = AumHash([0x11; 32]);
259        let h1 = AumHash([0x22; 32]);
260        let h2 = AumHash([0x33; 32]);
261        let offer = parse_offer(&h0.to_base32(), &[h1.to_base32(), h2.to_base32()]).expect("parse");
262        assert_eq!(offer.head, h0);
263        assert_eq!(offer.ancestors, vec![h1, h2]);
264    }
265
266    #[test]
267    fn parse_offer_rejects_bad_base32() {
268        // A non-base32 / wrong-length head fails closed (not a panic).
269        assert!(parse_offer("not valid base32!", &[]).is_err());
270        // A good head but a bad ancestor also fails.
271        let good = AumHash([1u8; 32]).to_base32();
272        assert!(parse_offer(&good, &["@@@@".to_string()]).is_err());
273    }
274
275    #[test]
276    fn decode_aums_roundtrips_and_rejects_garbage() {
277        // A valid AUM serializes → decode_aums reconstructs it; a garbage blob in the batch rejects
278        // the whole batch (fail-closed, never partial trust).
279        let aum = Aum {
280            message_kind: ts_tka::AumKind::NoOp,
281            prev_aum_hash: None,
282            key: None,
283            key_id: Vec::new(),
284            state: None,
285            votes: None,
286            meta: Vec::new(),
287            signatures: Vec::new(),
288        };
289        let good = aum.serialize();
290        let decoded = decode_aums(std::slice::from_ref(&good)).expect("decode");
291        assert_eq!(decoded.len(), 1);
292        assert_eq!(decoded[0].hash(), aum.hash());
293        // One garbage blob alongside a good one → the whole batch errors.
294        assert!(decode_aums(&[good, vec![0xff, 0x00, 0x13]]).is_err());
295    }
296
297    // ---- tka_log_entries (PR-A) ----------------------------------------------------------------
298
299    /// A test [`AumKey`](ts_tka::AumKey) from a seed byte (deterministic public key + given votes).
300    fn test_aum_key(seed: u8, votes: u32) -> ts_tka::AumKey {
301        use ed25519_dalek::SigningKey;
302        ts_tka::AumKey {
303            kind: ts_tka::KeyKind::Ed25519,
304            votes,
305            public: SigningKey::from_bytes(&[seed; 32])
306                .verifying_key()
307                .to_bytes()
308                .to_vec(),
309            meta: Vec::new(),
310        }
311    }
312
313    /// A genesis `Checkpoint` AUM trusting `key` (no parent). Mirrors the on-wire genesis a node
314    /// syncs; built directly (not via `new_genesis_checkpoint`) so the test stays a pure
315    /// ordering/mapping check independent of disablement-value construction.
316    fn genesis_checkpoint(key: ts_tka::AumKey) -> Aum {
317        Aum {
318            message_kind: ts_tka::AumKind::Checkpoint,
319            prev_aum_hash: None,
320            key: None,
321            key_id: Vec::new(),
322            state: Some(ts_tka::AumState {
323                last_aum_hash: None,
324                disablement_values: Some(vec![vec![0x11; 32]]),
325                keys: Some(vec![key]),
326                state_id1: 0,
327                state_id2: 0,
328            }),
329            votes: None,
330            meta: Vec::new(),
331            signatures: Vec::new(),
332        }
333    }
334
335    /// An `AddKey` child of `parent` adding `key`.
336    fn add_key_child(parent: &Aum, key: ts_tka::AumKey) -> Aum {
337        Aum {
338            message_kind: ts_tka::AumKind::AddKey,
339            prev_aum_hash: Some(parent.hash()),
340            key: Some(key),
341            key_id: Vec::new(),
342            state: None,
343            votes: None,
344            meta: Vec::new(),
345            signatures: Vec::new(),
346        }
347    }
348
349    /// `tka_log_entries` returns the chain **head-first** (Go `NetworkLockLog` walks head→genesis,
350    /// the opposite of the store's genesis→head order), with the correct `change` strings, an
351    /// `aum_hash` matching `Aum::hash`, and a `raw` that round-trips through the AUM decoder.
352    #[test]
353    fn tka_log_entries_head_first_with_fields() {
354        let g = genesis_checkpoint(test_aum_key(1, 1));
355        let a1 = add_key_child(&g, test_aum_key(2, 1));
356        let a2 = add_key_child(&a1, test_aum_key(3, 1));
357        // Insert in a scrambled order to prove ordering is by chain links, not insert order.
358        let mut store = MemAumStore::new();
359        store.insert(a1.clone());
360        store.insert(a2.clone());
361        store.insert(g.clone());
362
363        let log = tka_log_entries(&store, g.hash(), 100);
364
365        // (a) head-first: newest (a2) → genesis (g).
366        let got_hashes: Vec<[u8; 32]> = log.iter().map(|e| e.aum_hash).collect();
367        assert_eq!(
368            got_hashes,
369            vec![a2.hash().0, a1.hash().0, g.hash().0],
370            "log must be head-first (a2, a1, genesis)"
371        );
372        // (b) change strings.
373        let changes: Vec<&str> = log.iter().map(|e| e.change.as_str()).collect();
374        assert_eq!(changes, vec!["add-key", "add-key", "checkpoint"]);
375        // (c) aum_hash == Aum::hash().0 (re-checked against the genesis explicitly).
376        assert_eq!(log[2].aum_hash, g.hash().0);
377        // (d) raw round-trips through the AUM decoder back to the same AUM.
378        for (entry, aum) in log.iter().zip([&a2, &a1, &g]) {
379            let decoded = Aum::from_cbor(&entry.raw).expect("raw is canonical AUM CBOR");
380            assert_eq!(&decoded, aum, "raw must decode back to the source AUM");
381        }
382    }
383
384    /// `limit` truncates from the head (the most recent `limit` entries).
385    #[test]
386    fn tka_log_entries_limit_truncates_from_head() {
387        let g = genesis_checkpoint(test_aum_key(1, 1));
388        let a1 = add_key_child(&g, test_aum_key(2, 1));
389        let a2 = add_key_child(&a1, test_aum_key(3, 1));
390        let store = MemAumStore::from_aums([g.clone(), a1.clone(), a2.clone()]);
391
392        let log = tka_log_entries(&store, g.hash(), 2);
393        assert_eq!(log.len(), 2, "limit caps the row count");
394        assert_eq!(
395            log.iter().map(|e| e.aum_hash).collect::<Vec<_>>(),
396            vec![a2.hash().0, a1.hash().0],
397            "limit keeps the newest entries (head-first)"
398        );
399        // limit 0 → empty.
400        assert!(tka_log_entries(&store, g.hash(), 0).is_empty());
401    }
402
403    /// `signer_key_ids` is the `key_id` of each [`AumSignature`](ts_tka::AumSignature) on the AUM,
404    /// in order — what a daemon renders without re-decoding `raw`.
405    #[test]
406    fn tka_log_entries_extracts_signer_key_ids() {
407        use ed25519_dalek::SigningKey;
408        let mut g = genesis_checkpoint(test_aum_key(1, 1));
409        // Sign the genesis with the key it seeds (exactly what `Aum::sign` records: key_id = the
410        // signer's verifying-key bytes).
411        let sk = SigningKey::from_bytes(&[1u8; 32]);
412        g.sign(&sk);
413        let signer_id = sk.verifying_key().to_bytes().to_vec();
414        let store = MemAumStore::from_aums([g.clone()]);
415
416        let log = tka_log_entries(&store, g.hash(), 100);
417        assert_eq!(log.len(), 1);
418        assert_eq!(
419            log[0].signer_key_ids,
420            vec![signer_id],
421            "signer_key_ids carries each signature's key_id"
422        );
423        // An unsigned AUM yields no signer ids.
424        let unsigned = genesis_checkpoint(test_aum_key(2, 1));
425        let store2 = MemAumStore::from_aums([unsigned.clone()]);
426        assert!(
427            tka_log_entries(&store2, unsigned.hash(), 100)[0]
428                .signer_key_ids
429                .is_empty()
430        );
431    }
432
433    /// An empty / unwalkable store yields an empty log (mirrors the no-lock-synced case the actor
434    /// short-circuits before ever calling this): a missing genesis is an empty history, never an
435    /// error.
436    #[test]
437    fn tka_log_entries_unwalkable_store_is_empty() {
438        // Empty store: any `oldest` is absent → BadChain inside, mapped to an empty Vec.
439        let empty = MemAumStore::new();
440        assert!(tka_log_entries(&empty, AumHash([0u8; 32]), 100).is_empty());
441        // Non-empty store but `oldest` not present → still empty (not a panic / error).
442        let g = genesis_checkpoint(test_aum_key(1, 1));
443        let store = MemAumStore::from_aums([g]);
444        assert!(tka_log_entries(&store, AumHash([0xEE; 32]), 100).is_empty());
445    }
446}