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