diff --git a/docs/magic-dns-records.md b/docs/magic-dns-records.md index 5397cf5e..6a57350a 100644 --- a/docs/magic-dns-records.md +++ b/docs/magic-dns-records.md @@ -133,6 +133,14 @@ edits can overwrite each other. Records do not have IDs or individual CRUD operations; this model adds neither configuration CAS nor a publication ACK state machine. +Web keeps the original desired configuration when a connected core does not +advertise DNS configuration support. For that heartbeat, startup, patch planning, +readback comparison and runtime caches omit the unsupported `dns` field. Other +configuration still converges, and an applied revision means its supported fields +were applied. Once a core advertises support, the retained DNS configuration +participates in strict comparison and reconciliation again. This does not infer +capabilities from an offline device or add a frontend notice. + ## Runtime boundary All connected local instances contribute, including Web-managed and standalone diff --git a/easytier-web/src/client_manager/mod.rs b/easytier-web/src/client_manager/mod.rs index 0d1626fa..a0e8e554 100644 --- a/easytier-web/src/client_manager/mod.rs +++ b/easytier-web/src/client_manager/mod.rs @@ -16,12 +16,25 @@ use std::{ use dashmap::DashMap; use easytier::proto::{ - api::{config::ConfigRpc, manage::WebClientService}, + api::{ + config::ConfigRpc, + manage::{ + DeleteNetworkInstanceRequest, GetNetworkInstanceConfigRequest, NetworkConfig, + RunNetworkInstanceRequest, ValidateConfigRequest, ValidateConfigResponse, + WebClientService, + }, + }, rpc_types::controller::BaseController, web::{HeartbeatRequest, HeartbeatResponse}, }; use easytier_core::{ - management::remote_client::{self, RemoteClientManager}, + config::toml::ConfigSource, + management::{ + config_source_from_rpc, config_source_to_rpc, + remote_client::{ + self, PersistentConfig as _, RemoteClientError, RemoteClientManager, Storage as _, + }, + }, socket::SocketListener, tunnel::{Tunnel, web_security}, }; @@ -539,6 +552,7 @@ impl ClientManager { } } +#[async_trait::async_trait] impl RemoteClientManager< (UserIdInDb, uuid::Uuid), @@ -571,6 +585,192 @@ impl > { self.storage.db() } + + async fn handle_validate_config( + &self, + (user_id, machine_id): (UserIdInDb, uuid::Uuid), + config: NetworkConfig, + ) -> Result> { + let session = self + .get_session_by_machine_id(user_id, &machine_id) + .ok_or(RemoteClientError::ClientNotFound)?; + let heartbeat = session + .get_heartbeat_req() + .await + .ok_or_else(|| RemoteClientError::Other("Client heartbeat is not ready".to_owned()))?; + session + .scoped_rpc_client() + .validate_config( + BaseController::default(), + ValidateConfigRequest { + config: Some(runtime_reconcile::runtime_config_for_dns_capability( + config, + heartbeat.support_dns_config, + )), + }, + ) + .await + .map_err(RemoteClientError::RpcError) + } + + async fn handle_run_network_instance_with_source( + &self, + identify @ (user_id, machine_id): (UserIdInDb, uuid::Uuid), + config: NetworkConfig, + save: bool, + source: ConfigSource, + ) -> Result<(), RemoteClientError> { + let session = self + .get_session_by_machine_id(user_id, &machine_id) + .ok_or(RemoteClientError::ClientNotFound)?; + let heartbeat = session + .get_heartbeat_req() + .await + .ok_or_else(|| RemoteClientError::Other("Client heartbeat is not ready".to_owned()))?; + let response = session + .scoped_rpc_client() + .run_network_instance( + BaseController::default(), + RunNetworkInstanceRequest { + inst_id: None, + config: Some(runtime_reconcile::runtime_config_for_dns_capability( + config.clone(), + heartbeat.support_dns_config, + )), + overwrite: true, + source: config_source_to_rpc(source), + }, + ) + .await?; + if save { + self.storage + .db() + .insert_or_update_user_network_config( + identify, + response.inst_id.unwrap_or_default().into(), + config, + source, + ) + .await + .map_err(RemoteClientError::PersistentError)?; + } + Ok(()) + } + + async fn handle_update_network_state( + &self, + identify @ (user_id, machine_id): (UserIdInDb, uuid::Uuid), + inst_id: uuid::Uuid, + disabled: bool, + ) -> Result<(), RemoteClientError> { + let session = self + .get_session_by_machine_id(user_id, &machine_id) + .ok_or(RemoteClientError::ClientNotFound)?; + let client = session.scoped_rpc_client(); + let (config, source) = self + .handle_get_network_config_with_source(identify, inst_id) + .await?; + if disabled { + self.storage + .db() + .insert_or_update_user_network_config(identify, inst_id, config, source) + .await + .map_err(RemoteClientError::PersistentError)?; + client + .delete_network_instance( + BaseController::default(), + DeleteNetworkInstanceRequest { + inst_ids: vec![inst_id.into()], + }, + ) + .await?; + } else { + let heartbeat = session.get_heartbeat_req().await.ok_or_else(|| { + RemoteClientError::Other("Client heartbeat is not ready".to_owned()) + })?; + client + .run_network_instance( + BaseController::default(), + RunNetworkInstanceRequest { + inst_id: Some(inst_id.into()), + config: Some(runtime_reconcile::runtime_config_for_dns_capability( + config, + heartbeat.support_dns_config, + )), + overwrite: true, + source: config_source_to_rpc(source), + }, + ) + .await?; + } + self.storage + .db() + .update_network_config_state(identify, inst_id, disabled) + .await + .map_err(RemoteClientError::PersistentError) + } + + async fn handle_get_network_config_with_source( + &self, + identify @ (user_id, machine_id): (UserIdInDb, uuid::Uuid), + inst_id: uuid::Uuid, + ) -> Result<(NetworkConfig, ConfigSource), RemoteClientError> { + if let Some(session) = self.get_session_by_machine_id(user_id, &machine_id) + && let Ok(response) = session + .scoped_rpc_client() + .get_network_instance_config( + BaseController::default(), + GetNetworkInstanceConfigRequest { + inst_id: Some(inst_id.into()), + }, + ) + .await + && let Some(mut config) = response.config + { + let source = config_source_from_rpc(response.source); + let retain_saved_dns = session + .get_heartbeat_req() + .await + .is_some_and(|heartbeat| !heartbeat.support_dns_config); + let saved = if retain_saved_dns || source.is_none() { + self.storage + .db() + .get_network_config(identify, &inst_id.to_string()) + .await + .map_err(RemoteClientError::PersistentError)? + } else { + None + }; + if retain_saved_dns && let Some(saved) = &saved { + // The editor must retain DNS intent that this core cannot return. + config.dns = saved + .get_network_config() + .map_err(RemoteClientError::PersistentError)? + .dns; + } + let source = source.unwrap_or_else(|| { + saved + .map(|config| config.get_runtime_network_config_source()) + .unwrap_or(ConfigSource::User) + }); + return Ok((config, source)); + } + let saved = self + .storage + .db() + .get_network_config(identify, &inst_id.to_string()) + .await + .map_err(RemoteClientError::PersistentError)? + .ok_or_else(|| { + RemoteClientError::NotFound(format!("No such network instance: {inst_id}")) + })?; + Ok(( + saved + .get_network_config() + .map_err(RemoteClientError::PersistentError)?, + saved.get_runtime_network_config_source(), + )) + } } #[cfg(test)] @@ -1276,6 +1476,279 @@ mod tests { println!("{:?}", mgr); } + #[tokio::test] + async fn direct_dns_runtime_requests_follow_heartbeat_and_preserve_saved_config() { + use easytier::proto::{ + api::manage::{ + GetNetworkInstanceConfigRequest, GetNetworkInstanceConfigResponse, + ListNetworkInstanceMetaResponse, ListNetworkInstanceResponse, + RunNetworkInstanceRequest, RunNetworkInstanceResponse, ValidateConfigRequest, + ValidateConfigResponse, WebClientServiceDescriptor, + WebClientServiceMethodDescriptor, + }, + rpc::bidirect::BidirectRpcManager, + rpc_types::handler::Handler, + web::{HeartbeatRequest, WebServerServiceClientFactory}, + }; + use prost::Message as _; + + #[derive(Default)] + struct Requests { + runs: Vec, + validations: Vec, + runtime_config: Option, + } + #[derive(Clone)] + struct Recorder { + instance_id: uuid::Uuid, + requests: Arc>, + } + #[async_trait::async_trait] + impl Handler for Recorder { + type Descriptor = WebClientServiceDescriptor; + type Controller = super::BaseController; + + async fn call( + &self, + _: Self::Controller, + method: WebClientServiceMethodDescriptor, + input: prost::bytes::Bytes, + ) -> easytier::proto::rpc_types::error::Result { + let mut requests = self.requests.lock().unwrap(); + let response = match method { + WebClientServiceMethodDescriptor::RunNetworkInstance => { + let request = RunNetworkInstanceRequest::decode(input)?; + requests.runtime_config = request.config.clone(); + requests.runs.push(request); + RunNetworkInstanceResponse { + inst_id: Some(self.instance_id.into()), + } + .encode_to_vec() + } + WebClientServiceMethodDescriptor::ValidateConfig => { + requests + .validations + .push(ValidateConfigRequest::decode(input)?); + ValidateConfigResponse::default().encode_to_vec() + } + WebClientServiceMethodDescriptor::GetNetworkInstanceConfig => { + let request = GetNetworkInstanceConfigRequest::decode(input)?; + assert_eq!( + request.inst_id.map(uuid::Uuid::from), + Some(self.instance_id) + ); + GetNetworkInstanceConfigResponse { + config: requests.runtime_config.clone(), + source: easytier::proto::api::manage::ConfigSource::User as i32, + } + .encode_to_vec() + } + WebClientServiceMethodDescriptor::DeleteNetworkInstance => { + requests.runtime_config = None; + easytier::proto::api::manage::DeleteNetworkInstanceResponse::default() + .encode_to_vec() + } + WebClientServiceMethodDescriptor::ListNetworkInstance => { + ListNetworkInstanceResponse::default().encode_to_vec() + } + WebClientServiceMethodDescriptor::ListNetworkInstanceMeta => { + ListNetworkInstanceMetaResponse::default().encode_to_vec() + } + _ => panic!("unexpected direct runtime method: {method:?}"), + }; + Ok(response.into()) + } + } + + let db = Db::memory_db().await; + let mgr = ClientManager::new( + db.clone(), + None, + HeartbeatPolicy::default(), + Arc::new(FeatureFlags::default()), + Arc::new(crate::webhook::WebhookConfig::new( + None, None, None, None, None, + )), + ); + let user_id = db + .auto_create_user("dns-capability-token") + .await + .unwrap() + .id; + let machine_id = uuid::Uuid::new_v4(); + let instance_id = uuid::Uuid::new_v4(); + let identify = (user_id, machine_id); + let saved = NetworkConfig { + instance_id: Some(instance_id.to_string()), + hostname: Some("dns-capability-host".to_owned()), + networking_method: Some(NetworkingMethod::Standalone as i32), + dns: Some(easytier::proto::core_config::DnsConfigRaw { + domain: Some("retained.test".to_owned()), + zone: None, + }), + ..Default::default() + }; + assert!(matches!( + mgr.handle_validate_config(identify, saved.clone()).await, + Err(super::RemoteClientError::ClientNotFound) + )); + assert!(matches!( + mgr.handle_run_network_instance(identify, saved.clone(), true) + .await, + Err(super::RemoteClientError::ClientNotFound) + )); + + let requests = Arc::new(std::sync::Mutex::new(Requests::default())); + let rpc = BidirectRpcManager::new(); + rpc.rpc_server().registry().register( + Recorder { + instance_id, + requests: requests.clone(), + }, + "", + ); + let client_url = "ring://dns-capability".parse::().unwrap(); + let mut session = Session::new( + mgr.storage.weak_ref(), + client_url.clone(), + None, + HeartbeatPolicy::default(), + Arc::new(FeatureFlags::default()), + Arc::new(crate::webhook::WebhookConfig::new( + None, None, None, None, None, + )), + 1, + ); + session.serve(rpc.run_and_create_tunnel()).await; + let session = Arc::new(session); + mgr.client_sessions + .insert(client_url.clone(), session.clone()); + mgr.storage.update_client( + StorageToken { + token: "dns-capability-token".to_owned(), + client_url, + machine_id, + user_id, + }, + 1, + true, + ); + for result in [ + mgr.handle_validate_config(identify, saved.clone()) + .await + .map(|_| ()), + mgr.handle_run_network_instance(identify, saved.clone(), true) + .await, + ] { + assert!(matches!( + result, + Err(super::RemoteClientError::Other(message)) + if message == "Client heartbeat is not ready" + )); + } + assert!(requests.lock().unwrap().runs.is_empty()); + assert!(requests.lock().unwrap().validations.is_empty()); + assert!( + db.get_network_config(identify, &instance_id.to_string()) + .await + .unwrap() + .is_none() + ); + + let heartbeat_client = rpc + .rpc_client() + .scoped_client::>( + 1, + 1, + String::new(), + ); + let runtime_id = uuid::Uuid::new_v4(); + for (index, supported) in [false, true, false].into_iter().enumerate() { + heartbeat_client + .heartbeat( + super::BaseController::default(), + HeartbeatRequest { + machine_id: Some(machine_id.into()), + inst_id: Some(runtime_id.into()), + user_token: "dns-capability-token".to_owned(), + report_time: chrono::Local::now().to_rfc3339(), + support_config_source: true, + support_heartbeat_policy: true, + support_manual_routes_patch: true, + support_dns_config: supported, + running_network_instances: vec![instance_id.into()], + ..Default::default() + }, + ) + .await + .unwrap(); + mgr.handle_validate_config(identify, saved.clone()) + .await + .unwrap(); + mgr.handle_run_network_instance(identify, saved.clone(), index == 2) + .await + .unwrap(); + } + let editable = mgr + .handle_get_network_config(identify, instance_id) + .await + .unwrap(); + assert_eq!(editable, saved); + assert!( + requests + .lock() + .unwrap() + .runtime_config + .as_ref() + .unwrap() + .dns + .is_none() + ); + mgr.handle_save_network_config(identify, instance_id, editable) + .await + .unwrap(); + mgr.handle_update_network_state(identify, instance_id, true) + .await + .unwrap(); + mgr.handle_update_network_state(identify, instance_id, false) + .await + .unwrap(); + + { + let observed = requests.lock().unwrap(); + assert_eq!(observed.validations.len(), 3); + assert_eq!(observed.runs.len(), 4); + for (index, supported) in [false, true, false].into_iter().enumerate() { + let mut target = saved.clone(); + if !supported { + target.dns = None; + } + assert_eq!(observed.validations[index].config, Some(target.clone())); + assert_eq!(observed.runs[index].config, Some(target)); + assert!(observed.runs[index].overwrite); + assert!(observed.runs[index].inst_id.is_none()); + } + let restarted = &observed.runs[3]; + assert!(restarted.config.as_ref().unwrap().dns.is_none()); + assert_eq!(restarted.inst_id.map(uuid::Uuid::from), Some(instance_id)); + assert!(restarted.overwrite); + assert!(observed.runs.iter().all(|request| { + request.source == easytier::proto::api::manage::ConfigSource::User as i32 + })); + } + let persisted = db + .get_network_config(identify, &instance_id.to_string()) + .await + .unwrap() + .unwrap(); + let persisted_config: NetworkConfig = + serde_json::from_str(&persisted.network_config).unwrap(); + assert_eq!(persisted_config, saved); + assert!(!persisted.disabled); + session.stop().await; + rpc.stop().await; + } + #[tokio::test] async fn compact_runtime_preserves_unsupported_web_config_during_hot_patch() { let (webhook_config, webhook_server, webhook_state) = test_webhook_config().await; @@ -1743,7 +2216,7 @@ mod tests { #[tokio::test] #[ignore = "requires EASYTIER_TEST_LEGACY_CORE and an isolated network environment"] - async fn legacy_core_reconciles_ordinary_config_and_rejects_dns() { + async fn legacy_core_reconciles_supported_fields_and_retains_saved_dns() { use easytier::proto::api::instance::PeerManageRpcClientFactory; use easytier::proto::rpc_types::controller::BaseController; @@ -1827,7 +2300,7 @@ mod tests { previous_revision = Some(revision.to_owned()); } - desired["hostname"] = json!("must-not-be-patched"); + desired["hostname"] = json!("legacy-with-saved-dns"); desired["dns"] = json!({"domain": "unsupported.test"}); *webhook_state.config_revision.write().await = "legacy-unsupported".to_owned(); mgr.reconcile_managed_network_configs( @@ -1839,14 +2312,7 @@ mod tests { ) .await .unwrap(); - assert!( - tokio::time::timeout( - Duration::from_secs(8), - wait_for_applied_revision(&mgr, user_id, machine_id, "legacy-unsupported"), - ) - .await - .is_err() - ); + wait_for_applied_revision(&mgr, user_id, machine_id, "legacy-unsupported").await; let observed = super::runtime_reconcile::get_runtime_config( &mut config_client, &mut peer_client, @@ -1855,8 +2321,20 @@ mod tests { ) .await .unwrap(); - assert_eq!(observed.hostname.as_deref(), Some("legacy-updated-host")); + assert_eq!(observed.hostname.as_deref(), Some("legacy-with-saved-dns")); assert!(observed.dns.is_none()); + let saved = mgr + .storage + .db() + .get_network_config((user_id, machine_id), &instance_id.to_string()) + .await + .unwrap() + .unwrap(); + let saved: NetworkConfig = serde_json::from_str(&saved.network_config).unwrap(); + assert_eq!( + saved.dns.unwrap().domain.as_deref(), + Some("unsupported.test") + ); desired["dns"] = serde_json::Value::Null; *webhook_state.config_revision.write().await = "legacy-recovered".to_owned(); diff --git a/easytier-web/src/client_manager/runtime_reconcile.rs b/easytier-web/src/client_manager/runtime_reconcile.rs index 26a7cd28..50f27857 100644 --- a/easytier-web/src/client_manager/runtime_reconcile.rs +++ b/easytier-web/src/client_manager/runtime_reconcile.rs @@ -22,6 +22,7 @@ use easytier::{ }, common::{CompressionAlgoPb, FlagsPatch, Ipv4Inet as RpcIpv4Inet}, rpc_types::controller::BaseController, + web::HeartbeatRequest, }, }; use optionize::Retain; @@ -96,19 +97,15 @@ fn full_dns_patch( easytier_core::gateway::magic_dns::normalized_dns(&config.gen_config()?) } -pub(super) fn ensure_dns_config_supported( - config: &NetworkConfig, +pub(super) fn runtime_config_for_dns_capability( + mut config: NetworkConfig, support_dns_config: bool, -) -> anyhow::Result<()> { - if !support_dns_config && config.dns.is_some() { - let mut legacy_config = config.clone(); - legacy_config.dns = None; - anyhow::ensure!( - full_dns_patch(config)? == full_dns_patch(&legacy_config)?, - "core does not support DNS configuration" - ); +) -> NetworkConfig { + // Keep saved intent intact; only the runtime target follows this heartbeat. + if !support_dns_config { + config.dns = None; } - Ok(()) + config } fn normalized_data_compress_algo(algo: Option) -> Option { @@ -565,7 +562,9 @@ pub(super) async fn prepare_web_source_runtime_reconcile( desired_config: NetworkConfig, is_running: bool, support_manual_routes_patch: bool, + support_dns_config: bool, ) -> anyhow::Result { + let desired_config = runtime_config_for_dns_capability(desired_config, support_dns_config); if !is_running { return Ok(RuntimeReconcileAction::Run { config: Box::new(desired_config), @@ -580,6 +579,7 @@ pub(super) async fn prepare_web_source_runtime_reconcile( support_manual_routes_patch, ) .await?; + let current_config = runtime_config_for_dns_capability(current_config, support_dns_config); prepare_web_source_runtime_reconcile_from_current( ¤t_config, @@ -621,20 +621,24 @@ pub(super) async fn apply_web_source_runtime_reconcile( inst_id: &str, desired_config: NetworkConfig, action: RuntimeReconcileAction, - support_manual_routes_patch: bool, + heartbeat: &HeartbeatRequest, ) -> anyhow::Result { + let desired_config = + runtime_config_for_dns_capability(desired_config, heartbeat.support_dns_config); match action { RuntimeReconcileAction::Unchanged(current_config) => Ok(*current_config), RuntimeReconcileAction::Run { config, overwrite } => { let hostname_applied = config.hostname.is_some(); run_web_source_instance(rpc_client, inst_id, *config, overwrite).await?; - let mut current_config = get_runtime_config( + let current_config = get_runtime_config( config_client, peer_client, inst_id, - support_manual_routes_patch, + heartbeat.support_manual_routes_patch, ) .await?; + let mut current_config = + runtime_config_for_dns_capability(current_config, heartbeat.support_dns_config); ensure_runtime_config_converged(¤t_config, &desired_config, hostname_applied)?; restore_omitted_hostname(&mut current_config, &desired_config, hostname_applied); Ok(current_config) @@ -650,13 +654,15 @@ pub(super) async fn apply_web_source_runtime_reconcile( }, ) .await?; - let mut current_config = get_runtime_config( + let current_config = get_runtime_config( config_client, peer_client, inst_id, - support_manual_routes_patch, + heartbeat.support_manual_routes_patch, ) .await?; + let mut current_config = + runtime_config_for_dns_capability(current_config, heartbeat.support_dns_config); ensure_runtime_config_converged(¤t_config, &desired_config, hostname_applied)?; restore_omitted_hostname(&mut current_config, &desired_config, hostname_applied); Ok(current_config) @@ -1244,6 +1250,7 @@ mod tests { #[async_trait::async_trait] impl ConfigRpc for ConfigReader { type Controller = BaseController; + async fn get_dns_status( &self, _: BaseController, @@ -1253,7 +1260,6 @@ mod tests { > { unreachable!("configuration reconciliation does not query DNS publication") } - async fn get_config( &self, _: BaseController, @@ -1820,53 +1826,63 @@ mod tests { #[test] #[allow(deprecated)] - fn legacy_core_allows_dns_equivalent_to_legacy_config() { - for legacy_domain in [None, Some("corp.internal.")] { - let mut current = config_with_port_forwards(Vec::new()); - current.tld_dns_zone = legacy_domain.map(str::to_owned); - ensure_dns_config_supported(¤t, false).unwrap(); - let domain = legacy_domain.unwrap_or("et.net."); - for domain in [ - None, - Some(domain.to_owned()), - Some(domain.trim_end_matches('.').to_uppercase()), - ] { - let mut desired = current.clone(); - desired.dns = Some(easytier::proto::core_config::DnsConfigRaw { - domain, - zone: Some(Default::default()), - }); - ensure_dns_config_supported(&desired, false).unwrap(); - ensure_runtime_config_converged(¤t, &desired, false).unwrap(); - } - } + fn legacy_dns_runtime_target_keeps_saved_dns_and_legacy_domain() { + let mut saved = config_with_dns( + "mesh.test", + "records.test", + &[dns_record( + easytier::proto::core_config::DnsRecordType::A, + "192.0.2.1", + )], + ); + saved.tld_dns_zone = Some("corp.internal.".to_owned()); + let original = saved.clone(); + let target = runtime_config_for_dns_capability(saved.clone(), false); + assert!(target.dns.is_none()); + assert_eq!(saved, original); + assert_eq!(target.tld_dns_zone, saved.tld_dns_zone); + assert_eq!( + full_dns_patch(&target).unwrap().domain.as_deref(), + Some("corp.internal.") + ); + + let mut current = target.clone(); + current.hostname = Some("before".to_owned()); + let mut desired = target; + desired.hostname = Some("after".to_owned()); + let RuntimeReconcileAction::Patch(patch) = + prepare_web_source_runtime_reconcile_from_current(¤t, desired.clone(), true) + .unwrap() + else { + panic!("supported fields should still produce a patch"); + }; + assert_eq!(patch.hostname.as_deref(), Some("after")); + assert!(patch.dns.is_none()); + current.hostname = desired.hostname.clone(); + ensure_runtime_config_converged(¤t, &desired, true).unwrap(); } #[test] - #[allow(deprecated)] - fn legacy_core_rejects_dns_zones_or_domain_changes() { - let mut custom_domain = config_with_dns("mesh.test", "records.test", &[]); - custom_domain.dns.as_mut().unwrap().zone = None; - let mut default_domain = config_with_dns("et.net", "records.test", &[]); - default_domain.dns.as_mut().unwrap().zone = None; - for mut config in [ - custom_domain, - default_domain, - config_with_dns("et.net", "records.test", &[]), - config_with_dns( - "et.net", - "records.test", - &[dns_record( - easytier::proto::core_config::DnsRecordType::A, - "192.0.2.1", - )], - ), - ] { - config.tld_dns_zone = Some("corp.internal.".to_owned()); - let error = ensure_dns_config_supported(&config, false).unwrap_err(); - assert_eq!(error.to_string(), "core does not support DNS configuration"); - ensure_dns_config_supported(&config, true).unwrap(); - } + fn dns_capability_restores_strict_runtime_target_after_upgrade() { + let saved = config_with_dns( + "mesh.test", + "records.test", + &[dns_record( + easytier::proto::core_config::DnsRecordType::A, + "192.0.2.1", + )], + ); + let legacy = runtime_config_for_dns_capability(saved.clone(), false); + let supported = runtime_config_for_dns_capability(saved.clone(), true); + assert_eq!(supported, saved); + assert!(ensure_runtime_config_converged(&legacy, &supported, false).is_err()); + + let RuntimeReconcileAction::Patch(patch) = + prepare_web_source_runtime_reconcile_from_current(&legacy, supported, true).unwrap() + else { + panic!("an upgraded runtime must apply the retained DNS configuration"); + }; + assert!(patch.dns.is_some()); } #[test] diff --git a/easytier-web/src/client_manager/session.rs b/easytier-web/src/client_manager/session.rs index 4af5ca77..e2863261 100644 --- a/easytier-web/src/client_manager/session.rs +++ b/easytier-web/src/client_manager/session.rs @@ -108,6 +108,7 @@ pub(super) fn record_managed_config_reconcile_hint( #[derive(Debug, Default)] pub(super) struct ManagedRuntimeState { + // Applied means the fields supported by the runtime's current heartbeat. pub(super) applied_config_revision: Option, pub(super) applied_config_revision_known: bool, pub(super) known_runtime_base_revision: Option, @@ -570,6 +571,19 @@ impl SessionRpcService { data: &mut SessionData, req: HeartbeatRequest, ) -> HeartbeatRequest { + if data + .req + .as_ref() + .is_some_and(|previous| previous.support_dns_config != req.support_dns_config) + { + let mut runtime = data.managed_runtime(); + runtime.applied_config_revision = None; + runtime.applied_config_revision_known = true; + runtime.known_runtime_base_revision = None; + runtime.pending_managed_config_reconcile = Some(ManagedConfigReconcileHint::Full); + runtime.runtime_config_epoch = runtime.runtime_config_epoch.wrapping_add(1); + runtime.runtime_config_cache_epoch = runtime.runtime_config_cache_epoch.wrapping_add(1); + } data.req = Some(req); data.req .clone() @@ -600,6 +614,7 @@ impl SessionRpcService { Self::storage_token_matches_heartbeat(storage_token, req) && data.req.as_ref().is_some_and(|current_req| { Self::storage_token_matches_heartbeat(storage_token, current_req) + && current_req.support_dns_config == req.support_dns_config }) && data.auth_state.is_authorized() && data.storage.upgrade().is_some_and(|storage| { diff --git a/easytier-web/src/client_manager/session/runtime_revision.rs b/easytier-web/src/client_manager/session/runtime_revision.rs index b4b3658d..b1ce8816 100644 --- a/easytier-web/src/client_manager/session/runtime_revision.rs +++ b/easytier-web/src/client_manager/session/runtime_revision.rs @@ -243,13 +243,22 @@ impl SessionRuntimeConfigCache { inst_id: &str, desired_config: NetworkConfig, support_manual_routes_patch: bool, + support_dns_config: bool, ) -> anyhow::Result> { let Some(observed_config) = self.entries.get(inst_id) else { return Ok(None); }; + let observed_config = runtime_reconcile::runtime_config_for_dns_capability( + observed_config.clone(), + support_dns_config, + ); + let desired_config = runtime_reconcile::runtime_config_for_dns_capability( + desired_config, + support_dns_config, + ); runtime_reconcile::prepare_web_source_runtime_reconcile_from_current( - observed_config, + &observed_config, desired_config, support_manual_routes_patch, ) @@ -971,12 +980,11 @@ async fn reconcile_desired_runtime_configs( let desired_config = match serde_json::from_str::(&config.network_config) .map_err(anyhow::Error::from) - .and_then(|config| { - runtime_reconcile::ensure_dns_config_supported( - &config, + .map(|config| { + runtime_reconcile::runtime_config_for_dns_capability( + config, round.req.support_dns_config, - )?; - Ok(config) + ) }) { Ok(cfg) => cfg, Err(e) => { @@ -1027,6 +1035,7 @@ async fn reconcile_desired_runtime_configs( &desired_config, &mut cache.runtime_configs, round.req.support_manual_routes_patch, + round.req.support_dns_config, ) .await { @@ -1092,6 +1101,7 @@ async fn reconcile_running_web_config( &config.network_instance_id, desired_config.clone(), round.req.support_manual_routes_patch, + round.req.support_dns_config, )? { Some(action) => action, None => { @@ -1102,6 +1112,7 @@ async fn reconcile_running_web_config( desired_config.clone(), true, round.req.support_manual_routes_patch, + round.req.support_dns_config, ) .await? } @@ -1123,7 +1134,7 @@ async fn reconcile_running_web_config( &config.network_instance_id, desired_config.clone(), action, - round.req.support_manual_routes_patch, + &round.req, ) .await?; runtime_config_cache.remember(&config.network_instance_id, observed_config); @@ -1232,6 +1243,7 @@ async fn remember_web_runtime_config_after_run( desired_config: &NetworkConfig, runtime_config_cache: &mut SessionRuntimeConfigCache, support_manual_routes_patch: bool, + support_dns_config: bool, ) -> anyhow::Result<()> { let observed_config = runtime_reconcile::get_runtime_config( &mut clients.config, @@ -1240,6 +1252,8 @@ async fn remember_web_runtime_config_after_run( support_manual_routes_patch, ) .await?; + let observed_config = + runtime_reconcile::runtime_config_for_dns_capability(observed_config, support_dns_config); remember_if_runtime_matches_desired( inst_id, desired_config, @@ -1478,19 +1492,95 @@ mod tests { } #[tokio::test] - async fn unsupported_dns_sends_no_config_rpc_and_cannot_mark_revision_applied() { + async fn dns_capability_change_invalidates_applied_revision_and_stale_round() { + let (storage, data, mut round) = takeover_session(Some("current")).await; + round.should_apply_runtime_revision = true; + let weak = std::sync::Arc::downgrade(&data); + let initial_epoch = round.runtime_config_epoch; + for (index, supported) in [true, false].into_iter().enumerate() { + let mut current = round.req.clone(); + current.support_dns_config = supported; + { + let mut data = data.write().await; + SessionRpcService::store_latest_heartbeat_req(&mut data, current.clone()); + let runtime = data.managed_runtime(); + assert!(runtime.applied_config_revision.is_none()); + assert!(runtime.known_runtime_base_revision.is_none()); + assert!(matches!( + runtime.pending_managed_config_reconcile, + Some(ManagedConfigReconcileHint::Full) + )); + assert_eq!( + runtime.runtime_config_epoch, + initial_epoch + index as u64 + 1 + ); + assert_eq!( + runtime.runtime_config_cache_epoch, + round.runtime_config_cache_epoch + index as u64 + 1 + ); + } + assert!(!SessionRpcService::runtime_heartbeat_is_current(&weak, &round.req).await); + assert!(SessionRpcService::runtime_heartbeat_is_current(&weak, ¤t).await); + mark_config_revision_applied_if_current( + &weak, + &storage.weak_ref().upgrade().unwrap(), + &round, + &ReconcileOutcome::default(), + &RuntimeMutationFence::default(), + ) + .await; + assert!( + data.read() + .await + .managed_runtime() + .applied_config_revision + .is_none() + ); + round.req = current; + } + } + + #[tokio::test] + async fn legacy_dns_runtime_target_converges_and_caches_supported_fields() { use easytier::proto::api::{ config::{ ConfigRpc, GetConfigRequest, GetConfigResponse, PatchConfigRequest, PatchConfigResponse, }, instance::PeerManageRpcClientFactory, - manage::WebClientServiceClientFactory, + manage::{ + RunNetworkInstanceResponse, WebClientServiceClient, WebClientServiceClientFactory, + WebClientServiceDescriptor, WebClientServiceMethodDescriptor, + }, }; + use prost::Message as _; - struct NoConfigRpc; + #[derive(Clone)] + struct RunRecorder(std::sync::Arc>>); #[async_trait::async_trait] - impl ConfigRpc for NoConfigRpc { + impl easytier::proto::rpc_types::handler::Handler for RunRecorder { + type Descriptor = WebClientServiceDescriptor; + type Controller = BaseController; + + async fn call( + &self, + _: BaseController, + method: WebClientServiceMethodDescriptor, + input: prost::bytes::Bytes, + ) -> easytier::proto::rpc_types::error::Result { + assert_eq!(method, WebClientServiceMethodDescriptor::RunNetworkInstance); + let request = RunNetworkInstanceRequest::decode(input)?; + self.0.lock().unwrap().push(request); + Ok(RunNetworkInstanceResponse::default().encode_to_vec().into()) + } + } + + struct ConfigReader { + config: NetworkConfig, + reads: std::sync::Arc, + } + #[async_trait::async_trait] + impl ConfigRpc for ConfigReader { type Controller = BaseController; async fn get_dns_status( @@ -1508,7 +1598,12 @@ mod tests { _: BaseController, _: GetConfigRequest, ) -> easytier::proto::rpc_types::error::Result { - panic!("unsupported DNS must be rejected before reading runtime config") + self.reads + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok(GetConfigResponse { + config: Some(self.config.clone()), + toml_config: String::new(), + }) } async fn patch_config( @@ -1516,13 +1611,23 @@ mod tests { _: BaseController, _: PatchConfigRequest, ) -> easytier::proto::rpc_types::error::Result { - panic!("unsupported DNS must not send a patch") + panic!("matching supported fields must not send a patch") } } let (storage, data, mut round) = takeover_session(Some("current")).await; let instance_id = uuid::Uuid::from(round.req.running_network_instances[0]); round.should_apply_runtime_revision = true; + round.req.support_manual_routes_patch = true; + round.running_inst_ids = HashSet::from([instance_id.to_string()]); + let mut current = config_with_port_forwards(Vec::new()); + current.instance_id = Some(instance_id.to_string()); + let mut desired = current.clone(); + desired.dns = Some(easytier::proto::core_config::DnsConfigRaw { + domain: Some("saved-for-upgrade.test".to_owned()), + zone: None, + }); + let saved_config = serde_json::to_string(&desired).unwrap(); round .local_configs .push(crate::db::entity::user_running_network_configs::Model { @@ -1530,17 +1635,14 @@ mod tests { user_id: round.user_id, device_id: round.machine_id.to_string(), network_instance_id: instance_id.to_string(), - network_config: serde_json::json!({ - "networking_method": "Standalone", - "dns": { "domain": "unsupported.test" } - }) - .to_string(), + network_config: saved_config.clone(), source: "web".to_owned(), disabled: false, create_time: chrono::Utc::now().into(), update_time: chrono::Utc::now().into(), }); data.read().await.managed_runtime().applied_config_revision = None; + let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); let rpc = easytier::proto::rpc::bidirect::BidirectRpcManager::new(); let mut clients = SessionClients { rpc: rpc @@ -1550,19 +1652,17 @@ mod tests { 1, String::new(), ), - config: Box::new(NoConfigRpc), + config: Box::new(ConfigReader { + config: current.clone(), + reads: reads.clone(), + }), peer: rpc .rpc_client() .scoped_client::>(1, 1, String::new()), }; let weak = std::sync::Arc::downgrade(&data); let mut cache = ReconcileCache::default(); - for running in [true, false] { - round.running_inst_ids = if running { - HashSet::from([instance_id.to_string()]) - } else { - HashSet::new() - }; + for _ in 0..2 { let mut mutation_fence = RuntimeMutationFence::default(); let outcome = tokio::time::timeout( std::time::Duration::from_millis(250), @@ -1577,8 +1677,8 @@ mod tests { ), ) .await - .expect("capability rejection must not wait for RPC"); - assert!(outcome.managed_revision_failed); + .expect("matching runtime must not wait for a mutation RPC"); + assert!(!outcome.has_failed); assert!(!mutation_fence.started); mark_config_revision_applied_if_current( &weak, @@ -1588,14 +1688,54 @@ mod tests { &mutation_fence, ) .await; - assert!( + assert_eq!( data.read() .await .managed_runtime() .applied_config_revision - .is_none() + .as_deref(), + Some("current") ); } + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 1); + assert!( + cache.runtime_configs.entries[&instance_id.to_string()] + .dns + .is_none() + ); + assert_eq!(round.local_configs[0].network_config, saved_config); + assert!(desired.dns.is_some()); + + let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + clients.rpc = Box::new(WebClientServiceClient::new(RunRecorder(requests.clone()))); + round.running_inst_ids.clear(); + for source in ["web", "user", "legacy"] { + round.local_configs[0].source = source.to_owned(); + let outcome = reconcile_desired_runtime_configs( + &ReconcileRoundContext { + session_data: &weak, + round: &round, + }, + &mut clients, + &mut cache, + &mut RuntimeMutationFence::default(), + ) + .await; + assert!(!outcome.has_failed); + assert_eq!(round.local_configs[0].network_config, saved_config); + } + let requests = requests.lock().unwrap(); + assert_eq!(requests.len(), 3); + for (index, request) in requests.iter().enumerate() { + assert!(request.config.as_ref().unwrap().dns.is_none()); + assert!(!request.overwrite); + let expected_source = if index == 0 { + easytier::proto::api::manage::ConfigSource::Web + } else { + easytier::proto::api::manage::ConfigSource::User + }; + assert_eq!(request.source, expected_source as i32); + } } async fn validate_takeover_session( @@ -2282,7 +2422,12 @@ mod tests { fn session_runtime_config_cache_misses_unknown_instance() { let cache = SessionRuntimeConfigCache::default(); let action = cache - .plan("missing", config_with_port_forwards(Vec::new()), false) + .plan( + "missing", + config_with_port_forwards(Vec::new()), + false, + true, + ) .expect("prepare action"); assert!(action.is_none()); @@ -2305,6 +2450,7 @@ mod tests { "managed", manual.clone(), heartbeat.support_manual_routes_patch, + true, ) .unwrap() .unwrap(); @@ -2329,7 +2475,7 @@ mod tests { cache.remember("managed", config.clone()); let action = cache - .plan("managed", config, false) + .plan("managed", config, false, true) .expect("prepare action") .expect("cached action"); @@ -2348,7 +2494,7 @@ mod tests { let unmanaged_desired = config_with_port_forwards(Vec::new()); let action = cache - .plan("managed", unmanaged_desired, false) + .plan("managed", unmanaged_desired, false, true) .expect("prepare unmanaged hostname action") .expect("cached action"); let runtime_reconcile::RuntimeReconcileAction::Unchanged(observed) = action else { @@ -2360,7 +2506,7 @@ mod tests { let mut explicit_clear = config_with_port_forwards(Vec::new()); explicit_clear.hostname = Some(String::new()); let action = cache - .plan("managed", explicit_clear, false) + .plan("managed", explicit_clear, false, true) .expect("prepare explicit clear action") .expect("cached action"); let runtime_reconcile::RuntimeReconcileAction::Patch(patch) = action else { @@ -2379,7 +2525,7 @@ mod tests { cache.remember("managed", current); let action = cache - .plan("managed", desired, false) + .plan("managed", desired, false, true) .expect("prepare action") .expect("cached action"); @@ -2411,7 +2557,7 @@ mod tests { cache.forget("managed"); let action = cache - .plan("managed", config, false) + .plan("managed", config, false, true) .expect("prepare action after remove"); assert!(action.is_none()); } @@ -2424,7 +2570,7 @@ mod tests { remember_if_runtime_matches_desired("managed", &config, config.clone(), &mut cache) .expect("remember observed config after run"); let action = cache - .plan("managed", config, false) + .plan("managed", config, false, true) .expect("prepare action after run") .expect("cached action"); @@ -2449,7 +2595,7 @@ mod tests { .contains("runtime config still differs after managed run") ); let action = cache - .plan("managed", desired, false) + .plan("managed", desired, false, true) .expect("prepare action after stale run result"); assert!(action.is_none()); } @@ -2484,7 +2630,7 @@ mod tests { let mut cache = SessionRuntimeConfigCache::default(); cache.remember("managed", observed); let action = cache - .plan("managed", desired, false) + .plan("managed", desired, false, true) .expect("prepare action after restore") .expect("cached action");