diff --git a/lib/src/datum_apis/connector.rs b/lib/src/datum_apis/connector.rs index 3701801..721af6e 100644 --- a/lib/src/datum_apis/connector.rs +++ b/lib/src/datum_apis/connector.rs @@ -1,3 +1,5 @@ +use data_encoding::BASE64; +use iroh::SecretKey; use k8s_openapi::{api::core::v1, apimachinery::pkg::apis::meta::v1 as metav1}; use kube::CustomResource; use serde::{Deserialize, Serialize}; @@ -70,6 +72,30 @@ pub struct ConnectorConnectionDetailsPublicKey { pub discovery_mode: Option, pub home_relay: String, pub addresses: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub binding: Option, +} + +const CONNECTOR_KEY_BINDING_DOMAIN: &str = "datum-connector-binding/v1"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ConnectorKeyBinding { + pub signature: String, +} + +impl ConnectorKeyBinding { + pub fn message(connector_uid: &str, endpoint_id: &str) -> String { + format!("{CONNECTOR_KEY_BINDING_DOMAIN}\n{connector_uid}\n{endpoint_id}") + } + + pub fn sign(secret_key: &SecretKey, connector_uid: &str, endpoint_id: &str) -> Self { + let message = Self::message(connector_uid, endpoint_id); + let signature = secret_key.sign(message.as_bytes()); + Self { + signature: BASE64.encode(&signature.to_bytes()), + } + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -86,6 +112,19 @@ pub struct ConnectorConnectionDetails { pub public_key: Option, } +impl ConnectorConnectionDetails { + pub fn bind(mut self, secret_key: &SecretKey, connector_uid: &str) -> Self { + if let Some(public_key) = self.public_key.as_mut() { + public_key.binding = Some(ConnectorKeyBinding::sign( + secret_key, + connector_uid, + &public_key.id, + )); + } + self + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ConnectorCapabilityStatus { @@ -102,3 +141,96 @@ pub struct ConnectorStatus { pub connection_details: Option, pub lease_ref: Option, } + +#[cfg(test)] +mod tests { + use iroh::Signature; + + use super::*; + + const TEST_SECRET_KEY: [u8; 32] = [ + 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, + 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, + 0x7f, 0x60, + ]; + const TEST_CONNECTOR_UID: &str = "6b0f3c1e-2a4d-4e8b-9c7f-1d2e3f4a5b6c"; + + fn decode_signature(binding: &ConnectorKeyBinding) -> Signature { + let bytes: [u8; Signature::LENGTH] = BASE64 + .decode(binding.signature.as_bytes()) + .unwrap() + .try_into() + .unwrap(); + Signature::from_bytes(&bytes) + } + + #[test] + fn binding_message_format() { + assert_eq!( + ConnectorKeyBinding::message("uid-1", "endpoint-1"), + "datum-connector-binding/v1\nuid-1\nendpoint-1" + ); + } + + #[test] + fn binding_verifies_with_endpoint_key() { + let secret_key = SecretKey::from_bytes(&TEST_SECRET_KEY); + let endpoint_id = secret_key.public().to_string(); + let binding = ConnectorKeyBinding::sign(&secret_key, TEST_CONNECTOR_UID, &endpoint_id); + let signature = decode_signature(&binding); + let message = ConnectorKeyBinding::message(TEST_CONNECTOR_UID, &endpoint_id); + secret_key + .public() + .verify(message.as_bytes(), &signature) + .unwrap(); + + let other = + ConnectorKeyBinding::message("00000000-0000-0000-0000-000000000000", &endpoint_id); + assert!( + secret_key + .public() + .verify(other.as_bytes(), &signature) + .is_err() + ); + } + + #[test] + fn binding_test_vector() { + let secret_key = SecretKey::from_bytes(&TEST_SECRET_KEY); + let endpoint_id = secret_key.public().to_string(); + let binding = ConnectorKeyBinding::sign(&secret_key, TEST_CONNECTOR_UID, &endpoint_id); + assert_eq!( + endpoint_id, + "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a" + ); + assert_eq!( + binding.signature, + "pmdY3eHUNbxquZQw9swz5kxpfWoe1AnFU484kzICxgVRoO0Yn3NcyTJMc1QNzh+DDSU9UPI8V0T+U5Zk/cfuAg==" + ); + } + + #[test] + fn bind_signs_public_key_id() { + let secret_key = SecretKey::from_bytes(&TEST_SECRET_KEY); + let endpoint_id = secret_key.public().to_string(); + let details = ConnectorConnectionDetails { + connection_type: ConnectorConnectionType::PublicKey, + public_key: Some(ConnectorConnectionDetailsPublicKey { + id: endpoint_id.clone(), + discovery_mode: Some(PublicKeyDiscoveryMode::Dns), + home_relay: "https://relay.example".to_string(), + addresses: vec![], + binding: None, + }), + }; + let unbound = serde_json::to_value(&details).unwrap(); + assert!(unbound["publicKey"].get("binding").is_none()); + + let bound = serde_json::to_value(details.bind(&secret_key, TEST_CONNECTOR_UID)).unwrap(); + let expected = ConnectorKeyBinding::sign(&secret_key, TEST_CONNECTOR_UID, &endpoint_id); + assert_eq!( + bound["publicKey"]["binding"]["signature"], + serde_json::Value::String(expected.signature) + ); + } +} diff --git a/lib/src/heartbeat.rs b/lib/src/heartbeat.rs index 04c0331..d2e4e0d 100644 --- a/lib/src/heartbeat.rs +++ b/lib/src/heartbeat.rs @@ -1,7 +1,7 @@ use std::{ collections::{HashMap, HashSet}, sync::Arc, - time::Duration, + time::{Duration, Instant}, }; use chrono::Utc; @@ -19,7 +19,8 @@ use tracing::{debug, warn}; use crate::ListenNode; use crate::datum_apis::connector::{ Connector, ConnectorConnectionDetails, ConnectorConnectionDetailsPublicKey, - ConnectorConnectionType, PublicKeyConnectorAddress, PublicKeyDiscoveryMode, + ConnectorConnectionType, ConnectorKeyBinding, PublicKeyConnectorAddress, + PublicKeyDiscoveryMode, }; use crate::datum_apis::lease::Lease; use crate::datum_cloud::{DatumCloudClient, LoginState}; @@ -40,6 +41,8 @@ const DEFAULT_PCP_NAMESPACE: &str = "default"; const DEFAULT_LEASE_DURATION_SECS: i32 = 30; const BACKOFF_INITIAL: Duration = Duration::from_secs(2); const BACKOFF_MAX: Duration = Duration::from_secs(30); +const READBACK_INTERVAL: Duration = Duration::from_secs(300); +const READBACK_MAX: Duration = Duration::from_secs(3600); #[derive(derive_more::Debug, Clone)] pub struct HeartbeatAgent { @@ -234,10 +237,107 @@ impl HeartbeatAgent { struct ConnectorCache { name: String, + uid: Option, lease_name: Option, lease_duration_seconds: Option, last_details: Option, last_home_relay: Option, + sent_binding: Option, + readback_interval: Duration, + next_readback: Instant, + warned_missing_uid: bool, +} + +impl ConnectorCache { + fn new(connector: &Connector) -> Self { + Self { + name: connector.name_any(), + uid: connector.uid(), + lease_name: connector + .status + .as_ref() + .and_then(|status| status.lease_ref.as_ref()) + .map(|lease| lease.name.clone()), + lease_duration_seconds: None, + last_details: None, + last_home_relay: observed_public_key(connector) + .map(|details| details.home_relay.clone()), + sent_binding: None, + readback_interval: READBACK_INTERVAL, + next_readback: Instant::now() + READBACK_INTERVAL, + warned_missing_uid: false, + } + } + + fn apply_readback(&mut self, connector: &Connector) -> Readback { + let observed_uid = connector.uid(); + let action = readback_action( + self.uid.as_deref(), + observed_uid.as_deref(), + self.sent_binding.as_ref(), + observed_public_key(connector).and_then(|details| details.binding.as_ref()), + ); + match action { + Readback::Unchanged => {} + Readback::Resign => { + self.uid = observed_uid; + self.last_details = None; + self.sent_binding = None; + self.warned_missing_uid = false; + } + Readback::Repatch => { + self.last_details = None; + } + } + self.readback_interval = next_readback_interval(action, self.readback_interval); + self.next_readback = Instant::now() + self.readback_interval; + action + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Readback { + Unchanged, + Resign, + Repatch, +} + +fn readback_action( + cached_uid: Option<&str>, + observed_uid: Option<&str>, + sent_binding: Option<&ConnectorKeyBinding>, + observed_binding: Option<&ConnectorKeyBinding>, +) -> Readback { + if cached_uid != observed_uid { + return Readback::Resign; + } + match sent_binding { + Some(sent) if observed_binding != Some(sent) => Readback::Repatch, + _ => Readback::Unchanged, + } +} + +fn next_readback_interval(action: Readback, current: Duration) -> Duration { + match action { + Readback::Repatch => (current * 2).clamp(READBACK_INTERVAL, READBACK_MAX), + Readback::Unchanged | Readback::Resign => READBACK_INTERVAL, + } +} + +fn details_need_patch(last_sent: Option<&serde_json::Value>, details: &serde_json::Value) -> bool { + last_sent != Some(details) +} + +fn observed_public_key(connector: &Connector) -> Option<&ConnectorConnectionDetailsPublicKey> { + connector + .status + .as_ref() + .and_then(|status| status.connection_details.as_ref()) + .and_then(|details| details.public_key.as_ref()) +} + +fn is_kube_not_found(err: &kube::Error) -> bool { + matches!(err, kube::Error::Api(resp) if resp.code == 404) } async fn run_project( @@ -277,24 +377,7 @@ async fn run_project( if cache.is_none() { match find_connector(&connectors, provider.endpoint_id()).await { Ok(Some(connector)) => { - let lease_name = connector - .status - .as_ref() - .and_then(|status| status.lease_ref.as_ref()) - .map(|lease| lease.name.clone()); - let last_home_relay = connector - .status - .as_ref() - .and_then(|status| status.connection_details.as_ref()) - .and_then(|details| details.public_key.as_ref()) - .map(|details| details.home_relay.clone()); - cache = Some(ConnectorCache { - name: connector.name_any(), - lease_name, - lease_duration_seconds: None, - last_details: None, - last_home_relay, - }); + cache = Some(ConnectorCache::new(&connector)); backoff.reset(); } Ok(None) => { @@ -332,12 +415,9 @@ async fn run_project( cache = Some(cached); continue; } - cached.last_home_relay = connector - .status - .as_ref() - .and_then(|status| status.connection_details.as_ref()) - .and_then(|details| details.public_key.as_ref()) - .map(|details| details.home_relay.clone()); + cached.apply_readback(&connector); + cached.last_home_relay = + observed_public_key(&connector).map(|details| details.home_relay.clone()); } Err(err) => { warn!( @@ -357,7 +437,51 @@ async fn run_project( } } - let details = match provider.connection_details(cached.last_home_relay.as_deref()) { + if Instant::now() >= cached.next_readback { + match connectors.get(&cached.name).await { + Ok(connector) => { + if cached.apply_readback(&connector) == Readback::Repatch { + debug!( + %project_id, + connector = %cached.name, + retry_in = ?cached.readback_interval, + "heartbeat: connector key binding not in status; re-patching" + ); + } + } + Err(err) if is_kube_not_found(&err) => { + debug!(%project_id, connector = %cached.name, "heartbeat: connector gone"); + sleep_with_cancel(backoff.next(), &cancel).await; + continue; + } + Err(err) => { + warn!( + %project_id, + connector = %cached.name, + "heartbeat: failed to read back connector: {err:#}" + ); + if is_kube_auth_failure(&err) { + warn!(%project_id, "heartbeat: kube auth failure; logging out"); + let _ = datum.auth().logout().await; + return; + } + cached.next_readback = Instant::now() + cached.readback_interval; + } + } + } + + if cached.uid.is_none() && !cached.warned_missing_uid { + warn!( + %project_id, + connector = %cached.name, + "heartbeat: connector has no uid; publishing details without a key binding" + ); + cached.warned_missing_uid = true; + } + + let details = match provider + .connection_details(cached.uid.as_deref(), cached.last_home_relay.as_deref()) + { Some(details) => details, None => { warn!(%project_id, connector = %cached.name, "heartbeat: missing home relay"); @@ -381,7 +505,7 @@ async fn run_project( } }; - if cached.last_details.as_ref() != Some(&details_value) { + if details_need_patch(cached.last_details.as_ref(), &details_value) { let patch = json!({ "status": { "connectionDetails": details_value } }); match connectors .patch_status(&cached.name, &PatchParams::default(), &Patch::Merge(&patch)) @@ -389,6 +513,10 @@ async fn run_project( { Ok(_) => { cached.last_details = Some(patch["status"]["connectionDetails"].clone()); + cached.sent_binding = details + .public_key + .as_ref() + .and_then(|details| details.binding.clone()); } Err(err) => { warn!( @@ -454,6 +582,11 @@ async fn run_project( let _ = datum.auth().logout().await; return; } + if is_kube_not_found(&err) { + cached.lease_name = None; + cached.lease_duration_seconds = None; + cached.next_readback = Instant::now(); + } cache = Some(cached); sleep_with_cancel(backoff.next(), &cancel).await; continue; @@ -513,6 +646,7 @@ trait HeartbeatDetailsProvider: Send + Sync { fn endpoint_id(&self) -> String; fn connection_details( &self, + connector_uid: Option<&str>, fallback_home_relay: Option<&str>, ) -> Option; } @@ -534,6 +668,7 @@ impl HeartbeatDetailsProvider for ListenNodeDetailsProvider { fn connection_details( &self, + connector_uid: Option<&str>, fallback_home_relay: Option<&str>, ) -> Option { let endpoint = self.listen.endpoint(); @@ -551,14 +686,19 @@ impl HeartbeatDetailsProvider for ListenNodeDetailsProvider { }) .collect(); - Some(ConnectorConnectionDetails { + let details = ConnectorConnectionDetails { connection_type: ConnectorConnectionType::PublicKey, public_key: Some(ConnectorConnectionDetailsPublicKey { id: endpoint.id().to_string(), discovery_mode: Some(PublicKeyDiscoveryMode::Dns), home_relay, addresses, + binding: None, }), + }; + Some(match connector_uid { + Some(uid) => details.bind(endpoint.secret_key(), uid), + None => details, }) } } @@ -617,6 +757,7 @@ mod tests { fn connection_details( &self, + _connector_uid: Option<&str>, _fallback_home_relay: Option<&str>, ) -> Option { None @@ -676,6 +817,72 @@ mod tests { } } + fn binding(signature: &str) -> ConnectorKeyBinding { + ConnectorKeyBinding { + signature: signature.to_string(), + } + } + + #[test] + fn readback_repatches_when_binding_missing() { + let sent = binding("sig"); + assert_eq!( + readback_action(Some("uid"), Some("uid"), Some(&sent), None), + Readback::Repatch + ); + assert_eq!( + readback_action( + Some("uid"), + Some("uid"), + Some(&sent), + Some(&binding("other")) + ), + Readback::Repatch + ); + } + + #[test] + fn readback_resigns_on_uid_change() { + let sent = binding("sig"); + assert_eq!( + readback_action(Some("old"), Some("new"), Some(&sent), Some(&sent)), + Readback::Resign + ); + assert_eq!( + next_readback_interval(Readback::Resign, READBACK_MAX), + READBACK_INTERVAL + ); + } + + #[test] + fn readback_backs_off_while_binding_is_dropped() { + let sent = binding("sig"); + let mut interval = READBACK_INTERVAL; + let mut previous = Duration::ZERO; + for _ in 0..20 { + let action = readback_action(Some("uid"), Some("uid"), Some(&sent), None); + assert_eq!(action, Readback::Repatch); + interval = next_readback_interval(action, interval); + assert!(interval >= previous && interval >= READBACK_INTERVAL); + assert!(interval <= READBACK_MAX); + previous = interval; + } + assert_eq!(interval, READBACK_MAX); + } + + #[test] + fn readback_keeps_details_when_binding_matches() { + let sent = binding("sig"); + assert_eq!( + readback_action(Some("uid"), Some("uid"), Some(&sent), Some(&sent)), + Readback::Unchanged + ); + assert_eq!(readback_action(None, None, None, None), Readback::Unchanged); + let details = json!({ "publicKey": { "id": "ep", "binding": { "signature": "sig" } } }); + assert!(!details_need_patch(Some(&details), &details)); + assert!(details_need_patch(None, &details)); + } + #[test] fn backoff_doubles_and_resets() { let mut backoff = Backoff::new(); diff --git a/lib/src/tunnels.rs b/lib/src/tunnels.rs index a92a3c0..00a13b5 100644 --- a/lib/src/tunnels.rs +++ b/lib/src/tunnels.rs @@ -1,4 +1,5 @@ use std::collections::{BTreeMap, HashMap}; +use std::sync::{Arc, Mutex}; use iroh_proxy_utils::Authority; use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; @@ -11,7 +12,8 @@ use tracing::{debug, warn}; use crate::datum_apis::allowance_bucket::AllowanceBucket; use crate::datum_apis::connector::{ Connector, ConnectorConnectionDetails, ConnectorConnectionDetailsPublicKey, - ConnectorConnectionType, ConnectorSpec, PublicKeyConnectorAddress, PublicKeyDiscoveryMode, + ConnectorConnectionType, ConnectorKeyBinding, ConnectorSpec, PublicKeyConnectorAddress, + PublicKeyDiscoveryMode, }; use crate::datum_apis::connector_advertisement::{ ConnectorAdvertisement, ConnectorAdvertisementLayer4, ConnectorAdvertisementLayer4Service, @@ -152,6 +154,33 @@ pub struct TunnelService { listen: ListenNode, publish_tickets: bool, create_traffic_protection_policies: bool, + sent_bindings: Arc>>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct SentBinding { + binding: ConnectorKeyBinding, + readback: Option, +} + +fn connector_needs_patch( + current: Option<&ConnectorConnectionDetailsPublicKey>, + desired: &ConnectorConnectionDetailsPublicKey, + sent: Option<&SentBinding>, +) -> bool { + let Some(current) = current else { + return true; + }; + if current.id != desired.id { + return true; + } + if current.binding == desired.binding { + return false; + } + match (sent, desired.binding.as_ref()) { + (Some(sent), Some(desired)) => sent.binding != *desired || sent.readback != current.binding, + _ => true, + } } // TODO(zachsmith1): Use connectors + ConnectorAdvertisements across all projects to @@ -187,6 +216,7 @@ impl TunnelService { listen, publish_tickets: publish_tickets_enabled(), create_traffic_protection_policies: create_traffic_protection_policies_enabled(), + sent_bindings: Arc::default(), } } @@ -899,14 +929,16 @@ impl TunnelService { let project_id_owned = project_id.to_string(); let connection_details = build_connection_details(&self.listen); + let secret_key = self.listen.endpoint().secret_key().clone(); let device_annotations_value = device_annotations(); let connector = pcp .with_auth_retry(|client| { let selector = selector.clone(); - let endpoint_id = endpoint_id.clone(); let project_id = project_id_owned.clone(); let connection_details = connection_details.clone(); + let secret_key = secret_key.clone(); + let sent_bindings = self.sent_bindings.clone(); let device_annotations_value = device_annotations_value.clone(); async move { let connectors: Api = Api::namespaced(client, DEFAULT_PCP_NAMESPACE); @@ -925,21 +957,37 @@ impl TunnelService { } return Ok(None); } - let mut connector = fallback.items.into_iter().next().unwrap(); - let needs_patch = connector - .status - .as_ref() - .and_then(|status| status.connection_details.as_ref()) - .and_then(|details| details.public_key.as_ref()) - .map(|details| details.id.as_str() != endpoint_id.as_str()) - .unwrap_or(true); - if needs_patch && let Some(details) = connection_details.as_ref() { - let details_value = match serde_json::to_value(details) { - Ok(v) => v, - Err(err) => { - return Err(kube::Error::SerdeError(err)); - } - }; + fallback.items.into_iter().next().unwrap() + } else { + if list.items.len() > 1 { + debug!( + %selector, + count = list.items.len(), + "Multiple connectors found for endpoint, using first" + ); + } + list.items.into_iter().next().unwrap() + }; + if let Some(details) = connection_details.as_ref() + && let Some(uid) = connector.uid() + { + let details = details.clone().bind(&secret_key, &uid); + let sent = sent_bindings.lock().unwrap().get(&uid).cloned(); + let needs_patch = match details.public_key.as_ref() { + Some(desired) => connector_needs_patch( + connector + .status + .as_ref() + .and_then(|status| status.connection_details.as_ref()) + .and_then(|details| details.public_key.as_ref()), + desired, + sent.as_ref(), + ), + None => false, + }; + if needs_patch { + let details_value = + serde_json::to_value(&details).map_err(kube::Error::SerdeError)?; let patch = json!({ "status": { "connectionDetails": details_value } }); if let Err(err) = connectors .patch_status( @@ -955,19 +1003,25 @@ impl TunnelService { ); } else { connector = connectors.get(&connector.name_any()).await?; + if let Some(binding) = details + .public_key + .as_ref() + .and_then(|details| details.binding.clone()) + { + let readback = connector + .status + .as_ref() + .and_then(|status| status.connection_details.as_ref()) + .and_then(|details| details.public_key.as_ref()) + .and_then(|details| details.binding.clone()); + sent_bindings + .lock() + .unwrap() + .insert(uid, SentBinding { binding, readback }); + } } } - connector - } else { - if list.items.len() > 1 { - debug!( - %selector, - count = list.items.len(), - "Multiple connectors found for endpoint, using first" - ); - } - list.items.into_iter().next().unwrap() - }; + } patch_device_annotations( &connectors, &mut connector, @@ -988,6 +1042,7 @@ impl TunnelService { let pcp = self.datum.project_control_plane_client(project_id).await?; let connection_details = build_connection_details(&self.listen); + let secret_key = self.listen.endpoint().secret_key().clone(); let device_annotations_value = device_annotations(); let connector = pcp @@ -1010,9 +1065,13 @@ impl TunnelService { .create(&PostParams::default(), &connector) .await?; - if let Some(details) = connection_details.as_ref() { + if let Some(details) = connection_details { + let details = match connector.uid() { + Some(uid) => details.bind(&secret_key, &uid), + None => details, + }; let details_value = - serde_json::to_value(details).map_err(kube::Error::SerdeError)?; + serde_json::to_value(&details).map_err(kube::Error::SerdeError)?; let patch = json!({ "status": { "connectionDetails": details_value } }); if let Err(err) = connectors .patch_status( @@ -1098,6 +1157,7 @@ fn build_connection_details(listen: &ListenNode) -> Option ConnectorKeyBinding { + ConnectorKeyBinding { + signature: signature.to_string(), + } + } + + fn public_key( + id: &str, + binding: Option, + ) -> ConnectorConnectionDetailsPublicKey { + ConnectorConnectionDetailsPublicKey { + id: id.to_string(), + discovery_mode: Some(PublicKeyDiscoveryMode::Dns), + home_relay: "https://relay.example".to_string(), + addresses: vec![], + binding, + } + } + + #[test] + fn patches_when_binding_missing() { + let desired = public_key("ep", Some(binding("sig"))); + assert!(connector_needs_patch( + Some(&public_key("ep", None)), + &desired, + None + )); + assert!(connector_needs_patch(None, &desired, None)); + } + + #[test] + fn patches_when_binding_is_for_a_stale_uid() { + let desired = public_key("ep", Some(binding("sig-new-uid"))); + let current = public_key("ep", Some(binding("sig-old-uid"))); + let sent = SentBinding { + binding: binding("sig-old-uid"), + readback: Some(binding("sig-old-uid")), + }; + assert!(connector_needs_patch(Some(¤t), &desired, Some(&sent))); + assert!(connector_needs_patch(Some(¤t), &desired, None)); + } + + #[test] + fn skips_repatch_when_operator_drops_binding() { + let desired = public_key("ep", Some(binding("sig"))); + let current = public_key("ep", None); + let sent = SentBinding { + binding: binding("sig"), + readback: None, + }; + assert!(!connector_needs_patch( + Some(¤t), + &desired, + Some(&sent) + )); + } + + #[test] + fn patches_when_endpoint_id_differs() { + let desired = public_key("ep", Some(binding("sig"))); + let sent = SentBinding { + binding: binding("sig"), + readback: None, + }; + assert!(connector_needs_patch( + Some(&public_key("other", None)), + &desired, + Some(&sent) + )); + } + + #[test] + fn skips_patch_when_binding_matches() { + let desired = public_key("ep", Some(binding("sig"))); + assert!(!connector_needs_patch( + Some(&desired.clone()), + &desired, + None + )); + } +}