|
| 1 | +//! Shared routing pipeline for agent tunnel. |
| 2 | +//! |
| 3 | +//! Used by both connection forwarding (`fwd.rs`) and KDC proxy (`kdc_proxy.rs`) |
| 4 | +//! to ensure consistent routing behavior and error messages. |
| 5 | +
|
| 6 | +use std::net::IpAddr; |
| 7 | +use std::sync::Arc; |
| 8 | + |
| 9 | +use anyhow::{Result, anyhow}; |
| 10 | +use uuid::Uuid; |
| 11 | + |
| 12 | +use super::listener::AgentTunnelHandle; |
| 13 | +use super::registry::{AgentPeer, AgentRegistry}; |
| 14 | +use super::stream::TunnelStream; |
| 15 | + |
| 16 | +/// Result of the routing pipeline. |
| 17 | +/// |
| 18 | +/// Each variant carries enough context for the caller to produce an actionable error message. |
| 19 | +#[derive(Debug)] |
| 20 | +pub enum RoutingDecision { |
| 21 | + /// Route through these agent candidates (try in order, first success wins). |
| 22 | + ViaAgent(Vec<Arc<AgentPeer>>), |
| 23 | + /// Explicit agent_id was specified but not found in registry. |
| 24 | + ExplicitAgentNotFound(Uuid), |
| 25 | + /// No agent matched — caller should attempt direct connection. |
| 26 | + Direct, |
| 27 | +} |
| 28 | + |
| 29 | +/// Determines how to route a connection to the given target. |
| 30 | +/// |
| 31 | +/// Pipeline (in order of priority): |
| 32 | +/// 1. Explicit agent_id (from JWT) → route to that agent |
| 33 | +/// 2. IP target → subnet match against agent advertisements |
| 34 | +/// 3. Hostname target → domain suffix match (longest wins) |
| 35 | +/// 4. No match → direct connection |
| 36 | +pub fn resolve_route(registry: &AgentRegistry, explicit_agent_id: Option<Uuid>, target_host: &str) -> RoutingDecision { |
| 37 | + // Step 1: Explicit agent ID (from JWT) |
| 38 | + if let Some(agent_id) = explicit_agent_id { |
| 39 | + if let Some(agent) = registry.get(&agent_id) { |
| 40 | + return RoutingDecision::ViaAgent(vec![agent]); |
| 41 | + } |
| 42 | + return RoutingDecision::ExplicitAgentNotFound(agent_id); |
| 43 | + } |
| 44 | + |
| 45 | + // Step 2: Target is an IP address → subnet match |
| 46 | + if let Ok(ip) = target_host.parse::<IpAddr>() { |
| 47 | + let agents = registry.find_agents_for_target(ip); |
| 48 | + if !agents.is_empty() { |
| 49 | + return RoutingDecision::ViaAgent(agents); |
| 50 | + } |
| 51 | + return RoutingDecision::Direct; |
| 52 | + } |
| 53 | + |
| 54 | + // Step 3: Target is a hostname → domain suffix match (longest wins) |
| 55 | + let agents = registry.select_agents_for_domain(target_host); |
| 56 | + if !agents.is_empty() { |
| 57 | + return RoutingDecision::ViaAgent(agents); |
| 58 | + } |
| 59 | + |
| 60 | + // Step 4: No match → direct connect |
| 61 | + RoutingDecision::Direct |
| 62 | +} |
| 63 | + |
| 64 | +/// Try connecting to target through agent candidates (try-fail-retry). |
| 65 | +/// |
| 66 | +/// Returns the connected `TunnelStream` and the agent that succeeded. |
| 67 | +/// |
| 68 | +/// Callers must handle `RoutingDecision::ExplicitAgentNotFound` and |
| 69 | +/// `RoutingDecision::Direct` before calling this function. |
| 70 | +pub async fn route_and_connect( |
| 71 | + handle: &AgentTunnelHandle, |
| 72 | + candidates: &[Arc<AgentPeer>], |
| 73 | + session_id: Uuid, |
| 74 | + target: &str, |
| 75 | +) -> Result<(TunnelStream, Arc<AgentPeer>)> { |
| 76 | + assert!(!candidates.is_empty(), "route_and_connect called with empty candidates"); |
| 77 | + |
| 78 | + let mut last_error = None; |
| 79 | + |
| 80 | + for agent in candidates { |
| 81 | + info!( |
| 82 | + agent_id = %agent.agent_id, |
| 83 | + agent_name = %agent.name, |
| 84 | + %target, |
| 85 | + "Routing via agent tunnel" |
| 86 | + ); |
| 87 | + |
| 88 | + match handle.connect_via_agent(agent.agent_id, session_id, target).await { |
| 89 | + Ok(stream) => { |
| 90 | + info!( |
| 91 | + agent_id = %agent.agent_id, |
| 92 | + agent_name = %agent.name, |
| 93 | + %target, |
| 94 | + "Agent tunnel connection established" |
| 95 | + ); |
| 96 | + return Ok((stream, Arc::clone(agent))); |
| 97 | + } |
| 98 | + Err(error) => { |
| 99 | + warn!( |
| 100 | + agent_id = %agent.agent_id, |
| 101 | + agent_name = %agent.name, |
| 102 | + %target, |
| 103 | + error = format!("{error:#}"), |
| 104 | + "Agent tunnel connection failed, trying next candidate" |
| 105 | + ); |
| 106 | + last_error = Some(error); |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + let agent_names: Vec<&str> = candidates.iter().map(|a| a.name.as_str()).collect(); |
| 112 | + let last_err_msg = last_error.as_ref().map(|e| format!("{e:#}")).unwrap_or_default(); |
| 113 | + |
| 114 | + error!( |
| 115 | + agent_count = candidates.len(), |
| 116 | + %target, |
| 117 | + agents = ?agent_names, |
| 118 | + last_error = %last_err_msg, |
| 119 | + "All agent tunnel candidates failed" |
| 120 | + ); |
| 121 | + |
| 122 | + Err(last_error.unwrap_or_else(|| { |
| 123 | + anyhow!( |
| 124 | + "All {} agents matching target '{}' failed to connect. Agents tried: [{}]", |
| 125 | + candidates.len(), |
| 126 | + target, |
| 127 | + agent_names.join(", "), |
| 128 | + ) |
| 129 | + })) |
| 130 | +} |
| 131 | + |
| 132 | +#[cfg(test)] |
| 133 | +mod tests { |
| 134 | + use std::sync::atomic::Ordering; |
| 135 | + |
| 136 | + use agent_tunnel_proto::DomainAdvertisement; |
| 137 | + |
| 138 | + use super::*; |
| 139 | + use crate::agent_tunnel::registry::AgentPeer; |
| 140 | + |
| 141 | + fn make_peer(name: &str) -> Arc<AgentPeer> { |
| 142 | + Arc::new(AgentPeer::new( |
| 143 | + Uuid::new_v4(), |
| 144 | + name.to_owned(), |
| 145 | + "sha256:test".to_owned(), |
| 146 | + )) |
| 147 | + } |
| 148 | + |
| 149 | + fn domain(name: &str) -> DomainAdvertisement { |
| 150 | + DomainAdvertisement { |
| 151 | + domain: name.to_owned(), |
| 152 | + auto_detected: false, |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + #[test] |
| 157 | + fn route_explicit_agent_id() { |
| 158 | + let registry = AgentRegistry::new(); |
| 159 | + let peer = make_peer("agent-a"); |
| 160 | + let agent_id = peer.agent_id; |
| 161 | + registry.register(Arc::clone(&peer)); |
| 162 | + |
| 163 | + match resolve_route(®istry, Some(agent_id), "anything") { |
| 164 | + RoutingDecision::ViaAgent(agents) => { |
| 165 | + assert_eq!(agents.len(), 1); |
| 166 | + assert_eq!(agents[0].agent_id, agent_id); |
| 167 | + } |
| 168 | + other => panic!("expected ViaAgent, got {other:?}"), |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + #[test] |
| 173 | + fn route_explicit_agent_id_not_found() { |
| 174 | + let registry = AgentRegistry::new(); |
| 175 | + let bogus_id = Uuid::new_v4(); |
| 176 | + |
| 177 | + match resolve_route(®istry, Some(bogus_id), "anything") { |
| 178 | + RoutingDecision::ExplicitAgentNotFound(id) => { |
| 179 | + assert_eq!(id, bogus_id); |
| 180 | + } |
| 181 | + other => panic!("expected ExplicitAgentNotFound, got {other:?}"), |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + #[test] |
| 186 | + fn route_ip_target_via_subnet() { |
| 187 | + let registry = AgentRegistry::new(); |
| 188 | + let peer = make_peer("agent-a"); |
| 189 | + let agent_id = peer.agent_id; |
| 190 | + let subnet: ipnetwork::Ipv4Network = "10.1.0.0/16".parse().expect("valid test subnet"); |
| 191 | + peer.update_routes(1, vec![subnet], vec![]); |
| 192 | + registry.register(peer); |
| 193 | + |
| 194 | + match resolve_route(®istry, None, "10.1.5.50") { |
| 195 | + RoutingDecision::ViaAgent(agents) => { |
| 196 | + assert_eq!(agents[0].agent_id, agent_id); |
| 197 | + } |
| 198 | + other => panic!("expected ViaAgent, got {other:?}"), |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + #[test] |
| 203 | + fn route_hostname_via_domain() { |
| 204 | + let registry = AgentRegistry::new(); |
| 205 | + let peer = make_peer("agent-a"); |
| 206 | + let agent_id = peer.agent_id; |
| 207 | + let subnet: ipnetwork::Ipv4Network = "10.1.0.0/16".parse().expect("valid test subnet"); |
| 208 | + peer.update_routes(1, vec![subnet], vec![domain("contoso.local")]); |
| 209 | + registry.register(peer); |
| 210 | + |
| 211 | + match resolve_route(®istry, None, "dc01.contoso.local") { |
| 212 | + RoutingDecision::ViaAgent(agents) => { |
| 213 | + assert_eq!(agents[0].agent_id, agent_id); |
| 214 | + } |
| 215 | + other => panic!("expected ViaAgent, got {other:?}"), |
| 216 | + } |
| 217 | + } |
| 218 | + |
| 219 | + #[test] |
| 220 | + fn route_no_match_returns_direct() { |
| 221 | + let registry = AgentRegistry::new(); |
| 222 | + let peer = make_peer("agent-a"); |
| 223 | + let subnet: ipnetwork::Ipv4Network = "10.1.0.0/16".parse().expect("valid test subnet"); |
| 224 | + peer.update_routes(1, vec![subnet], vec![domain("contoso.local")]); |
| 225 | + registry.register(peer); |
| 226 | + |
| 227 | + assert!(matches!( |
| 228 | + resolve_route(®istry, None, "external.example.com"), |
| 229 | + RoutingDecision::Direct |
| 230 | + )); |
| 231 | + } |
| 232 | + |
| 233 | + #[test] |
| 234 | + fn route_ip_no_match_returns_direct() { |
| 235 | + let registry = AgentRegistry::new(); |
| 236 | + let peer = make_peer("agent-a"); |
| 237 | + let subnet: ipnetwork::Ipv4Network = "10.1.0.0/16".parse().expect("valid test subnet"); |
| 238 | + peer.update_routes(1, vec![subnet], vec![]); |
| 239 | + registry.register(peer); |
| 240 | + |
| 241 | + assert!(matches!( |
| 242 | + resolve_route(®istry, None, "192.168.1.1"), |
| 243 | + RoutingDecision::Direct |
| 244 | + )); |
| 245 | + } |
| 246 | + |
| 247 | + #[test] |
| 248 | + fn route_skips_offline_agents() { |
| 249 | + let registry = AgentRegistry::new(); |
| 250 | + let peer = make_peer("offline-agent"); |
| 251 | + let subnet: ipnetwork::Ipv4Network = "10.1.0.0/16".parse().expect("valid test subnet"); |
| 252 | + peer.update_routes(1, vec![subnet], vec![domain("contoso.local")]); |
| 253 | + peer.last_seen.store(0, Ordering::Release); |
| 254 | + registry.register(peer); |
| 255 | + |
| 256 | + assert!(matches!( |
| 257 | + resolve_route(®istry, None, "dc01.contoso.local"), |
| 258 | + RoutingDecision::Direct |
| 259 | + )); |
| 260 | + } |
| 261 | + |
| 262 | + #[test] |
| 263 | + fn route_domain_match_returns_multiple_agents_ordered() { |
| 264 | + let registry = AgentRegistry::new(); |
| 265 | + |
| 266 | + let peer_a = make_peer("agent-a"); |
| 267 | + let subnet_a: ipnetwork::Ipv4Network = "10.1.0.0/16".parse().expect("valid test subnet"); |
| 268 | + peer_a.update_routes(1, vec![subnet_a], vec![domain("contoso.local")]); |
| 269 | + registry.register(Arc::clone(&peer_a)); |
| 270 | + |
| 271 | + std::thread::sleep(std::time::Duration::from_millis(10)); |
| 272 | + |
| 273 | + let peer_b = make_peer("agent-b"); |
| 274 | + let id_b = peer_b.agent_id; |
| 275 | + let subnet_b: ipnetwork::Ipv4Network = "10.2.0.0/16".parse().expect("valid test subnet"); |
| 276 | + peer_b.update_routes(1, vec![subnet_b], vec![domain("contoso.local")]); |
| 277 | + registry.register(Arc::clone(&peer_b)); |
| 278 | + |
| 279 | + match resolve_route(®istry, None, "dc01.contoso.local") { |
| 280 | + RoutingDecision::ViaAgent(agents) => { |
| 281 | + assert_eq!(agents.len(), 2); |
| 282 | + assert_eq!(agents[0].agent_id, id_b, "most recent first"); |
| 283 | + } |
| 284 | + other => panic!("expected ViaAgent, got {other:?}"), |
| 285 | + } |
| 286 | + } |
| 287 | +} |
0 commit comments