|
| 1 | +//! Shared routing pipeline for agent tunnel. |
| 2 | +//! |
| 3 | +//! Consumed by the upstream connection paths (forwarding, RDP clean path, |
| 4 | +//! generic client) to ensure consistent routing behavior and error messages. |
| 5 | +
|
| 6 | +use std::net::IpAddr; |
| 7 | +use std::sync::Arc; |
| 8 | + |
| 9 | +use agent_tunnel_proto::DomainName; |
| 10 | +use anyhow::{Result, anyhow}; |
| 11 | +use uuid::Uuid; |
| 12 | + |
| 13 | +use super::listener::AgentTunnelHandle; |
| 14 | +use super::registry::{AgentPeer, AgentRegistry}; |
| 15 | +use super::stream::TunnelStream; |
| 16 | + |
| 17 | +/// A parsed target host used for route matching. |
| 18 | +/// |
| 19 | +/// Routing cares only about the host identity, not the port or scheme used by |
| 20 | +/// the eventual connection attempt. |
| 21 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 22 | +pub enum RouteTarget { |
| 23 | + Ip(IpAddr), |
| 24 | + Hostname(DomainName), |
| 25 | +} |
| 26 | + |
| 27 | +impl RouteTarget { |
| 28 | + pub fn ip(ip: IpAddr) -> Self { |
| 29 | + Self::Ip(ip) |
| 30 | + } |
| 31 | + |
| 32 | + pub fn hostname(hostname: impl Into<String>) -> Self { |
| 33 | + Self::Hostname(DomainName::new(hostname)) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl std::fmt::Display for RouteTarget { |
| 38 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 39 | + match self { |
| 40 | + Self::Ip(ip) => ip.fmt(f), |
| 41 | + Self::Hostname(hostname) => hostname.fmt(f), |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/// Result of the routing pipeline. |
| 47 | +/// |
| 48 | +/// Each variant carries enough context for the caller to produce an actionable error message. |
| 49 | +#[derive(Debug)] |
| 50 | +pub enum RoutingDecision { |
| 51 | + /// Route through these agent candidates (try in order, first success wins). |
| 52 | + ViaAgent(Vec<Arc<AgentPeer>>), |
| 53 | + /// Explicit agent_id was specified but not found in registry. |
| 54 | + ExplicitAgentNotFound(Uuid), |
| 55 | + /// No agent matched — caller should attempt direct connection. |
| 56 | + Direct, |
| 57 | +} |
| 58 | + |
| 59 | +/// Determines how to route a connection to the given target. |
| 60 | +/// |
| 61 | +/// Pipeline (in order of priority): |
| 62 | +/// 1. Explicit agent_id (from JWT) → route to that agent |
| 63 | +/// 2. Target match (IP subnet or domain suffix) → best match wins |
| 64 | +/// 3. No match → direct connection |
| 65 | +pub async fn resolve_route( |
| 66 | + registry: &AgentRegistry, |
| 67 | + explicit_agent_id: Option<Uuid>, |
| 68 | + target: &RouteTarget, |
| 69 | +) -> RoutingDecision { |
| 70 | + // Step 1: Explicit agent ID (from JWT) |
| 71 | + if let Some(id) = explicit_agent_id { |
| 72 | + return match registry.get(&id).await { |
| 73 | + Some(agent) => RoutingDecision::ViaAgent(vec![agent]), |
| 74 | + None => RoutingDecision::ExplicitAgentNotFound(id), |
| 75 | + }; |
| 76 | + } |
| 77 | + |
| 78 | + // Step 2: Match target against all agents (IP subnet or domain suffix) |
| 79 | + let agents = registry.find_agents_for(target).await; |
| 80 | + |
| 81 | + if agents.is_empty() { |
| 82 | + RoutingDecision::Direct |
| 83 | + } else { |
| 84 | + RoutingDecision::ViaAgent(agents) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +/// Attempt to route a connection via the agent tunnel. |
| 89 | +/// |
| 90 | +/// Returns `Ok(Some(stream))` if routed through an agent, `Ok(None)` if the caller |
| 91 | +/// should fall through to direct connect, or `Err` if an explicit agent was specified |
| 92 | +/// but not found (or all candidates failed). |
| 93 | +pub async fn try_route( |
| 94 | + handle: Option<&AgentTunnelHandle>, |
| 95 | + explicit_agent_id: Option<Uuid>, |
| 96 | + target: &RouteTarget, |
| 97 | + session_id: Uuid, |
| 98 | + target_addr: &str, |
| 99 | +) -> Result<Option<(TunnelStream, Arc<AgentPeer>)>> { |
| 100 | + let Some(handle) = handle else { |
| 101 | + // An explicit `jet_agent_id` claim means the token requires routing via that |
| 102 | + // specific agent; silently falling back to a direct connect would bypass the |
| 103 | + // intended network boundary. Reject instead. |
| 104 | + return match explicit_agent_id { |
| 105 | + Some(id) => Err(anyhow!( |
| 106 | + "agent {id} specified in token requires agent tunnel routing, but no tunnel handle is configured" |
| 107 | + )), |
| 108 | + None => Ok(None), |
| 109 | + }; |
| 110 | + }; |
| 111 | + |
| 112 | + match resolve_route(handle.registry(), explicit_agent_id, target).await { |
| 113 | + RoutingDecision::ExplicitAgentNotFound(id) => { |
| 114 | + Err(anyhow!("agent {id} specified in token not found in registry")) |
| 115 | + } |
| 116 | + RoutingDecision::Direct => Ok(None), |
| 117 | + RoutingDecision::ViaAgent(candidates) => { |
| 118 | + let result = route_and_connect(handle, &candidates, session_id, target_addr).await?; |
| 119 | + Ok(Some(result)) |
| 120 | + } |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +/// Try connecting to target through agent candidates (try-fail-retry). |
| 125 | +/// |
| 126 | +/// Returns the connected `TunnelStream` and the agent that succeeded. |
| 127 | +/// |
| 128 | +/// Callers must handle `RoutingDecision::ExplicitAgentNotFound` and |
| 129 | +/// `RoutingDecision::Direct` before calling this function. |
| 130 | +pub async fn route_and_connect( |
| 131 | + handle: &AgentTunnelHandle, |
| 132 | + candidates: &[Arc<AgentPeer>], |
| 133 | + session_id: Uuid, |
| 134 | + target: &str, |
| 135 | +) -> Result<(TunnelStream, Arc<AgentPeer>)> { |
| 136 | + if candidates.is_empty() { |
| 137 | + return Err(anyhow!("route_and_connect called with empty candidates")); |
| 138 | + } |
| 139 | + |
| 140 | + let mut last_error = None; |
| 141 | + |
| 142 | + for agent in candidates { |
| 143 | + info!( |
| 144 | + agent_id = %agent.agent_id, |
| 145 | + agent_name = %agent.name, |
| 146 | + %target, |
| 147 | + "Routing via agent tunnel" |
| 148 | + ); |
| 149 | + |
| 150 | + match handle.connect_via_agent(agent.agent_id, session_id, target).await { |
| 151 | + Ok(stream) => { |
| 152 | + info!( |
| 153 | + agent_id = %agent.agent_id, |
| 154 | + agent_name = %agent.name, |
| 155 | + %target, |
| 156 | + "Agent tunnel connection established" |
| 157 | + ); |
| 158 | + return Ok((stream, Arc::clone(agent))); |
| 159 | + } |
| 160 | + Err(error) => { |
| 161 | + warn!( |
| 162 | + agent_id = %agent.agent_id, |
| 163 | + agent_name = %agent.name, |
| 164 | + %target, |
| 165 | + error = format!("{error:#}"), |
| 166 | + "Agent tunnel connection failed, trying next candidate" |
| 167 | + ); |
| 168 | + last_error = Some(error); |
| 169 | + } |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + let agent_names: Vec<&str> = candidates.iter().map(|a| a.name.as_str()).collect(); |
| 174 | + let last_err_msg = last_error.as_ref().map(|e| format!("{e:#}")).unwrap_or_default(); |
| 175 | + |
| 176 | + error!( |
| 177 | + agent_count = candidates.len(), |
| 178 | + %target, |
| 179 | + agents = ?agent_names, |
| 180 | + last_error = %last_err_msg, |
| 181 | + "All agent tunnel candidates failed" |
| 182 | + ); |
| 183 | + |
| 184 | + Err(last_error.unwrap_or_else(|| { |
| 185 | + anyhow!( |
| 186 | + "All {} agents matching target '{}' failed to connect. Agents tried: [{}]", |
| 187 | + candidates.len(), |
| 188 | + target, |
| 189 | + agent_names.join(", "), |
| 190 | + ) |
| 191 | + })) |
| 192 | +} |
0 commit comments