1use relay_core_api::flow::{BodyData, Direction, Flow, FlowUpdate, Layer, WebSocketMessage};
24use relay_core_api::policy::{ProxyPolicy, ProxyPolicyPatch, RedactionPolicy};
25#[cfg(all(target_os = "linux", feature = "transparent-linux"))]
26use relay_core_lib::capture::LinuxOriginalDstProvider;
27#[cfg(all(target_os = "macos", feature = "transparent-macos"))]
28use relay_core_lib::capture::MacOsOriginalDstProvider;
29#[cfg(target_os = "windows")]
30use relay_core_lib::capture::WindowsOriginalDstProvider;
31use relay_core_lib::capture::udp::UdpProxy;
32use relay_core_lib::capture::{OriginalDstProvider, TcpCaptureSource, TransparentTcpCaptureSource};
33use relay_core_lib::interceptor::{CompositeInterceptor, Interceptor};
34use relay_core_lib::tls::CertificateAuthority;
35#[cfg(feature = "script")]
36use relay_core_script::ScriptInterceptor;
37use std::collections::{BTreeSet, HashSet, VecDeque};
38use std::net::SocketAddr;
39use std::sync::Arc;
40use std::sync::Mutex;
41use std::sync::atomic::{AtomicUsize, Ordering};
42use std::time::{SystemTime, UNIX_EPOCH};
43use tokio::net::TcpListener;
44use tokio::sync::{broadcast, mpsc, oneshot, watch};
45
46use tracing::error;
47
48use crate::audit::{AuditActor, AuditEvent, AuditEventKind, AuditOutcome};
49use crate::rule::{
50 InterceptRule, InterceptRuleConfig, MockResponseRuleConfig, build_intercept_rules,
51 build_mock_response_rule,
52};
53use relay_core_api::modification::{FlowQuery, FlowSummary};
54use relay_core_lib::rule::Rule;
55use relay_core_lib::rule::engine::RuleEngine;
56use relay_core_storage::store::{AuditEventRecord, Store};
57use serde_json::json;
58
59pub mod actors;
60pub mod audit;
61pub mod interceptors;
62pub mod modification;
63pub mod rule;
64pub mod services;
65
66pub use relay_core_api::{flow, policy};
69pub use relay_core_lib::InterceptionResult;
70pub use relay_core_lib::rule as lib_rule;
71
72use actors::flow_store::{FlowStoreActor, FlowStoreMessage};
73use actors::intercept_broker::{InterceptBrokerActor, InterceptBrokerMessage};
74use actors::rule_store::{RuleStoreActor, RuleStoreMessage};
75
76pub mod rule_engine {
77 pub use relay_core_lib::rule_engine::*;
78}
79
80#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
81pub struct CoreMetrics {
82 pub flows_total: usize,
83 pub flows_in_memory: usize,
84 pub flows_dropped: usize,
85 pub intercepts_pending: usize,
86 pub ws_pending_messages: usize,
87 pub oldest_intercept_age_ms: Option<u64>,
88 pub oldest_ws_message_age_ms: Option<u64>,
89 pub rule_exec_errors: usize,
90 pub audit_events_total: usize,
91 pub audit_events_failed: usize,
92 pub flow_events_lagged_total: usize,
93 pub audit_events_lagged_total: usize,
94}
95
96impl CoreMetrics {
97 pub fn to_prometheus_text(&self) -> String {
98 let oldest_intercept_age_ms = self.oldest_intercept_age_ms.unwrap_or(0);
99 let oldest_ws_message_age_ms = self.oldest_ws_message_age_ms.unwrap_or(0);
100 format!(
101 "relay_core_flows_total {}\n\
102relay_core_flows_in_memory {}\n\
103relay_core_flows_dropped_total {}\n\
104relay_core_intercepts_pending {}\n\
105relay_core_ws_pending_messages {}\n\
106relay_core_oldest_intercept_age_ms {}\n\
107relay_core_oldest_ws_message_age_ms {}\n\
108relay_core_rule_exec_errors_total {}\n\
109relay_core_audit_events_total {}\n\
110relay_core_audit_events_failed_total {}\n\
111relay_core_flow_events_lagged_total {}\n\
112relay_core_audit_events_lagged_total {}\n",
113 self.flows_total,
114 self.flows_in_memory,
115 self.flows_dropped,
116 self.intercepts_pending,
117 self.ws_pending_messages,
118 oldest_intercept_age_ms,
119 oldest_ws_message_age_ms,
120 self.rule_exec_errors,
121 self.audit_events_total,
122 self.audit_events_failed,
123 self.flow_events_lagged_total,
124 self.audit_events_lagged_total,
125 )
126 }
127}
128
129#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
130pub struct CoreStatusSnapshot {
131 pub phase: RuntimeLifecyclePhase,
132 pub running: bool,
133 pub port: Option<u16>,
134 pub uptime: Option<u64>,
135 pub last_error: Option<String>,
136}
137
138#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
139pub struct CoreStatusReport {
140 pub status: CoreStatusSnapshot,
141 pub metrics: CoreMetrics,
142}
143
144#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
145pub struct CoreInterceptSnapshot {
146 pub pending_count: usize,
147 pub ws_pending_count: usize,
148}
149
150#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
151pub struct CoreAuditSnapshot {
152 pub events: Vec<AuditEvent>,
153}
154
155#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
156pub struct CoreAuditQuery {
157 pub since_ms: Option<u64>,
158 pub until_ms: Option<u64>,
159 pub actor: Option<AuditActor>,
160 pub kind: Option<AuditEventKind>,
161 pub outcome: Option<AuditOutcome>,
162 pub limit: usize,
163}
164
165impl Default for CoreAuditQuery {
166 fn default() -> Self {
167 Self {
168 since_ms: None,
169 until_ms: None,
170 actor: None,
171 kind: None,
172 outcome: None,
173 limit: 50,
174 }
175 }
176}
177
178#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
179#[serde(rename_all = "snake_case")]
180pub enum RuntimeLifecyclePhase {
181 Created,
182 Starting,
183 Running,
184 Stopping,
185 Stopped,
186 Failed,
187}
188
189impl RuntimeLifecyclePhase {
190 pub fn as_str(&self) -> &'static str {
191 match self {
192 Self::Created => "created",
193 Self::Starting => "starting",
194 Self::Running => "running",
195 Self::Stopping => "stopping",
196 Self::Stopped => "stopped",
197 Self::Failed => "failed",
198 }
199 }
200
201 pub fn is_active(&self) -> bool {
202 matches!(self, Self::Starting | Self::Running | Self::Stopping)
203 }
204}
205
206#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
207pub struct RuntimeLifecycle {
208 pub phase: RuntimeLifecyclePhase,
209 pub port: Option<u16>,
210 pub started_at_ms: Option<u64>,
211 pub last_error: Option<String>,
212}
213
214impl RuntimeLifecycle {
215 pub fn created() -> Self {
216 Self {
217 phase: RuntimeLifecyclePhase::Created,
218 port: None,
219 started_at_ms: None,
220 last_error: None,
221 }
222 }
223
224 pub fn is_active(&self) -> bool {
225 self.phase.is_active()
226 }
227
228 pub fn uptime_seconds(&self) -> Option<u64> {
229 let started_at_ms = self.started_at_ms?;
230 let now_ms = now_unix_ms();
231 Some(now_ms.saturating_sub(started_at_ms) / 1_000)
232 }
233}
234
235pub enum ProxySpawnResult {
236 Started(tokio::task::JoinHandle<()>),
237 AlreadyRunning,
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub enum ProxyStopResult {
242 Stopping,
243 NotRunning,
244}
245
246impl From<RuntimeLifecycle> for CoreStatusSnapshot {
247 fn from(lifecycle: RuntimeLifecycle) -> Self {
248 Self {
249 running: lifecycle.is_active(),
250 uptime: lifecycle.uptime_seconds(),
251 port: lifecycle.port,
252 last_error: lifecycle.last_error,
253 phase: lifecycle.phase,
254 }
255 }
256}
257
258pub struct CoreState {
259 flow_store: mpsc::Sender<FlowStoreMessage>,
260 intercept_broker: mpsc::Sender<InterceptBrokerMessage>,
261 rule_store: mpsc::Sender<RuleStoreMessage>,
262 store: Option<Store>,
263 #[cfg(feature = "script")]
264 pub script_interceptor: Arc<ScriptInterceptor>,
265 pub policy_tx: watch::Sender<ProxyPolicy>,
266 pub flows_dropped: Arc<AtomicUsize>,
267 audit_events_total: Arc<AtomicUsize>,
268 audit_events_failed: Arc<AtomicUsize>,
269 flow_events_lagged_total: Arc<AtomicUsize>,
270 audit_events_lagged_total: Arc<AtomicUsize>,
271 flow_broadcast_tx: broadcast::Sender<FlowUpdate>,
273 audit_broadcast_tx: broadcast::Sender<AuditEvent>,
274 audit_history: Arc<Mutex<VecDeque<AuditEvent>>>,
275 lifecycle_tx: watch::Sender<RuntimeLifecycle>,
276 shutdown_tx: Mutex<Option<oneshot::Sender<()>>>,
277}
278
279impl CoreState {
280 pub async fn new(db_url: Option<String>) -> Self {
281 const AUDIT_HISTORY_LIMIT: usize = 200;
282
283 let store = if let Some(url) = db_url {
284 match Store::connect(&url).await {
285 Ok(s) => {
286 if let Err(e) = s.init().await {
287 tracing::error!("Failed to init store: {}", e);
288 }
289 Some(s)
290 }
291 Err(e) => {
292 tracing::error!("Failed to connect to store: {}", e);
293 None
294 }
295 }
296 } else {
297 None
298 };
299
300 let (flow_tx, flow_rx) = mpsc::channel(10000);
301 let flow_actor = FlowStoreActor::new(flow_rx, store.clone());
302 tokio::spawn(flow_actor.run());
303
304 let (intercept_tx, intercept_rx) = mpsc::channel(1000);
305 let intercept_actor = InterceptBrokerActor::new(intercept_rx);
306 tokio::spawn(intercept_actor.run());
307
308 let (rule_tx, rule_rx) = mpsc::channel(100);
309 let rule_actor = RuleStoreActor::new(rule_rx, store.clone());
310 tokio::spawn(rule_actor.run());
311
312 let (policy_tx, _) = watch::channel(ProxyPolicy::default());
313 let (flow_broadcast_tx, _) = broadcast::channel(1000);
314 let (audit_broadcast_tx, _) = broadcast::channel(256);
315 let (lifecycle_tx, _) = watch::channel(RuntimeLifecycle::created());
316
317 #[cfg(feature = "script")]
318 let script_interceptor = ScriptInterceptor::new()
319 .await
320 .expect("Failed to initialize ScriptInterceptor");
321 Self {
322 flow_store: flow_tx,
323 intercept_broker: intercept_tx,
324 rule_store: rule_tx,
325 store,
326 #[cfg(feature = "script")]
327 script_interceptor: Arc::new(script_interceptor),
328 policy_tx,
329 flows_dropped: Arc::new(AtomicUsize::new(0)),
330 audit_events_total: Arc::new(AtomicUsize::new(0)),
331 audit_events_failed: Arc::new(AtomicUsize::new(0)),
332 flow_events_lagged_total: Arc::new(AtomicUsize::new(0)),
333 audit_events_lagged_total: Arc::new(AtomicUsize::new(0)),
334 flow_broadcast_tx,
335 audit_broadcast_tx,
336 audit_history: Arc::new(Mutex::new(VecDeque::with_capacity(AUDIT_HISTORY_LIMIT))),
337 lifecycle_tx,
338 shutdown_tx: Mutex::new(None),
339 }
340 }
341
342 pub async fn get_metrics(&self) -> CoreMetrics {
343 let (flow_tx, flow_rx) = oneshot::channel();
344 let _ = self
345 .flow_store
346 .send(FlowStoreMessage::GetMetrics(flow_tx))
347 .await;
348 let (flows_total, flows_in_memory) = flow_rx.await.unwrap_or((0, 0));
349
350 let (int_tx, int_rx) = oneshot::channel();
351 let _ = self
352 .intercept_broker
353 .send(InterceptBrokerMessage::GetMetrics { respond_to: int_tx })
354 .await;
355 let (
356 intercepts_pending,
357 ws_pending_messages,
358 oldest_intercept_age_ms,
359 oldest_ws_message_age_ms,
360 ) = int_rx.await.unwrap_or((0, 0, None, None));
361
362 let (rule_tx, rule_rx) = oneshot::channel();
363 let _ = self
364 .rule_store
365 .send(RuleStoreMessage::GetMetrics(rule_tx))
366 .await;
367 let rule_exec_errors = rule_rx.await.unwrap_or(0);
368
369 CoreMetrics {
370 flows_total,
371 flows_in_memory,
372 flows_dropped: self.flows_dropped.load(Ordering::Relaxed),
373 intercepts_pending,
374 ws_pending_messages,
375 oldest_intercept_age_ms,
376 oldest_ws_message_age_ms,
377 rule_exec_errors,
378 audit_events_total: self.audit_events_total.load(Ordering::Relaxed),
379 audit_events_failed: self.audit_events_failed.load(Ordering::Relaxed),
380 flow_events_lagged_total: self.flow_events_lagged_total.load(Ordering::Relaxed),
381 audit_events_lagged_total: self.audit_events_lagged_total.load(Ordering::Relaxed),
382 }
383 }
384
385 pub async fn get_metrics_prometheus_text(&self) -> String {
386 let mut text = self.get_metrics().await.to_prometheus_text();
387 #[cfg(feature = "script")]
388 {
389 text.push_str(&self.script_interceptor.metrics.prometheus_lines());
390 }
391 text
392 }
393
394 pub fn status_snapshot(&self) -> CoreStatusSnapshot {
395 self.lifecycle().into()
396 }
397
398 pub async fn status_report(&self) -> CoreStatusReport {
399 CoreStatusReport {
400 status: self.status_snapshot(),
401 metrics: self.get_metrics().await,
402 }
403 }
404
405 pub async fn intercept_snapshot(&self) -> CoreInterceptSnapshot {
406 let metrics = self.get_metrics().await;
407 CoreInterceptSnapshot {
408 pending_count: metrics.intercepts_pending,
409 ws_pending_count: metrics.ws_pending_messages,
410 }
411 }
412
413 pub fn audit_snapshot(&self, limit: usize) -> CoreAuditSnapshot {
414 let events = self.recent_audit_events();
415 let start = events.len().saturating_sub(limit);
416 CoreAuditSnapshot {
417 events: events.into_iter().skip(start).collect(),
418 }
419 }
420
421 pub async fn query_audit_snapshot(&self, query: CoreAuditQuery) -> CoreAuditSnapshot {
422 let limit = query.limit.clamp(1, 500);
423 if let Some(store) = &self.store {
424 let rows = store
425 .query_audit_events(
426 query.since_ms,
427 query.until_ms,
428 query.actor.as_ref().map(AuditActor::as_str),
429 query.kind.as_ref().map(AuditEventKind::as_str),
430 query.outcome.as_ref().map(AuditOutcome::as_str),
431 limit,
432 )
433 .await
434 .unwrap_or_default();
435
436 let mut events = Vec::with_capacity(rows.len());
437 for row in rows {
438 if let Ok(event) = serde_json::from_value::<AuditEvent>(row) {
439 events.push(event);
440 }
441 }
442 return CoreAuditSnapshot { events };
443 }
444
445 let mut events = self.recent_audit_events();
446 events.reverse();
447 let filtered = events
448 .into_iter()
449 .filter(|event| {
450 query
451 .since_ms
452 .map(|v| event.timestamp_ms >= v)
453 .unwrap_or(true)
454 })
455 .filter(|event| {
456 query
457 .until_ms
458 .map(|v| event.timestamp_ms <= v)
459 .unwrap_or(true)
460 })
461 .filter(|event| {
462 query
463 .actor
464 .as_ref()
465 .map(|v| &event.actor == v)
466 .unwrap_or(true)
467 })
468 .filter(|event| {
469 query
470 .kind
471 .as_ref()
472 .map(|v| &event.kind == v)
473 .unwrap_or(true)
474 })
475 .filter(|event| {
476 query
477 .outcome
478 .as_ref()
479 .map(|v| &event.outcome == v)
480 .unwrap_or(true)
481 })
482 .take(limit)
483 .collect();
484 CoreAuditSnapshot { events: filtered }
485 }
486
487 pub async fn get_flow(&self, id: String) -> Option<Flow> {
488 let (tx, rx) = oneshot::channel();
489 if let Err(e) = self
490 .flow_store
491 .send(FlowStoreMessage::GetFlow {
492 id: id.clone(),
493 respond_to: tx,
494 })
495 .await
496 {
497 error!("Failed to send GetFlow request: {}", e);
498 if let Some(store) = &self.store {
499 return store
500 .load_flow(&id)
501 .await
502 .ok()
503 .flatten()
504 .and_then(|value| serde_json::from_value::<Flow>(value).ok());
505 }
506 return None;
507 }
508 let flow = rx
509 .await
510 .map_err(|e| {
511 error!("Failed to receive Flow response: {}", e);
512 e
513 })
514 .unwrap_or(None);
515 if let Some(flow) = flow {
516 return Some(redact_flow(flow, &self.current_redaction_policy()));
517 }
518 if let Some(store) = &self.store {
519 return store
520 .load_flow(&id)
521 .await
522 .ok()
523 .flatten()
524 .and_then(|value| serde_json::from_value::<Flow>(value).ok())
525 .map(|flow| redact_flow(flow, &self.current_redaction_policy()));
526 }
527 None
528 }
529
530 pub async fn get_rules(&self) -> Vec<Rule> {
531 let (tx, rx) = oneshot::channel();
532 if let Err(e) = self.rule_store.send(RuleStoreMessage::GetRules(tx)).await {
533 error!("Failed to send GetRules request: {}", e);
534 return Vec::new();
535 }
536 rx.await
537 .map_err(|e| {
538 error!("Failed to receive Rules response: {}", e);
539 e
540 })
541 .unwrap_or_default()
542 }
543
544 pub async fn set_rules(&self, rules: Vec<Rule>) {
545 let _ = self
546 .set_rules_from(
547 AuditActor::Runtime,
548 "rules.replace",
549 "rule_set".to_string(),
550 json!({}),
551 rules,
552 )
553 .await;
554 }
555
556 pub async fn upsert_rule_from(
557 &self,
558 actor: AuditActor,
559 operation: &str,
560 target: String,
561 details: serde_json::Value,
562 rule: Rule,
563 ) -> Result<(), String> {
564 let rule_id = rule.id.clone();
565 let mut rules = self.get_rules().await;
566 rules.retain(|existing| existing.id != rule_id);
567 rules.push(rule);
568 self.set_rules_from(actor, operation, target, details, rules)
569 .await
570 }
571
572 pub async fn delete_rule_from(
573 &self,
574 actor: AuditActor,
575 operation: &str,
576 target: String,
577 details: serde_json::Value,
578 rule_id: &str,
579 ) -> Result<bool, String> {
580 let mut rules = self.get_rules().await;
581 let before = rules.len();
582 rules.retain(|rule| rule.id != rule_id);
583 if rules.len() == before {
584 return Ok(false);
585 }
586 self.set_rules_from(actor, operation, target, details, rules)
587 .await
588 .map(|_| true)
589 }
590
591 pub async fn create_mock_response_rule_from(
592 &self,
593 actor: AuditActor,
594 target: String,
595 details: serde_json::Value,
596 config: MockResponseRuleConfig,
597 ) -> Result<String, String> {
598 let rule_id = config.rule_id.clone();
599 let rule = build_mock_response_rule(config);
600 self.upsert_rule_from(actor, "rule.mock_create", target, details, rule)
601 .await
602 .map(|_| rule_id)
603 }
604
605 pub async fn create_intercept_rule_from(
606 &self,
607 actor: AuditActor,
608 target: String,
609 details: serde_json::Value,
610 config: InterceptRuleConfig,
611 ) -> Result<String, String> {
612 let rule_id = config.rule_id.clone();
613 let mut rules = self.get_rules().await;
614 rules.extend(build_intercept_rules(config));
615 self.set_rules_from(actor, "rule.intercept_create", target, details, rules)
616 .await
617 .map(|_| rule_id)
618 }
619
620 pub async fn upsert_legacy_intercept_rule_from(
621 &self,
622 actor: AuditActor,
623 target: String,
624 details: serde_json::Value,
625 rule: InterceptRule,
626 ) -> Result<(), String> {
627 let rule_id = rule.id.clone();
628 let mut rules = self.get_rules().await;
629 rules.retain(|existing| {
630 existing.id != rule_id && !existing.id.starts_with(&format!("{}-", rule_id))
631 });
632 rules.extend(rule.to_rules());
633 self.set_rules_from(
634 actor,
635 "rule.intercept_legacy_upsert",
636 target,
637 details,
638 rules,
639 )
640 .await
641 }
642
643 pub async fn set_rules_from(
644 &self,
645 actor: AuditActor,
646 operation: &str,
647 target: String,
648 details: serde_json::Value,
649 rules: Vec<Rule>,
650 ) -> Result<(), String> {
651 let rule_count = rules.len();
652 if let Err(e) = self
653 .rule_store
654 .send(RuleStoreMessage::SetRules(rules))
655 .await
656 {
657 error!("Failed to send SetRules request: {}", e);
658 self.record_audit_event(AuditEvent::new(
659 actor,
660 AuditEventKind::RuleChanged,
661 target,
662 AuditOutcome::Failed,
663 json!({
664 "operation": operation,
665 "rule_count": rule_count,
666 "details": details,
667 "error": e.to_string()
668 }),
669 ));
670 return Err(e.to_string());
671 }
672
673 self.record_audit_event(AuditEvent::new(
674 actor,
675 AuditEventKind::RuleChanged,
676 target,
677 AuditOutcome::Success,
678 json!({
679 "operation": operation,
680 "rule_count": rule_count,
681 "details": details
682 }),
683 ));
684 Ok(())
685 }
686
687 pub async fn set_legacy_rules(&self, rules: Vec<InterceptRule>) {
688 let mut new_rules = Vec::new();
689 for rule in rules {
690 new_rules.extend(rule.to_rules());
691 }
692 self.set_rules(new_rules).await;
693 }
694
695 pub async fn get_rule_engine(&self) -> Arc<RuleEngine> {
696 let (tx, rx) = oneshot::channel();
697 if let Err(e) = self
698 .rule_store
699 .send(RuleStoreMessage::GetRuleEngine(tx))
700 .await
701 {
702 error!("Failed to send GetRuleEngine request: {}", e);
703 return Arc::new(RuleEngine::new(Vec::new(), Vec::new(), None, None));
704 }
705 rx.await
706 .map_err(|e| {
707 error!("Failed to receive RuleEngine response: {}", e);
708 e
709 })
710 .unwrap_or_else(|_| Arc::new(RuleEngine::new(Vec::new(), Vec::new(), None, None)))
711 }
712
713 pub fn update_policy(&self, policy: ProxyPolicy) {
714 self.update_policy_from(AuditActor::Runtime, "policy".to_string(), policy);
715 }
716
717 pub fn patch_policy_from(&self, actor: AuditActor, target: String, patch: ProxyPolicyPatch) {
718 let mut policy = self.policy_snapshot();
719 policy.apply_patch(patch);
720 self.update_policy_from(actor, target, policy);
721 }
722
723 pub fn policy_snapshot(&self) -> ProxyPolicy {
724 self.policy_tx.borrow().clone()
725 }
726
727 pub fn update_policy_from(&self, actor: AuditActor, target: String, policy: ProxyPolicy) {
728 let details = json!({
729 "strict_http_semantics": policy.strict_http_semantics,
730 "request_timeout_ms": policy.request_timeout_ms,
731 "max_body_size": policy.max_body_size,
732 "transparent_enabled": policy.transparent_enabled,
733 "redaction_enabled": policy.redaction.enabled,
734 "redact_bodies": policy.redaction.redact_bodies
735 });
736
737 self.policy_tx.send_replace(policy);
738 self.record_audit_event(AuditEvent::new(
739 actor,
740 AuditEventKind::PolicyUpdated,
741 target,
742 AuditOutcome::Success,
743 details,
744 ));
745 }
746
747 pub async fn register_intercept(&self, key: String, tx: oneshot::Sender<InterceptionResult>) {
748 if let Err(e) = self
749 .intercept_broker
750 .send(InterceptBrokerMessage::RegisterIntercept { key, tx })
751 .await
752 {
753 error!("Failed to send RegisterIntercept request: {}", e);
754 }
755 }
756
757 pub async fn resolve_intercept(
758 &self,
759 key: String,
760 result: InterceptionResult,
761 ) -> Result<(), String> {
762 let (tx, rx) = oneshot::channel();
763 if let Err(e) = self
764 .intercept_broker
765 .send(InterceptBrokerMessage::ResolveIntercept {
766 key,
767 result,
768 respond_to: tx,
769 })
770 .await
771 {
772 error!("Failed to send ResolveIntercept request: {}", e);
773 return Err(e.to_string());
774 }
775 rx.await.map_err(|_| "Actor dropped".to_string())?
776 }
777
778 pub async fn get_pending_ws_message(&self, key: String) -> Option<WebSocketMessage> {
779 let (tx, rx) = oneshot::channel();
780 if let Err(e) = self
781 .intercept_broker
782 .send(InterceptBrokerMessage::GetPendingWebSocketMessage {
783 key,
784 respond_to: tx,
785 })
786 .await
787 {
788 error!("Failed to send GetPendingWebSocketMessage request: {}", e);
789 return None;
790 }
791 rx.await
792 .map_err(|e| {
793 error!("Failed to receive WebSocketMessage response: {}", e);
794 e
795 })
796 .unwrap_or(None)
797 }
798
799 pub async fn set_pending_ws_message(&self, key: String, message: WebSocketMessage) {
800 if let Err(e) = self
801 .intercept_broker
802 .send(InterceptBrokerMessage::SetPendingWebSocketMessage { key, message })
803 .await
804 {
805 error!("Failed to send SetPendingWebSocketMessage request: {}", e);
806 }
807 }
808
809 pub async fn is_intercept_pending(&self, key: String) -> bool {
810 let (tx, rx) = oneshot::channel();
811 if let Err(e) = self
812 .intercept_broker
813 .send(InterceptBrokerMessage::GetPendingIntercept {
814 key,
815 respond_to: tx,
816 })
817 .await
818 {
819 error!("Failed to send GetPendingIntercept request: {}", e);
820 return false;
821 }
822 rx.await
823 .map_err(|e| {
824 error!("Failed to receive PendingIntercept response: {}", e);
825 e
826 })
827 .unwrap_or(false)
828 }
829
830 pub async fn is_flow_intercepted(&self, flow_id: String) -> bool {
831 let (tx, rx) = oneshot::channel();
832 if let Err(e) = self
833 .intercept_broker
834 .send(InterceptBrokerMessage::GetPendingInterceptByFlowId {
835 flow_id,
836 respond_to: tx,
837 })
838 .await
839 {
840 error!("Failed to send GetPendingInterceptByFlowId request: {}", e);
841 return false;
842 }
843 rx.await
844 .map_err(|e| {
845 error!("Failed to receive PendingInterceptByFlowId response: {}", e);
846 e
847 })
848 .unwrap_or(false)
849 }
850
851 pub fn upsert_flow(&self, flow: Box<Flow>) {
852 if let Err(e) = self.flow_store.try_send(FlowStoreMessage::UpsertFlow(flow)) {
853 error!("FlowStore dropped flow: {}", e);
855 self.flows_dropped.fetch_add(1, Ordering::Relaxed);
856 }
857 }
858
859 pub fn append_ws_message(&self, flow_id: String, message: WebSocketMessage) {
860 if let Err(e) = self
861 .flow_store
862 .try_send(FlowStoreMessage::AppendWebSocketMessage { flow_id, message })
863 {
864 error!("FlowStore dropped WS message: {}", e);
865 self.flows_dropped.fetch_add(1, Ordering::Relaxed);
866 }
867 }
868
869 pub fn update_http_body(&self, flow_id: String, body: BodyData, direction: Direction) {
870 if let Err(e) = self.flow_store.try_send(FlowStoreMessage::UpdateHttpBody {
871 flow_id,
872 body,
873 direction,
874 }) {
875 error!("FlowStore dropped HTTP body: {}", e);
876 self.flows_dropped.fetch_add(1, Ordering::Relaxed);
877 }
878 }
879
880 pub fn subscribe_flow_updates(&self) -> broadcast::Receiver<FlowUpdate> {
882 self.flow_broadcast_tx.subscribe()
883 }
884
885 pub fn subscribe_audit_events(&self) -> broadcast::Receiver<AuditEvent> {
886 self.audit_broadcast_tx.subscribe()
887 }
888
889 fn current_redaction_policy(&self) -> RedactionPolicy {
890 self.policy_tx.borrow().redaction.clone()
891 }
892
893 pub fn record_flow_events_lagged(&self, skipped: u64) {
894 self.flow_events_lagged_total
895 .fetch_add(skipped as usize, Ordering::Relaxed);
896 }
897
898 pub fn record_audit_events_lagged(&self, skipped: u64) {
899 self.audit_events_lagged_total
900 .fetch_add(skipped as usize, Ordering::Relaxed);
901 }
902
903 pub fn lifecycle(&self) -> RuntimeLifecycle {
904 self.lifecycle_tx.borrow().clone()
905 }
906
907 pub fn subscribe_lifecycle(&self) -> watch::Receiver<RuntimeLifecycle> {
908 self.lifecycle_tx.subscribe()
909 }
910
911 fn prepare_start(&self, port: u16, shutdown_tx: oneshot::Sender<()>) -> Result<(), String> {
912 let current = self.lifecycle();
913 if current.is_active() {
914 return Err(format!(
915 "Proxy is already {} on port {}",
916 current.phase.as_str(),
917 current.port.unwrap_or(port)
918 ));
919 }
920
921 let mut guard = self
922 .shutdown_tx
923 .lock()
924 .map_err(|_| "shutdown state poisoned".to_string())?;
925 *guard = Some(shutdown_tx);
926 drop(guard);
927
928 self.update_lifecycle(RuntimeLifecycle {
929 phase: RuntimeLifecyclePhase::Starting,
930 port: Some(port),
931 started_at_ms: None,
932 last_error: None,
933 });
934 Ok(())
935 }
936
937 pub fn stop_proxy(&self) -> Result<ProxyStopResult, String> {
938 let mut guard = self
939 .shutdown_tx
940 .lock()
941 .map_err(|_| "shutdown state poisoned".to_string())?;
942 let Some(tx) = guard.take() else {
943 return Ok(ProxyStopResult::NotRunning);
944 };
945 drop(guard);
946
947 let current = self.lifecycle();
948 self.update_lifecycle(RuntimeLifecycle {
949 phase: RuntimeLifecyclePhase::Stopping,
950 port: current.port,
951 started_at_ms: current.started_at_ms,
952 last_error: current.last_error,
953 });
954 let _ = tx.send(());
955 Ok(ProxyStopResult::Stopping)
956 }
957
958 pub fn recent_audit_events(&self) -> Vec<AuditEvent> {
959 self.audit_history
960 .lock()
961 .map(|events| events.iter().cloned().collect())
962 .unwrap_or_default()
963 }
964
965 pub async fn search_flows(&self, query: FlowQuery) -> Vec<FlowSummary> {
967 let redaction = self.current_redaction_policy();
968 if let Some(store) = &self.store {
969 return store
970 .query_flow_summaries(&query)
971 .await
972 .unwrap_or_default()
973 .into_iter()
974 .map(|summary| redact_flow_summary(summary, &redaction))
975 .collect();
976 }
977 let (tx, rx) = oneshot::channel();
978 if let Err(e) = self
979 .flow_store
980 .send(FlowStoreMessage::SearchFlows {
981 query,
982 respond_to: tx,
983 })
984 .await
985 {
986 error!("Failed to send SearchFlows request: {}", e);
987 return Vec::new();
988 }
989 rx.await
990 .unwrap_or_default()
991 .into_iter()
992 .map(|summary| redact_flow_summary(summary, &redaction))
993 .collect()
994 }
995
996 pub fn redact_flow_update_for_output(&self, update: FlowUpdate) -> FlowUpdate {
997 let redaction = self.current_redaction_policy();
998 redact_flow_update(update, &redaction)
999 }
1000
1001 pub async fn resolve_intercept_with_modifications(
1011 &self,
1012 key: String,
1013 action: &str,
1014 mods: Option<relay_core_api::modification::FlowModification>,
1015 ) -> Result<(), String> {
1016 self.resolve_intercept_with_modifications_from(AuditActor::Runtime, key, action, mods)
1017 .await
1018 }
1019
1020 pub async fn resolve_intercept_with_modifications_from(
1021 &self,
1022 actor: AuditActor,
1023 key: String,
1024 action: &str,
1025 mods: Option<relay_core_api::modification::FlowModification>,
1026 ) -> Result<(), String> {
1027 let modified_fields = modification_field_names(mods.as_ref());
1028 let result = match action {
1029 "drop" => InterceptionResult::Drop,
1030 _ => match mods {
1031 None => InterceptionResult::Continue,
1032 Some(m) => {
1033 let parts: Vec<&str> = key.splitn(4, ':').collect();
1034 match parts.as_slice() {
1035 [flow_id, phase] => {
1036 if let Some(flow) = self.get_flow(flow_id.to_string()).await {
1037 modification::apply_flow_modification(&flow, phase, m)
1038 } else {
1039 InterceptionResult::Continue
1040 }
1041 }
1042 [_, "ws_msg", _] => {
1045 if let Some(msg) = self.get_pending_ws_message(key.clone()).await {
1046 modification::apply_ws_modification(&msg, m)
1047 } else {
1048 InterceptionResult::Continue
1049 }
1050 }
1051 _ => InterceptionResult::Continue,
1052 }
1053 }
1054 },
1055 };
1056 let outcome = self.resolve_intercept(key.clone(), result).await;
1057 let audit_outcome = if outcome.is_ok() {
1058 AuditOutcome::Success
1059 } else {
1060 AuditOutcome::Failed
1061 };
1062 let error_message = outcome.as_ref().err().cloned();
1063
1064 self.record_audit_event(AuditEvent::new(
1065 actor,
1066 AuditEventKind::InterceptResolved,
1067 key,
1068 audit_outcome,
1069 json!({
1070 "action": action,
1071 "has_modifications": !modified_fields.is_empty(),
1072 "modified_fields": modified_fields,
1073 "error": error_message
1074 }),
1075 ));
1076 outcome
1077 }
1078
1079 #[cfg(feature = "script")]
1080 pub async fn load_script_from(
1081 &self,
1082 actor: AuditActor,
1083 target: String,
1084 script: &str,
1085 ) -> Result<(), String> {
1086 let result = self
1087 .script_interceptor
1088 .load_script(script)
1089 .await
1090 .map_err(|e| e.to_string());
1091
1092 let outcome = if result.is_ok() {
1093 AuditOutcome::Success
1094 } else {
1095 AuditOutcome::Failed
1096 };
1097 let error_message = result.as_ref().err().cloned();
1098
1099 self.record_audit_event(AuditEvent::new(
1100 actor,
1101 AuditEventKind::ScriptReloaded,
1102 target,
1103 outcome,
1104 json!({
1105 "script_bytes": script.len(),
1106 "error": error_message
1107 }),
1108 ));
1109
1110 result
1111 }
1112
1113 fn record_audit_event(&self, event: AuditEvent) {
1114 const AUDIT_HISTORY_LIMIT: usize = 200;
1115 self.audit_events_total.fetch_add(1, Ordering::Relaxed);
1116 if event.outcome == AuditOutcome::Failed {
1117 self.audit_events_failed.fetch_add(1, Ordering::Relaxed);
1118 }
1119
1120 let details = event.details.to_string();
1121 tracing::info!(
1122 target: "relay_core_audit",
1123 event_id = %event.id,
1124 actor = %event.actor.as_str(),
1125 kind = %event.kind.as_str(),
1126 target = %event.target,
1127 outcome = %event.outcome.as_str(),
1128 details = %details
1129 );
1130
1131 if let Ok(mut history) = self.audit_history.lock() {
1132 if history.len() >= AUDIT_HISTORY_LIMIT {
1133 history.pop_front();
1134 }
1135 history.push_back(event.clone());
1136 }
1137
1138 if let Some(store) = self.store.clone() {
1139 let event_json = serde_json::to_value(&event).unwrap_or_default();
1140 let event_id = event.id.clone();
1141 let timestamp_ms = event.timestamp_ms;
1142 let actor = event.actor.as_str().to_string();
1143 let kind = event.kind.as_str().to_string();
1144 let target = event.target.clone();
1145 let outcome = event.outcome.as_str().to_string();
1146 if let Ok(handle) = tokio::runtime::Handle::try_current() {
1147 handle.spawn(async move {
1148 if let Err(e) = store
1149 .save_audit_event(AuditEventRecord {
1150 id: &event_id,
1151 timestamp_ms,
1152 actor: &actor,
1153 kind: &kind,
1154 target: &target,
1155 outcome: &outcome,
1156 content: &event_json,
1157 })
1158 .await
1159 {
1160 tracing::error!("Failed to persist audit event: {}", e);
1161 }
1162 });
1163 }
1164 }
1165
1166 let _ = self.audit_broadcast_tx.send(event);
1167 }
1168
1169 fn transition_to_running(&self, port: u16) {
1170 self.update_lifecycle(RuntimeLifecycle {
1171 phase: RuntimeLifecyclePhase::Running,
1172 port: Some(port),
1173 started_at_ms: Some(now_unix_ms()),
1174 last_error: None,
1175 });
1176 }
1177
1178 fn transition_to_stopped(&self) {
1179 if let Ok(mut guard) = self.shutdown_tx.lock() {
1180 *guard = None;
1181 }
1182
1183 self.update_lifecycle(RuntimeLifecycle {
1184 phase: RuntimeLifecyclePhase::Stopped,
1185 port: None,
1186 started_at_ms: None,
1187 last_error: None,
1188 });
1189 }
1190
1191 fn transition_to_failed(&self, port: u16, error: String) {
1192 if let Ok(mut guard) = self.shutdown_tx.lock() {
1193 *guard = None;
1194 }
1195
1196 self.update_lifecycle(RuntimeLifecycle {
1197 phase: RuntimeLifecyclePhase::Failed,
1198 port: Some(port),
1199 started_at_ms: None,
1200 last_error: Some(error),
1201 });
1202 }
1203
1204 fn update_lifecycle(&self, lifecycle: RuntimeLifecycle) {
1205 tracing::info!(
1206 target: "relay_core_lifecycle",
1207 phase = %lifecycle.phase.as_str(),
1208 port = ?lifecycle.port,
1209 started_at_ms = ?lifecycle.started_at_ms,
1210 last_error = ?lifecycle.last_error
1211 );
1212 self.lifecycle_tx.send_replace(lifecycle);
1213 }
1214
1215 pub fn spawn_proxy(
1216 self: &Arc<Self>,
1217 config: ProxyConfig,
1218 sink: mpsc::Sender<FlowUpdate>,
1219 extra_interceptor: Option<Arc<dyn Interceptor>>,
1220 ) -> Result<ProxySpawnResult, String> {
1221 let (shutdown_tx, shutdown_rx) = oneshot::channel();
1222 match self.prepare_start(config.port, shutdown_tx) {
1223 Ok(()) => {}
1224 Err(error) if error.contains("already") => return Ok(ProxySpawnResult::AlreadyRunning),
1225 Err(error) => return Err(error),
1226 }
1227 let state = self.clone();
1228 Ok(ProxySpawnResult::Started(tokio::spawn(async move {
1229 if let Err(error) = state
1230 .run_proxy(config, sink, extra_interceptor, shutdown_rx)
1231 .await
1232 {
1233 error!("Proxy failed: {}", error);
1234 }
1235 })))
1236 }
1237
1238 pub async fn start_proxy(
1239 self: &Arc<Self>,
1240 config: ProxyConfig,
1241 sink: mpsc::Sender<FlowUpdate>,
1242 extra_interceptor: Option<Arc<dyn Interceptor>>,
1243 ) -> Result<(), String> {
1244 let (shutdown_tx, shutdown_rx) = oneshot::channel();
1245 self.prepare_start(config.port, shutdown_tx)?;
1246 self.run_proxy(config, sink, extra_interceptor, shutdown_rx)
1247 .await
1248 }
1249
1250 async fn run_proxy(
1251 self: &Arc<Self>,
1252 config: ProxyConfig,
1253 sink: mpsc::Sender<FlowUpdate>,
1254 extra_interceptor: Option<Arc<dyn Interceptor>>,
1255 shutdown_rx: oneshot::Receiver<()>,
1256 ) -> Result<(), String> {
1257 let addr = SocketAddr::from(([127, 0, 0, 1], config.port));
1258 let state = self.clone();
1259
1260 if let Some(parent) = config.ca_cert_path.parent()
1261 && !parent.exists()
1262 {
1263 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
1264 }
1265
1266 let ca = CertificateAuthority::load_or_create(&config.ca_cert_path, &config.ca_key_path)
1267 .map_err(|e| format!("Failed to load/create CA: {}", e))?;
1268 let ca = Arc::new(ca);
1269
1270 #[cfg(feature = "script")]
1271 let script_interceptor = self.script_interceptor.clone();
1272
1273 #[cfg(feature = "script")]
1274 let mut interceptors: Vec<Arc<dyn Interceptor>> = vec![script_interceptor];
1275
1276 #[cfg(not(feature = "script"))]
1277 let mut interceptors: Vec<Arc<dyn Interceptor>> = vec![];
1278
1279 interceptors.push(Arc::new(interceptors::metrics::MetricsInterceptor::new(
1280 self.clone(),
1281 )));
1282
1283 if let Some(interceptor) = extra_interceptor {
1284 interceptors.push(interceptor);
1285 }
1286
1287 let interceptor = Arc::new(CompositeInterceptor::new(interceptors));
1288 let (proxy_tx, mut proxy_rx) = mpsc::channel::<FlowUpdate>(1000);
1289
1290 tokio::spawn(async move {
1291 while let Some(update) = proxy_rx.recv().await {
1292 match update.clone() {
1293 FlowUpdate::Full(flow) => {
1294 state.upsert_flow(flow);
1295 }
1296 FlowUpdate::WebSocketMessage { flow_id, message } => {
1297 state.append_ws_message(flow_id, message);
1298 }
1299 FlowUpdate::HttpBody {
1300 flow_id,
1301 direction,
1302 body,
1303 } => {
1304 state.update_http_body(flow_id, body, direction);
1305 }
1306 }
1307
1308 let _ = state.flow_broadcast_tx.send(update.clone());
1309
1310 if sink.try_send(update).is_err() {
1311 relay_core_lib::metrics::inc_flows_dropped();
1312 }
1313 }
1314 });
1315
1316 if let Some(udp_port) = config.udp_tproxy_port {
1317 let udp_proxy_tx = proxy_tx.clone();
1318 let udp_addr = SocketAddr::from(([0, 0, 0, 0], udp_port));
1319 tokio::spawn(async move {
1320 match tokio::net::UdpSocket::bind(udp_addr).await {
1321 Ok(socket) => {
1322 let proxy = UdpProxy::new(socket, std::time::Duration::from_secs(60));
1323 if let Err(e) = proxy.run(udp_proxy_tx).await {
1324 error!("UDP TPROXY failed: {}", e);
1325 }
1326 }
1327 Err(e) => {
1328 error!("Failed to bind UDP TPROXY socket: {}", e);
1329 }
1330 }
1331 });
1332 }
1333
1334 let listener = match TcpListener::bind(addr).await {
1335 Ok(listener) => listener,
1336 Err(e) => {
1337 if let Ok(mut guard) = self.shutdown_tx.lock() {
1338 *guard = None;
1339 }
1340 let message = format!("Failed to bind to address {}: {}", addr, e);
1341 self.transition_to_failed(config.port, message.clone());
1342 return Err(message);
1343 }
1344 };
1345
1346 self.transition_to_running(config.port);
1347 let shutdown_rx = Some(shutdown_rx);
1348
1349 if config.transparent {
1350 let policy = ProxyPolicy {
1351 transparent_enabled: true,
1352 ..Default::default()
1353 };
1354 self.update_policy_from(AuditActor::Runtime, "proxy.transparent".to_string(), policy);
1355 let policy_rx = self.policy_tx.subscribe();
1356
1357 let provider: Arc<dyn OriginalDstProvider> = {
1358 let mut addrs = BTreeSet::new();
1359 if let Ok(local) = listener.local_addr() {
1360 addrs.insert(local);
1361 }
1362
1363 #[cfg(all(target_os = "linux", feature = "transparent-linux"))]
1364 {
1365 Arc::new(LinuxOriginalDstProvider::new(addrs))
1366 }
1367 #[cfg(all(target_os = "macos", feature = "transparent-macos"))]
1368 {
1369 match MacOsOriginalDstProvider::new(addrs.clone()) {
1370 Ok(provider) => Arc::new(provider),
1371 Err(e) => {
1372 error!("Failed to initialize macOS PF provider: {}", e);
1373 Arc::new(relay_core_lib::capture::NoOpOriginalDstProvider::new(addrs))
1374 }
1375 }
1376 }
1377 #[cfg(target_os = "windows")]
1378 {
1379 let filter =
1380 "outbound and !loopback and (tcp.DstPort == 80 or tcp.DstPort == 443)"
1381 .to_string();
1382 let port = config.port;
1383 tokio::spawn(async move {
1384 relay_core_lib::capture::windows::start_windivert_capture(filter, port)
1385 .await;
1386 });
1387
1388 Arc::new(WindowsOriginalDstProvider::new(addrs))
1389 }
1390 #[cfg(not(any(
1391 all(target_os = "linux", feature = "transparent-linux"),
1392 all(target_os = "macos", feature = "transparent-macos"),
1393 target_os = "windows"
1394 )))]
1395 {
1396 Arc::new(NoOpOriginalDstProvider::new(addrs))
1397 }
1398 };
1399
1400 let source = TransparentTcpCaptureSource::new(listener, provider);
1401 let result = relay_core_lib::start_proxy(
1402 source,
1403 proxy_tx,
1404 interceptor,
1405 ca,
1406 policy_rx,
1407 None,
1408 shutdown_rx,
1409 )
1410 .await
1411 .map_err(|e| e.to_string());
1412 if let Err(error) = &result {
1413 self.transition_to_failed(config.port, error.clone());
1414 } else {
1415 self.transition_to_stopped();
1416 }
1417 result
1418 } else {
1419 let source = TcpCaptureSource::new(listener);
1420 let policy = ProxyPolicy::default();
1421 self.update_policy_from(AuditActor::Runtime, "proxy.standard".to_string(), policy);
1422 let policy_rx = self.policy_tx.subscribe();
1423
1424 let result = relay_core_lib::start_proxy(
1425 source,
1426 proxy_tx,
1427 interceptor,
1428 ca,
1429 policy_rx,
1430 None,
1431 shutdown_rx,
1432 )
1433 .await
1434 .map_err(|e| e.to_string());
1435 if let Err(error) = &result {
1436 self.transition_to_failed(config.port, error.clone());
1437 } else {
1438 self.transition_to_stopped();
1439 }
1440 result
1441 }
1442 }
1443}
1444
1445fn redact_flow_update(update: FlowUpdate, redaction: &RedactionPolicy) -> FlowUpdate {
1446 match update {
1447 FlowUpdate::Full(flow) => FlowUpdate::Full(Box::new(redact_flow(*flow, redaction))),
1448 FlowUpdate::WebSocketMessage {
1449 flow_id,
1450 mut message,
1451 } => {
1452 message.content = redact_body(message.content, redaction);
1453 FlowUpdate::WebSocketMessage { flow_id, message }
1454 }
1455 FlowUpdate::HttpBody {
1456 flow_id,
1457 direction,
1458 body,
1459 } => FlowUpdate::HttpBody {
1460 flow_id,
1461 direction,
1462 body: redact_body(body, redaction),
1463 },
1464 }
1465}
1466
1467fn redact_flow(mut flow: Flow, redaction: &RedactionPolicy) -> Flow {
1468 if !redaction.enabled {
1469 return flow;
1470 }
1471 match &mut flow.layer {
1472 Layer::Http(http) => {
1473 redact_http_request(&mut http.request, redaction);
1474 if let Some(response) = &mut http.response {
1475 redact_headers(&mut response.headers, redaction);
1476 response.body = response
1477 .body
1478 .take()
1479 .map(|body| redact_body(body, redaction));
1480 }
1481 }
1482 Layer::WebSocket(ws) => {
1483 redact_http_request(&mut ws.handshake_request, redaction);
1484 redact_headers(&mut ws.handshake_response.headers, redaction);
1485 ws.handshake_response.body = ws
1486 .handshake_response
1487 .body
1488 .take()
1489 .map(|body| redact_body(body, redaction));
1490 for message in &mut ws.messages {
1491 message.content = redact_body(message.content.clone(), redaction);
1492 }
1493 }
1494 _ => {}
1495 }
1496 flow
1497}
1498
1499fn redact_flow_summary(mut summary: FlowSummary, redaction: &RedactionPolicy) -> FlowSummary {
1500 if !redaction.enabled {
1501 return summary;
1502 }
1503 summary.url = redact_url_string(&summary.url, redaction);
1504 summary
1505}
1506
1507fn redact_http_request(
1508 request: &mut relay_core_api::flow::HttpRequest,
1509 redaction: &RedactionPolicy,
1510) {
1511 redact_headers(&mut request.headers, redaction);
1512 redact_query_pairs(&mut request.query, redaction);
1513 request.url = redact_url(&request.url, redaction);
1514 request.body = request.body.take().map(|body| redact_body(body, redaction));
1515}
1516
1517fn redact_headers(headers: &mut [(String, String)], redaction: &RedactionPolicy) {
1518 if !redaction.enabled {
1519 return;
1520 }
1521 let sensitive = redaction_set(&redaction.sensitive_header_names);
1522 for (name, value) in headers.iter_mut() {
1523 if sensitive.contains(&name.to_ascii_lowercase()) {
1524 *value = "[REDACTED]".to_string();
1525 }
1526 }
1527}
1528
1529fn redact_query_pairs(query: &mut [(String, String)], redaction: &RedactionPolicy) {
1530 if !redaction.enabled {
1531 return;
1532 }
1533 let sensitive = redaction_set(&redaction.sensitive_query_keys);
1534 for (name, value) in query.iter_mut() {
1535 if sensitive.contains(&name.to_ascii_lowercase()) {
1536 *value = "[REDACTED]".to_string();
1537 }
1538 }
1539}
1540
1541fn redact_url(url: &url::Url, redaction: &RedactionPolicy) -> url::Url {
1542 if !redaction.enabled {
1543 return url.clone();
1544 }
1545 let sensitive = redaction_set(&redaction.sensitive_query_keys);
1546 let pairs: Vec<(String, String)> = url
1547 .query_pairs()
1548 .map(|(k, v)| {
1549 let key = k.to_string();
1550 let value = if sensitive.contains(&key.to_ascii_lowercase()) {
1551 "[REDACTED]".to_string()
1552 } else {
1553 v.to_string()
1554 };
1555 (key, value)
1556 })
1557 .collect();
1558 let mut next = url.clone();
1559 if pairs.is_empty() {
1560 return next;
1561 }
1562 next.query_pairs_mut().clear();
1563 for (k, v) in pairs {
1564 next.query_pairs_mut().append_pair(&k, &v);
1565 }
1566 next
1567}
1568
1569fn redact_url_string(input: &str, redaction: &RedactionPolicy) -> String {
1570 match url::Url::parse(input) {
1571 Ok(url) => redact_url(&url, redaction).to_string(),
1572 Err(_) => input.to_string(),
1573 }
1574}
1575
1576fn redact_body(mut body: BodyData, redaction: &RedactionPolicy) -> BodyData {
1577 if redaction.enabled && redaction.redact_bodies {
1578 body.content = "[REDACTED]".to_string();
1579 }
1580 body
1581}
1582
1583fn redaction_set(values: &[String]) -> HashSet<String> {
1584 values
1585 .iter()
1586 .map(|value| value.to_ascii_lowercase())
1587 .collect()
1588}
1589
1590#[derive(Clone)]
1591pub struct ProxyConfig {
1592 pub port: u16,
1593 pub ca_cert_path: std::path::PathBuf,
1594 pub ca_key_path: std::path::PathBuf,
1595 pub transparent: bool,
1596 pub udp_tproxy_port: Option<u16>,
1597}
1598
1599impl ProxyConfig {
1600 pub fn new(
1601 port: u16,
1602 ca_cert_path: std::path::PathBuf,
1603 ca_key_path: std::path::PathBuf,
1604 ) -> Self {
1605 Self {
1606 port,
1607 ca_cert_path,
1608 ca_key_path,
1609 transparent: false,
1610 udp_tproxy_port: None,
1611 }
1612 }
1613
1614 pub fn from_app_data_dir(
1615 app_data_dir: impl Into<std::path::PathBuf>,
1616 port: u16,
1617 ) -> Result<Self, String> {
1618 let app_data_dir = app_data_dir.into();
1619 if !app_data_dir.exists() {
1620 std::fs::create_dir_all(&app_data_dir).map_err(|e| e.to_string())?;
1621 }
1622
1623 Ok(Self::new(
1624 port,
1625 app_data_dir.join("ca_cert.pem"),
1626 app_data_dir.join("ca_key.pem"),
1627 ))
1628 }
1629
1630 pub fn with_transparent(mut self, transparent: bool) -> Self {
1631 self.transparent = transparent;
1632 self
1633 }
1634
1635 pub fn with_udp_tproxy_port(mut self, udp_tproxy_port: Option<u16>) -> Self {
1636 self.udp_tproxy_port = udp_tproxy_port;
1637 self
1638 }
1639}
1640
1641fn now_unix_ms() -> u64 {
1642 SystemTime::now()
1643 .duration_since(UNIX_EPOCH)
1644 .unwrap_or_default()
1645 .as_millis() as u64
1646}
1647
1648fn modification_field_names(
1649 mods: Option<&relay_core_api::modification::FlowModification>,
1650) -> Vec<&'static str> {
1651 let Some(mods) = mods else {
1652 return Vec::new();
1653 };
1654
1655 let mut fields = Vec::new();
1656 if mods.method.is_some() {
1657 fields.push("method");
1658 }
1659 if mods.url.is_some() {
1660 fields.push("url");
1661 }
1662 if mods.request_headers.is_some() {
1663 fields.push("request_headers");
1664 }
1665 if mods.request_body.is_some() {
1666 fields.push("request_body");
1667 }
1668 if mods.status_code.is_some() {
1669 fields.push("status_code");
1670 }
1671 if mods.response_headers.is_some() {
1672 fields.push("response_headers");
1673 }
1674 if mods.response_body.is_some() {
1675 fields.push("response_body");
1676 }
1677 if mods.message_content.is_some() {
1678 fields.push("message_content");
1679 }
1680 fields
1681}
1682
1683#[cfg(test)]
1684mod tests {
1685 use super::*;
1686 use chrono::Utc;
1687 use relay_core_api::flow::{
1688 BodyData, Flow, FlowUpdate, HttpLayer, HttpRequest, HttpResponse, Layer, NetworkInfo,
1689 ResponseTiming, TransportProtocol,
1690 };
1691 use std::sync::atomic::{AtomicU64, Ordering};
1692 use tokio::time::{Duration, sleep};
1693 use url::Url;
1694 use uuid::Uuid;
1695
1696 static TEST_DB_COUNTER: AtomicU64 = AtomicU64::new(0);
1697
1698 fn sqlite_url() -> String {
1699 let nanos = SystemTime::now()
1700 .duration_since(UNIX_EPOCH)
1701 .expect("clock drift")
1702 .as_nanos();
1703 let pid = std::process::id();
1704 let seq = TEST_DB_COUNTER.fetch_add(1, Ordering::Relaxed);
1705 let db_dir = std::env::current_dir()
1706 .expect("cwd")
1707 .join("target")
1708 .join("test-dbs");
1709 std::fs::create_dir_all(&db_dir).expect("create test db dir");
1710 let db_path = db_dir.join(format!(
1711 "relay-core-runtime-test-{}-{}-{}.db",
1712 pid, nanos, seq
1713 ));
1714 format!("sqlite://{}?mode=rwc", db_path.display())
1715 }
1716
1717 fn sample_http_flow(host: &str, path: &str, method: &str, status: u16, ts: i64) -> Flow {
1718 let start_time =
1719 chrono::DateTime::<Utc>::from_timestamp_millis(ts).expect("timestamp should be valid");
1720 let request_url =
1721 Url::parse(&format!("http://{}{}", host, path)).expect("url should parse");
1722 Flow {
1723 id: Uuid::new_v4(),
1724 start_time,
1725 end_time: Some(start_time),
1726 network: NetworkInfo {
1727 client_ip: "127.0.0.1".to_string(),
1728 client_port: 12000,
1729 server_ip: "127.0.0.1".to_string(),
1730 server_port: 8080,
1731 protocol: TransportProtocol::TCP,
1732 tls: false,
1733 tls_version: None,
1734 sni: None,
1735 },
1736 layer: Layer::Http(HttpLayer {
1737 request: HttpRequest {
1738 method: method.to_string(),
1739 url: request_url,
1740 version: "HTTP/1.1".to_string(),
1741 headers: vec![],
1742 cookies: vec![],
1743 query: vec![],
1744 body: None,
1745 },
1746 response: Some(HttpResponse {
1747 status,
1748 status_text: "OK".to_string(),
1749 version: "HTTP/1.1".to_string(),
1750 headers: vec![],
1751 cookies: vec![],
1752 body: None,
1753 timing: ResponseTiming {
1754 time_to_first_byte: None,
1755 time_to_last_byte: None,
1756 connect_time_ms: None,
1757 ssl_time_ms: None,
1758 },
1759 }),
1760 error: None,
1761 }),
1762 tags: vec![],
1763 meta: std::collections::HashMap::new(),
1764 }
1765 }
1766
1767 fn sample_sensitive_http_flow(ts: i64) -> Flow {
1768 let start_time =
1769 chrono::DateTime::<Utc>::from_timestamp_millis(ts).expect("timestamp should be valid");
1770 let request_url = Url::parse("http://api.example.com/private?token=abc123&ok=1")
1771 .expect("url should parse");
1772 Flow {
1773 id: Uuid::new_v4(),
1774 start_time,
1775 end_time: Some(start_time),
1776 network: NetworkInfo {
1777 client_ip: "127.0.0.1".to_string(),
1778 client_port: 12000,
1779 server_ip: "127.0.0.1".to_string(),
1780 server_port: 8080,
1781 protocol: TransportProtocol::TCP,
1782 tls: false,
1783 tls_version: None,
1784 sni: None,
1785 },
1786 layer: Layer::Http(HttpLayer {
1787 request: HttpRequest {
1788 method: "GET".to_string(),
1789 url: request_url,
1790 version: "HTTP/1.1".to_string(),
1791 headers: vec![
1792 (
1793 "Authorization".to_string(),
1794 "Bearer secret-token".to_string(),
1795 ),
1796 ("X-Normal".to_string(), "visible".to_string()),
1797 ],
1798 cookies: vec![],
1799 query: vec![
1800 ("token".to_string(), "abc123".to_string()),
1801 ("ok".to_string(), "1".to_string()),
1802 ],
1803 body: Some(BodyData {
1804 encoding: "utf-8".to_string(),
1805 content: "secret request body".to_string(),
1806 size: 19,
1807 }),
1808 },
1809 response: Some(HttpResponse {
1810 status: 200,
1811 status_text: "OK".to_string(),
1812 version: "HTTP/1.1".to_string(),
1813 headers: vec![
1814 ("Set-Cookie".to_string(), "session=abcd".to_string()),
1815 ("X-Response".to_string(), "visible".to_string()),
1816 ],
1817 cookies: vec![],
1818 body: Some(BodyData {
1819 encoding: "utf-8".to_string(),
1820 content: "secret response body".to_string(),
1821 size: 20,
1822 }),
1823 timing: ResponseTiming {
1824 time_to_first_byte: None,
1825 time_to_last_byte: None,
1826 connect_time_ms: None,
1827 ssl_time_ms: None,
1828 },
1829 }),
1830 error: None,
1831 }),
1832 tags: vec![],
1833 meta: std::collections::HashMap::new(),
1834 }
1835 }
1836
1837 #[tokio::test]
1838 async fn set_rules_from_records_audit_event() {
1839 let state = CoreState::new(None).await;
1840
1841 state
1842 .set_rules_from(
1843 AuditActor::Http,
1844 "rule.upsert",
1845 "rule-1".to_string(),
1846 json!({ "route": "/api/v1/rules" }),
1847 Vec::new(),
1848 )
1849 .await
1850 .expect("set rules should succeed");
1851
1852 let events = state.recent_audit_events();
1853 let event = events.last().expect("audit event should exist");
1854 assert_eq!(event.actor, AuditActor::Http);
1855 assert_eq!(event.kind, AuditEventKind::RuleChanged);
1856 assert_eq!(event.outcome, AuditOutcome::Success);
1857 assert_eq!(event.target, "rule-1");
1858 assert_eq!(event.details["operation"], "rule.upsert");
1859 assert_eq!(event.details["details"]["route"], "/api/v1/rules");
1860 }
1861
1862 #[tokio::test]
1863 async fn upsert_rule_from_replaces_existing_rule_and_records_audit_event() {
1864 let state = CoreState::new(None).await;
1865
1866 state
1867 .upsert_rule_from(
1868 AuditActor::Probe,
1869 "rule.upsert",
1870 "rule-1".to_string(),
1871 json!({ "tool": "set_rule" }),
1872 Rule {
1873 id: "rule-1".to_string(),
1874 name: "first".to_string(),
1875 active: true,
1876 stage: relay_core_lib::rule::RuleStage::RequestHeaders,
1877 priority: 1,
1878 termination: relay_core_lib::rule::RuleTermination::Continue,
1879 filter: relay_core_lib::rule::Filter::Url(
1880 relay_core_lib::rule::StringMatcher::Contains("a".to_string()),
1881 ),
1882 actions: vec![],
1883 constraints: None,
1884 },
1885 )
1886 .await
1887 .expect("initial upsert should succeed");
1888
1889 state
1890 .upsert_rule_from(
1891 AuditActor::Probe,
1892 "rule.upsert",
1893 "rule-1".to_string(),
1894 json!({ "tool": "set_rule" }),
1895 Rule {
1896 id: "rule-1".to_string(),
1897 name: "second".to_string(),
1898 active: true,
1899 stage: relay_core_lib::rule::RuleStage::RequestHeaders,
1900 priority: 2,
1901 termination: relay_core_lib::rule::RuleTermination::Continue,
1902 filter: relay_core_lib::rule::Filter::Url(
1903 relay_core_lib::rule::StringMatcher::Contains("b".to_string()),
1904 ),
1905 actions: vec![],
1906 constraints: None,
1907 },
1908 )
1909 .await
1910 .expect("replacement upsert should succeed");
1911
1912 let rules = state.get_rules().await;
1913 assert_eq!(rules.len(), 1);
1914 assert_eq!(rules[0].name, "second");
1915 let event = state
1916 .recent_audit_events()
1917 .last()
1918 .cloned()
1919 .expect("audit event");
1920 assert_eq!(event.details["operation"], "rule.upsert");
1921 assert_eq!(event.details["details"]["tool"], "set_rule");
1922 }
1923
1924 #[tokio::test]
1925 async fn delete_rule_from_returns_false_when_rule_missing() {
1926 let state = CoreState::new(None).await;
1927
1928 let deleted = state
1929 .delete_rule_from(
1930 AuditActor::Http,
1931 "rule.delete",
1932 "missing".to_string(),
1933 json!({ "route": "/api/v1/rules/{id}" }),
1934 "missing",
1935 )
1936 .await
1937 .expect("delete should not fail");
1938
1939 assert!(!deleted);
1940 assert!(state.recent_audit_events().is_empty());
1941 }
1942
1943 #[tokio::test]
1944 async fn create_mock_response_rule_from_adds_rule_and_records_audit_event() {
1945 let state = CoreState::new(None).await;
1946
1947 let rule_id = state
1948 .create_mock_response_rule_from(
1949 AuditActor::Http,
1950 "api-mock-1".to_string(),
1951 json!({ "route": "/api/v1/mock", "status": 201 }),
1952 MockResponseRuleConfig {
1953 rule_id: "api-mock-1".to_string(),
1954 url_pattern: "example.com".to_string(),
1955 name: "api-mock:example.com".to_string(),
1956 status: 201,
1957 content_type: "application/json".to_string(),
1958 body: "{\"ok\":true}".to_string(),
1959 },
1960 )
1961 .await
1962 .expect("mock rule should be created");
1963
1964 assert_eq!(rule_id, "api-mock-1");
1965 let rules = state.get_rules().await;
1966 assert_eq!(rules.len(), 1);
1967 assert_eq!(rules[0].id, "api-mock-1");
1968 let event = state
1969 .recent_audit_events()
1970 .last()
1971 .cloned()
1972 .expect("audit event");
1973 assert_eq!(event.details["operation"], "rule.mock_create");
1974 assert_eq!(event.details["details"]["route"], "/api/v1/mock");
1975 }
1976
1977 #[tokio::test]
1978 async fn create_intercept_rule_from_adds_stop_rule_and_records_audit_event() {
1979 let state = CoreState::new(None).await;
1980
1981 let rule_id = state
1982 .create_intercept_rule_from(
1983 AuditActor::Http,
1984 "intercept-1".to_string(),
1985 json!({ "route": "/api/v1/intercepts", "phase": "request" }),
1986 InterceptRuleConfig {
1987 rule_id: "intercept-1".to_string(),
1988 active: true,
1989 url_pattern: "example.com".to_string(),
1990 method: None,
1991 phase: "request".to_string(),
1992 name: "api-intercept:example.com".to_string(),
1993 priority: 100,
1994 termination: relay_core_lib::rule::RuleTermination::Stop,
1995 },
1996 )
1997 .await
1998 .expect("intercept rule should be created");
1999
2000 assert_eq!(rule_id, "intercept-1");
2001 let rules = state.get_rules().await;
2002 assert_eq!(rules.len(), 1);
2003 assert_eq!(rules[0].id, "intercept-1");
2004 assert_eq!(rules[0].name, "api-intercept:example.com");
2005 let event = state
2006 .recent_audit_events()
2007 .last()
2008 .cloned()
2009 .expect("audit event");
2010 assert_eq!(event.details["operation"], "rule.intercept_create");
2011 assert_eq!(event.details["details"]["route"], "/api/v1/intercepts");
2012 }
2013
2014 #[tokio::test]
2015 async fn upsert_legacy_intercept_rule_from_replaces_existing_family() {
2016 let state = CoreState::new(None).await;
2017
2018 state
2019 .upsert_legacy_intercept_rule_from(
2020 AuditActor::Tauri,
2021 "legacy-1".to_string(),
2022 json!({ "command": "set_intercept_rule" }),
2023 InterceptRule {
2024 id: "legacy-1".to_string(),
2025 active: true,
2026 url_pattern: "example.com".to_string(),
2027 method: None,
2028 phase: "both".to_string(),
2029 },
2030 )
2031 .await
2032 .expect("initial family upsert should succeed");
2033 assert_eq!(state.get_rules().await.len(), 2);
2034
2035 state
2036 .upsert_legacy_intercept_rule_from(
2037 AuditActor::Tauri,
2038 "legacy-1".to_string(),
2039 json!({ "command": "set_intercept_rule" }),
2040 InterceptRule {
2041 id: "legacy-1".to_string(),
2042 active: true,
2043 url_pattern: "example.org".to_string(),
2044 method: Some("POST".to_string()),
2045 phase: "request".to_string(),
2046 },
2047 )
2048 .await
2049 .expect("replacement family upsert should succeed");
2050
2051 let rules = state.get_rules().await;
2052 assert_eq!(rules.len(), 1);
2053 assert_eq!(rules[0].id, "legacy-1");
2054 let event = state
2055 .recent_audit_events()
2056 .last()
2057 .cloned()
2058 .expect("audit event");
2059 assert_eq!(event.details["operation"], "rule.intercept_legacy_upsert");
2060 assert_eq!(event.details["details"]["command"], "set_intercept_rule");
2061 }
2062
2063 #[tokio::test]
2064 async fn resolve_intercept_failure_records_failed_audit_event() {
2065 let state = CoreState::new(None).await;
2066
2067 let result = state
2068 .resolve_intercept_with_modifications_from(
2069 AuditActor::Probe,
2070 "missing-flow:request".to_string(),
2071 "drop",
2072 None,
2073 )
2074 .await;
2075
2076 assert!(result.is_err());
2077 let events = state.recent_audit_events();
2078 let event = events.last().expect("audit event should exist");
2079 assert_eq!(event.actor, AuditActor::Probe);
2080 assert_eq!(event.kind, AuditEventKind::InterceptResolved);
2081 assert_eq!(event.outcome, AuditOutcome::Failed);
2082 assert_eq!(event.details["action"], "drop");
2083 assert!(
2084 event.details["error"]
2085 .as_str()
2086 .unwrap_or_default()
2087 .contains("Interception not found")
2088 );
2089 }
2090
2091 #[tokio::test]
2092 async fn lifecycle_prepare_start_and_stop_updates_snapshot() {
2093 let state = CoreState::new(None).await;
2094 let (shutdown_tx, shutdown_rx) = oneshot::channel();
2095
2096 state
2097 .prepare_start(8080, shutdown_tx)
2098 .expect("prepare start should succeed");
2099 let lifecycle = state.lifecycle();
2100 assert_eq!(lifecycle.phase, RuntimeLifecyclePhase::Starting);
2101 assert_eq!(lifecycle.port, Some(8080));
2102 assert!(lifecycle.started_at_ms.is_none());
2103 assert!(lifecycle.last_error.is_none());
2104
2105 assert_eq!(
2106 state.stop_proxy().expect("stop should succeed"),
2107 ProxyStopResult::Stopping
2108 );
2109 let lifecycle = state.lifecycle();
2110 assert_eq!(lifecycle.phase, RuntimeLifecyclePhase::Stopping);
2111 assert_eq!(lifecycle.port, Some(8080));
2112 assert!(shutdown_rx.await.is_ok());
2113 }
2114
2115 #[tokio::test]
2116 async fn status_snapshot_derives_runtime_facing_fields() {
2117 let state = CoreState::new(None).await;
2118 let (shutdown_tx, _shutdown_rx) = oneshot::channel();
2119 state
2120 .prepare_start(8080, shutdown_tx)
2121 .expect("prepare start should succeed");
2122
2123 let status = state.status_snapshot();
2124 assert_eq!(status.phase, RuntimeLifecyclePhase::Starting);
2125 assert!(status.running);
2126 assert_eq!(status.port, Some(8080));
2127 assert!(status.uptime.is_none());
2128 assert!(status.last_error.is_none());
2129 }
2130
2131 #[tokio::test]
2132 async fn status_report_combines_status_and_metrics() {
2133 let state = CoreState::new(None).await;
2134 let report = state.status_report().await;
2135
2136 assert_eq!(report.status.phase, RuntimeLifecyclePhase::Created);
2137 assert!(!report.status.running);
2138 assert_eq!(report.metrics.intercepts_pending, 0);
2139 assert_eq!(report.metrics.ws_pending_messages, 0);
2140 assert_eq!(report.metrics.oldest_intercept_age_ms, None);
2141 assert_eq!(report.metrics.oldest_ws_message_age_ms, None);
2142 assert_eq!(report.metrics.audit_events_total, 0);
2143 assert_eq!(report.metrics.audit_events_failed, 0);
2144 assert_eq!(report.metrics.flow_events_lagged_total, 0);
2145 assert_eq!(report.metrics.audit_events_lagged_total, 0);
2146 }
2147
2148 #[test]
2149 fn proxy_config_new_and_transport_setters_preserve_values() {
2150 let config = ProxyConfig::new(
2151 8080,
2152 std::path::PathBuf::from("/tmp/ca_cert.pem"),
2153 std::path::PathBuf::from("/tmp/ca_key.pem"),
2154 )
2155 .with_transparent(true)
2156 .with_udp_tproxy_port(Some(15000));
2157
2158 assert_eq!(config.port, 8080);
2159 assert_eq!(
2160 config.ca_cert_path,
2161 std::path::PathBuf::from("/tmp/ca_cert.pem")
2162 );
2163 assert_eq!(
2164 config.ca_key_path,
2165 std::path::PathBuf::from("/tmp/ca_key.pem")
2166 );
2167 assert!(config.transparent);
2168 assert_eq!(config.udp_tproxy_port, Some(15000));
2169 }
2170
2171 #[test]
2172 fn proxy_config_from_app_data_dir_creates_default_paths() {
2173 let unique = SystemTime::now()
2174 .duration_since(UNIX_EPOCH)
2175 .expect("clock drift")
2176 .as_nanos();
2177 let dir = std::env::temp_dir().join(format!("relaycraft-runtime-config-{}", unique));
2178
2179 let config =
2180 ProxyConfig::from_app_data_dir(dir.clone(), 8899).expect("config should build");
2181
2182 assert!(dir.exists());
2183 assert_eq!(config.port, 8899);
2184 assert_eq!(config.ca_cert_path, dir.join("ca_cert.pem"));
2185 assert_eq!(config.ca_key_path, dir.join("ca_key.pem"));
2186 assert!(!config.transparent);
2187 assert!(config.udp_tproxy_port.is_none());
2188 }
2189
2190 #[tokio::test]
2191 async fn intercept_snapshot_maps_pending_counts() {
2192 let state = CoreState::new(None).await;
2193 let snapshot = state.intercept_snapshot().await;
2194
2195 assert_eq!(snapshot.pending_count, 0);
2196 assert_eq!(snapshot.ws_pending_count, 0);
2197 }
2198
2199 #[tokio::test]
2200 async fn audit_snapshot_returns_latest_events_in_order() {
2201 let state = CoreState::new(None).await;
2202 state.record_audit_event(AuditEvent::new(
2203 AuditActor::Runtime,
2204 AuditEventKind::RuleChanged,
2205 "first",
2206 AuditOutcome::Success,
2207 json!({ "index": 1 }),
2208 ));
2209 state.record_audit_event(AuditEvent::new(
2210 AuditActor::Http,
2211 AuditEventKind::PolicyUpdated,
2212 "second",
2213 AuditOutcome::Success,
2214 json!({ "index": 2 }),
2215 ));
2216
2217 let snapshot = state.audit_snapshot(1);
2218
2219 assert_eq!(snapshot.events.len(), 1);
2220 assert_eq!(snapshot.events[0].target, "second");
2221 assert_eq!(snapshot.events[0].details["index"], 2);
2222 }
2223
2224 #[tokio::test]
2225 async fn query_audit_snapshot_filters_in_memory_events() {
2226 let state = CoreState::new(None).await;
2227 state.record_audit_event(AuditEvent::new(
2228 AuditActor::Http,
2229 AuditEventKind::RuleChanged,
2230 "rule-1",
2231 AuditOutcome::Success,
2232 json!({ "idx": 1 }),
2233 ));
2234 state.record_audit_event(AuditEvent::new(
2235 AuditActor::Probe,
2236 AuditEventKind::PolicyUpdated,
2237 "policy",
2238 AuditOutcome::Failed,
2239 json!({ "idx": 2 }),
2240 ));
2241
2242 let snapshot = state
2243 .query_audit_snapshot(CoreAuditQuery {
2244 actor: Some(AuditActor::Probe),
2245 kind: Some(AuditEventKind::PolicyUpdated),
2246 outcome: Some(AuditOutcome::Failed),
2247 limit: 10,
2248 ..Default::default()
2249 })
2250 .await;
2251
2252 assert_eq!(snapshot.events.len(), 1);
2253 assert_eq!(snapshot.events[0].actor, AuditActor::Probe);
2254 assert_eq!(snapshot.events[0].kind, AuditEventKind::PolicyUpdated);
2255 assert_eq!(snapshot.events[0].outcome, AuditOutcome::Failed);
2256 }
2257
2258 #[tokio::test]
2259 async fn query_audit_snapshot_reads_persisted_events_when_storage_enabled() {
2260 let state = CoreState::new(Some(sqlite_url())).await;
2261 state.update_policy_from(
2262 AuditActor::Http,
2263 "policy".to_string(),
2264 ProxyPolicy {
2265 transparent_enabled: true,
2266 ..Default::default()
2267 },
2268 );
2269
2270 let mut snapshot = CoreAuditSnapshot { events: Vec::new() };
2271 for _ in 0..10 {
2272 snapshot = state
2273 .query_audit_snapshot(CoreAuditQuery {
2274 actor: Some(AuditActor::Http),
2275 kind: Some(AuditEventKind::PolicyUpdated),
2276 limit: 10,
2277 ..Default::default()
2278 })
2279 .await;
2280 if !snapshot.events.is_empty() {
2281 break;
2282 }
2283 sleep(Duration::from_millis(20)).await;
2284 }
2285
2286 assert!(!snapshot.events.is_empty());
2287 assert_eq!(snapshot.events[0].actor, AuditActor::Http);
2288 assert_eq!(snapshot.events[0].kind, AuditEventKind::PolicyUpdated);
2289 }
2290
2291 #[tokio::test]
2292 async fn prepare_start_rejects_second_active_start() {
2293 let state = CoreState::new(None).await;
2294 let (shutdown_tx, _shutdown_rx) = oneshot::channel();
2295 state
2296 .prepare_start(8080, shutdown_tx)
2297 .expect("first start should succeed");
2298
2299 let (second_tx, _second_rx) = oneshot::channel();
2300 let error = state
2301 .prepare_start(8081, second_tx)
2302 .expect_err("second active start should be rejected");
2303 assert!(error.contains("already"));
2304 }
2305
2306 #[test]
2307 fn update_policy_records_audit_event() {
2308 let runtime = tokio::runtime::Runtime::new().expect("runtime should build");
2309 let state = runtime.block_on(CoreState::new(None));
2310
2311 state.update_policy_from(
2312 AuditActor::Runtime,
2313 "policy".to_string(),
2314 ProxyPolicy {
2315 transparent_enabled: true,
2316 ..Default::default()
2317 },
2318 );
2319
2320 let events = state.recent_audit_events();
2321 let event = events.last().expect("audit event should exist");
2322 assert_eq!(event.kind, AuditEventKind::PolicyUpdated);
2323 assert_eq!(event.outcome, AuditOutcome::Success);
2324 assert_eq!(event.details["transparent_enabled"], true);
2325 }
2326
2327 #[test]
2328 fn patch_policy_updates_redaction_without_replacing_other_fields() {
2329 let runtime = tokio::runtime::Runtime::new().expect("runtime should build");
2330 let state = runtime.block_on(CoreState::new(None));
2331 let original_timeout = state.policy_snapshot().request_timeout_ms;
2332
2333 state.patch_policy_from(
2334 AuditActor::Runtime,
2335 "policy.patch".to_string(),
2336 relay_core_api::policy::ProxyPolicyPatch {
2337 redaction: Some(relay_core_api::policy::RedactionPolicyPatch {
2338 enabled: Some(true),
2339 redact_bodies: Some(true),
2340 ..Default::default()
2341 }),
2342 },
2343 );
2344
2345 let policy = state.policy_snapshot();
2346 assert_eq!(policy.request_timeout_ms, original_timeout);
2347 assert!(policy.redaction.enabled);
2348 assert!(policy.redaction.redact_bodies);
2349
2350 let events = state.recent_audit_events();
2351 let event = events.last().expect("audit event should exist");
2352 assert_eq!(event.kind, AuditEventKind::PolicyUpdated);
2353 assert_eq!(event.details["redaction_enabled"], true);
2354 }
2355
2356 #[tokio::test]
2357 async fn metrics_include_audit_and_lagged_event_counters() {
2358 let state = CoreState::new(None).await;
2359
2360 state.update_policy_from(
2361 AuditActor::Runtime,
2362 "policy".to_string(),
2363 ProxyPolicy::default(),
2364 );
2365 let _ = state
2366 .resolve_intercept_with_modifications_from(
2367 AuditActor::Probe,
2368 "missing-flow:request".to_string(),
2369 "drop",
2370 None,
2371 )
2372 .await;
2373
2374 state.record_flow_events_lagged(3);
2375 state.record_audit_events_lagged(5);
2376
2377 let metrics = state.get_metrics().await;
2378 assert_eq!(metrics.audit_events_total, 2);
2379 assert_eq!(metrics.audit_events_failed, 1);
2380 assert_eq!(metrics.flow_events_lagged_total, 3);
2381 assert_eq!(metrics.audit_events_lagged_total, 5);
2382 }
2383
2384 #[tokio::test]
2385 async fn prometheus_metrics_text_contains_observability_fields() {
2386 let state = CoreState::new(None).await;
2387 state.record_flow_events_lagged(2);
2388 state.record_audit_events_lagged(4);
2389
2390 let text = state.get_metrics_prometheus_text().await;
2391 assert!(text.contains("relay_core_flow_events_lagged_total 2"));
2392 assert!(text.contains("relay_core_audit_events_lagged_total 4"));
2393 assert!(text.contains("relay_core_oldest_intercept_age_ms 0"));
2394 assert!(text.contains("relay_core_oldest_ws_message_age_ms 0"));
2395 }
2396
2397 #[tokio::test]
2398 async fn search_flows_uses_store_with_offset_pagination() {
2399 let state = CoreState::new(Some(sqlite_url())).await;
2400 let flow_a = sample_http_flow("api.example.com", "/a", "GET", 200, 1_700_000_001_000);
2401 let flow_b = sample_http_flow("api.example.com", "/b", "POST", 500, 1_700_000_002_000);
2402 let flow_c = sample_http_flow("api.example.com", "/c", "GET", 201, 1_700_000_003_000);
2403
2404 state.upsert_flow(Box::new(flow_a));
2405 state.upsert_flow(Box::new(flow_b));
2406 state.upsert_flow(Box::new(flow_c));
2407
2408 let mut baseline = Vec::new();
2409 for _ in 0..20 {
2410 baseline = state
2411 .search_flows(FlowQuery {
2412 host: Some("api.example.com".to_string()),
2413 path_contains: None,
2414 method: None,
2415 status_min: None,
2416 status_max: None,
2417 has_error: None,
2418 is_websocket: None,
2419 limit: Some(3),
2420 offset: Some(0),
2421 })
2422 .await;
2423 if baseline.len() == 3 {
2424 break;
2425 }
2426 sleep(Duration::from_millis(20)).await;
2427 }
2428
2429 assert_eq!(baseline.len(), 3);
2430 let page = state
2431 .search_flows(FlowQuery {
2432 host: Some("api.example.com".to_string()),
2433 path_contains: None,
2434 method: None,
2435 status_min: None,
2436 status_max: None,
2437 has_error: None,
2438 is_websocket: None,
2439 limit: Some(1),
2440 offset: Some(1),
2441 })
2442 .await;
2443 assert_eq!(page.len(), 1);
2444 assert_eq!(page[0].id, baseline[1].id);
2445 }
2446
2447 #[tokio::test]
2448 async fn get_flow_falls_back_to_store_after_lru_eviction() {
2449 let state = CoreState::new(Some(sqlite_url())).await;
2450 let first_flow = sample_http_flow(
2451 "persist.example.com",
2452 "/first",
2453 "GET",
2454 200,
2455 1_700_000_010_000,
2456 );
2457 let first_id = first_flow.id.to_string();
2458 state.upsert_flow(Box::new(first_flow));
2459 for i in 0..240 {
2460 state.upsert_flow(Box::new(sample_http_flow(
2461 "persist.example.com",
2462 &format!("/{}", i),
2463 "GET",
2464 200,
2465 1_700_000_020_000 + i,
2466 )));
2467 }
2468
2469 sleep(Duration::from_millis(200)).await;
2470
2471 let loaded = state.get_flow(first_id).await;
2472 assert!(loaded.is_some());
2473 }
2474
2475 #[tokio::test]
2476 async fn search_flows_redacts_summary_url_when_enabled() {
2477 let state = CoreState::new(None).await;
2478 state.update_policy_from(
2479 AuditActor::Runtime,
2480 "policy.redaction".to_string(),
2481 ProxyPolicy {
2482 redaction: RedactionPolicy {
2483 enabled: true,
2484 sensitive_query_keys: vec!["token".to_string()],
2485 redact_bodies: false,
2486 ..Default::default()
2487 },
2488 ..Default::default()
2489 },
2490 );
2491 state.upsert_flow(Box::new(sample_sensitive_http_flow(1_700_000_100_000)));
2492
2493 let mut items = Vec::new();
2494 for _ in 0..20 {
2495 items = state
2496 .search_flows(FlowQuery {
2497 host: Some("api.example.com".to_string()),
2498 path_contains: Some("/private".to_string()),
2499 ..Default::default()
2500 })
2501 .await;
2502 if !items.is_empty() {
2503 break;
2504 }
2505 sleep(Duration::from_millis(20)).await;
2506 }
2507
2508 assert!(!items.is_empty());
2509 let redacted = Url::parse(&items[0].url).expect("summary url should parse");
2510 let token = redacted
2511 .query_pairs()
2512 .find(|(k, _)| k == "token")
2513 .map(|(_, v)| v.to_string());
2514 assert_eq!(token.as_deref(), Some("[REDACTED]"));
2515 }
2516
2517 #[tokio::test]
2518 async fn get_flow_applies_header_query_and_body_redaction_when_enabled() {
2519 let state = CoreState::new(Some(sqlite_url())).await;
2520 state.update_policy_from(
2521 AuditActor::Runtime,
2522 "policy.redaction".to_string(),
2523 ProxyPolicy {
2524 redaction: RedactionPolicy {
2525 enabled: true,
2526 sensitive_header_names: vec![
2527 "authorization".to_string(),
2528 "set-cookie".to_string(),
2529 ],
2530 sensitive_query_keys: vec!["token".to_string()],
2531 redact_bodies: true,
2532 },
2533 ..Default::default()
2534 },
2535 );
2536
2537 let flow = sample_sensitive_http_flow(1_700_000_200_000);
2538 let flow_id = flow.id.to_string();
2539 state.upsert_flow(Box::new(flow));
2540 sleep(Duration::from_millis(80)).await;
2541
2542 let loaded = state.get_flow(flow_id).await.expect("flow should exist");
2543 let Layer::Http(http) = loaded.layer else {
2544 panic!("expected http layer");
2545 };
2546
2547 let auth = http
2548 .request
2549 .headers
2550 .iter()
2551 .find(|(k, _)| k.eq_ignore_ascii_case("authorization"))
2552 .map(|(_, v)| v.as_str());
2553 assert_eq!(auth, Some("[REDACTED]"));
2554
2555 let req_query_token = http
2556 .request
2557 .query
2558 .iter()
2559 .find(|(k, _)| k == "token")
2560 .map(|(_, v)| v.as_str());
2561 assert_eq!(req_query_token, Some("[REDACTED]"));
2562
2563 let req_body = http.request.body.as_ref().map(|b| b.content.as_str());
2564 assert_eq!(req_body, Some("[REDACTED]"));
2565
2566 let response = http.response.expect("response should exist");
2567 let set_cookie = response
2568 .headers
2569 .iter()
2570 .find(|(k, _)| k.eq_ignore_ascii_case("set-cookie"))
2571 .map(|(_, v)| v.as_str());
2572 assert_eq!(set_cookie, Some("[REDACTED]"));
2573 let res_body = response.body.as_ref().map(|b| b.content.as_str());
2574 assert_eq!(res_body, Some("[REDACTED]"));
2575 }
2576
2577 #[test]
2578 fn redact_flow_update_masks_http_body_when_enabled() {
2579 let runtime = tokio::runtime::Runtime::new().expect("runtime should build");
2580 let state = runtime.block_on(CoreState::new(None));
2581 state.update_policy_from(
2582 AuditActor::Runtime,
2583 "policy.redaction".to_string(),
2584 ProxyPolicy {
2585 redaction: RedactionPolicy {
2586 enabled: true,
2587 redact_bodies: true,
2588 ..Default::default()
2589 },
2590 ..Default::default()
2591 },
2592 );
2593
2594 let update = FlowUpdate::HttpBody {
2595 flow_id: "f-1".to_string(),
2596 direction: relay_core_api::flow::Direction::ClientToServer,
2597 body: BodyData {
2598 encoding: "utf-8".to_string(),
2599 content: "super-secret".to_string(),
2600 size: 12,
2601 },
2602 };
2603 let redacted = state.redact_flow_update_for_output(update);
2604 match redacted {
2605 FlowUpdate::HttpBody { body, .. } => assert_eq!(body.content, "[REDACTED]"),
2606 _ => panic!("expected http body update"),
2607 }
2608 }
2609
2610 #[cfg(feature = "script")]
2611 #[tokio::test]
2612 async fn load_script_from_records_audit_event() {
2613 let state = CoreState::new(None).await;
2614
2615 state
2616 .load_script_from(
2617 AuditActor::Tauri,
2618 "tauri.load_script".to_string(),
2619 "globalThis.onRequestHeaders = (_flow) => {};",
2620 )
2621 .await
2622 .expect("script should load");
2623
2624 let events = state.recent_audit_events();
2625 let event = events.last().expect("audit event should exist");
2626 assert_eq!(event.actor, AuditActor::Tauri);
2627 assert_eq!(event.kind, AuditEventKind::ScriptReloaded);
2628 assert_eq!(event.outcome, AuditOutcome::Success);
2629 assert_eq!(event.target, "tauri.load_script");
2630 }
2631}