sentinel_agent_protocol/
lib.rs

1// Allow large enum variants in generated protobuf code
2#![allow(clippy::large_enum_variant)]
3
4//! Agent protocol for Sentinel proxy
5//!
6//! This crate defines the protocol for communication between the proxy dataplane
7//! and external processing agents (WAF, auth, rate limiting, custom logic).
8//!
9//! The protocol is inspired by SPOE (Stream Processing Offload Engine) and Envoy's ext_proc,
10//! designed for bounded, predictable behavior with strong failure isolation.
11//!
12//! # Architecture
13//!
14//! - [`AgentClient`]: Client for sending events to agents from the proxy
15//! - [`AgentServer`]: Server for implementing agent handlers
16//! - [`AgentHandler`]: Trait for implementing agent logic
17//! - [`AgentResponse`]: Response from agent with decision and mutations
18//!
19//! # Transports
20//!
21//! Two transport options are supported:
22//!
23//! ## Unix Domain Sockets (Default)
24//! Messages are length-prefixed JSON:
25//! - 4-byte big-endian length prefix
26//! - JSON payload (max 10MB)
27//!
28//! ## gRPC
29//! Binary protocol using Protocol Buffers over HTTP/2:
30//! - Better performance for high-throughput scenarios
31//! - Native support for TLS/mTLS
32//! - Language-agnostic (agents can be written in any language with gRPC support)
33//!
34//! # Example: Client Usage (Unix Socket)
35//!
36//! ```ignore
37//! use sentinel_agent_protocol::{AgentClient, EventType, RequestHeadersEvent};
38//!
39//! let mut client = AgentClient::unix_socket("my-agent", "/tmp/agent.sock", timeout).await?;
40//! let response = client.send_event(EventType::RequestHeaders, &event).await?;
41//! ```
42//!
43//! # Example: Client Usage (gRPC)
44//!
45//! ```ignore
46//! use sentinel_agent_protocol::{AgentClient, EventType, RequestHeadersEvent};
47//!
48//! let mut client = AgentClient::grpc("my-agent", "http://localhost:50051", timeout).await?;
49//! let response = client.send_event(EventType::RequestHeaders, &event).await?;
50//! ```
51//!
52//! # Example: Server Implementation
53//!
54//! ```ignore
55//! use sentinel_agent_protocol::{AgentServer, AgentHandler, AgentResponse};
56//!
57//! struct MyAgent;
58//!
59//! #[async_trait]
60//! impl AgentHandler for MyAgent {
61//!     async fn on_request_headers(&self, event: RequestHeadersEvent) -> AgentResponse {
62//!         // Implement your logic here
63//!         AgentResponse::default_allow()
64//!     }
65//! }
66//!
67//! let server = AgentServer::new("my-agent", "/tmp/agent.sock", Box::new(MyAgent));
68//! server.run().await?;
69//! ```
70
71#![allow(dead_code)]
72
73mod client;
74mod errors;
75mod protocol;
76mod server;
77
78/// gRPC protocol definitions generated from proto/agent.proto
79pub mod grpc {
80    tonic::include_proto!("sentinel.agent.v1");
81}
82
83// Re-export error types
84pub use errors::AgentProtocolError;
85
86// Re-export protocol types
87pub use protocol::{
88    AgentRequest, AgentResponse, AuditMetadata, BodyMutation, Decision, EventType, HeaderOp,
89    RequestBodyChunkEvent, RequestCompleteEvent, RequestHeadersEvent, RequestMetadata,
90    ResponseBodyChunkEvent, ResponseHeadersEvent, WebSocketDecision, WebSocketFrameEvent,
91    WebSocketOpcode, MAX_MESSAGE_SIZE, PROTOCOL_VERSION,
92};
93
94// Re-export client
95pub use client::AgentClient;
96
97// Re-export server and handler
98pub use server::{
99    AgentHandler, AgentServer, DenylistAgent, EchoAgent, GrpcAgentHandler, GrpcAgentServer,
100};
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use std::collections::HashMap;
106    use std::time::Duration;
107    use tempfile::tempdir;
108
109    #[tokio::test]
110    async fn test_agent_protocol_echo() {
111        let dir = tempdir().unwrap();
112        let socket_path = dir.path().join("test.sock");
113
114        // Start echo agent server
115        let server = AgentServer::new("test-echo", socket_path.clone(), Box::new(EchoAgent));
116
117        let server_handle = tokio::spawn(async move {
118            server.run().await.unwrap();
119        });
120
121        // Give server time to start
122        tokio::time::sleep(Duration::from_millis(100)).await;
123
124        // Connect client
125        let mut client =
126            AgentClient::unix_socket("test-client", &socket_path, Duration::from_secs(5))
127                .await
128                .unwrap();
129
130        // Send request headers event
131        let event = RequestHeadersEvent {
132            metadata: RequestMetadata {
133                correlation_id: "test-123".to_string(),
134                request_id: "req-456".to_string(),
135                client_ip: "127.0.0.1".to_string(),
136                client_port: 12345,
137                server_name: Some("example.com".to_string()),
138                protocol: "HTTP/1.1".to_string(),
139                tls_version: None,
140                tls_cipher: None,
141                route_id: Some("default".to_string()),
142                upstream_id: Some("backend".to_string()),
143                timestamp: chrono::Utc::now().to_rfc3339(),
144            },
145            method: "GET".to_string(),
146            uri: "/test".to_string(),
147            headers: HashMap::new(),
148        };
149
150        let response = client
151            .send_event(EventType::RequestHeaders, &event)
152            .await
153            .unwrap();
154
155        // Check response
156        assert_eq!(response.decision, Decision::Allow);
157        assert_eq!(response.request_headers.len(), 1);
158
159        // Clean up
160        client.close().await.unwrap();
161        server_handle.abort();
162    }
163
164    #[tokio::test]
165    async fn test_agent_protocol_denylist() {
166        let dir = tempdir().unwrap();
167        let socket_path = dir.path().join("denylist.sock");
168
169        // Start denylist agent server
170        let agent = DenylistAgent::new(vec!["/admin".to_string()], vec!["10.0.0.1".to_string()]);
171        let server = AgentServer::new("test-denylist", socket_path.clone(), Box::new(agent));
172
173        let server_handle = tokio::spawn(async move {
174            server.run().await.unwrap();
175        });
176
177        // Give server time to start
178        tokio::time::sleep(Duration::from_millis(100)).await;
179
180        // Connect client
181        let mut client =
182            AgentClient::unix_socket("test-client", &socket_path, Duration::from_secs(5))
183                .await
184                .unwrap();
185
186        // Test blocked path
187        let event = RequestHeadersEvent {
188            metadata: RequestMetadata {
189                correlation_id: "test-123".to_string(),
190                request_id: "req-456".to_string(),
191                client_ip: "127.0.0.1".to_string(),
192                client_port: 12345,
193                server_name: Some("example.com".to_string()),
194                protocol: "HTTP/1.1".to_string(),
195                tls_version: None,
196                tls_cipher: None,
197                route_id: Some("default".to_string()),
198                upstream_id: Some("backend".to_string()),
199                timestamp: chrono::Utc::now().to_rfc3339(),
200            },
201            method: "GET".to_string(),
202            uri: "/admin/secret".to_string(),
203            headers: HashMap::new(),
204        };
205
206        let response = client
207            .send_event(EventType::RequestHeaders, &event)
208            .await
209            .unwrap();
210
211        // Check response is blocked
212        match response.decision {
213            Decision::Block { status, .. } => assert_eq!(status, 403),
214            _ => panic!("Expected block decision"),
215        }
216
217        // Clean up
218        client.close().await.unwrap();
219        server_handle.abort();
220    }
221
222    #[test]
223    fn test_body_mutation_types() {
224        // Test pass-through mutation
225        let pass_through = BodyMutation::pass_through(0);
226        assert!(pass_through.is_pass_through());
227        assert!(!pass_through.is_drop());
228        assert_eq!(pass_through.chunk_index, 0);
229
230        // Test drop mutation
231        let drop = BodyMutation::drop_chunk(1);
232        assert!(!drop.is_pass_through());
233        assert!(drop.is_drop());
234        assert_eq!(drop.chunk_index, 1);
235
236        // Test replace mutation
237        let replace = BodyMutation::replace(2, "modified content".to_string());
238        assert!(!replace.is_pass_through());
239        assert!(!replace.is_drop());
240        assert_eq!(replace.chunk_index, 2);
241        assert_eq!(replace.data, Some("modified content".to_string()));
242    }
243
244    #[test]
245    fn test_agent_response_streaming() {
246        // Test needs_more_data response
247        let response = AgentResponse::needs_more_data();
248        assert!(response.needs_more);
249        assert_eq!(response.decision, Decision::Allow);
250
251        // Test response with body mutation
252        let mutation = BodyMutation::replace(0, "new content".to_string());
253        let response = AgentResponse::default_allow().with_request_body_mutation(mutation.clone());
254        assert!(!response.needs_more);
255        assert!(response.request_body_mutation.is_some());
256        assert_eq!(
257            response.request_body_mutation.unwrap().data,
258            Some("new content".to_string())
259        );
260
261        // Test set_needs_more
262        let response = AgentResponse::default_allow().set_needs_more(true);
263        assert!(response.needs_more);
264    }
265}