grapsus-proxy 0.5.12

A security-first reverse proxy built on Pingora with sleepable ops at the edge
Documentation
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Integration tests for Grapsus proxy.
//!
//! These tests verify the end-to-end flow from configuration loading
//! through agent processing to proxy operation.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tempfile::tempdir;

use grapsus_agent_protocol::v2::server::AgentHandlerV2;
use grapsus_agent_protocol::v2::uds::AgentClientV2Uds;
use grapsus_agent_protocol::v2::uds_server::UdsAgentServerV2;
use grapsus_agent_protocol::v2::AgentCapabilities;
use grapsus_agent_protocol::{
    AgentResponse, AuditMetadata, Decision, HeaderOp, RequestHeadersEvent, RequestMetadata,
};
use grapsus_common::CorrelationId;
use grapsus_config::Config;
use grapsus_proxy::agents::AgentDecision;

// ============================================================================
// Test Agent Implementation
// ============================================================================

/// Test agent that adds headers and tracks processed requests.
struct TestAgent {
    name: String,
}

impl TestAgent {
    fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }
}

#[async_trait::async_trait]
impl AgentHandlerV2 for TestAgent {
    fn capabilities(&self) -> AgentCapabilities {
        AgentCapabilities::new("test-agent", "Test Agent", "0.1.0")
    }

    async fn on_request_headers(&self, event: RequestHeadersEvent) -> AgentResponse {
        AgentResponse::default_allow()
            .add_request_header(HeaderOp::Set {
                name: format!("X-Agent-{}", self.name),
                value: event.metadata.correlation_id.clone(),
            })
            .with_audit(AuditMetadata {
                tags: vec![format!("agent:{}", self.name)],
                ..Default::default()
            })
    }
}

/// Blocking agent for testing failure modes.
struct BlockingAgent {
    block_paths: Vec<String>,
}

impl BlockingAgent {
    fn new(block_paths: Vec<String>) -> Self {
        Self { block_paths }
    }
}

#[async_trait::async_trait]
impl AgentHandlerV2 for BlockingAgent {
    fn capabilities(&self) -> AgentCapabilities {
        AgentCapabilities::new("blocking-agent", "Blocking Agent", "0.1.0")
    }

    async fn on_request_headers(&self, event: RequestHeadersEvent) -> AgentResponse {
        for path in &self.block_paths {
            if event.uri.starts_with(path) {
                return AgentResponse::block(403, Some("Blocked by test agent".to_string()))
                    .with_audit(AuditMetadata {
                        tags: vec!["blocked".to_string()],
                        reason_codes: vec!["TEST_BLOCK".to_string()],
                        ..Default::default()
                    });
            }
        }
        AgentResponse::default_allow()
    }
}

// ============================================================================
// Configuration Integration Tests
// ============================================================================

#[test]
fn test_config_loading_from_kdl() {
    let kdl_config = r#"
        server {
            worker-threads 4
        }

        listeners {
            listener "http" {
                address "0.0.0.0:8080"
                protocol "http"
            }
        }

        upstreams {
            upstream "backend" {
                target "127.0.0.1:3000"
            }
        }

        routes {
            route "api" {
                matches {
                    path-prefix "/api"
                }
                upstream "backend"
            }
        }
    "#;

    let config = Config::from_kdl(kdl_config).expect("Config should parse");

    assert_eq!(config.server.worker_threads, 4);
    assert_eq!(config.listeners.len(), 1);
    assert_eq!(config.upstreams.len(), 1);
    assert_eq!(config.routes.len(), 1);
}

#[test]
fn test_config_with_multiple_upstreams() {
    let kdl_config = r#"
        server {
            worker-threads 2
        }

        listeners {
            listener "http" {
                address "0.0.0.0:8080"
                protocol "http"
            }
        }

        upstreams {
            upstream "backend1" {
                target "127.0.0.1:3000"
            }
            upstream "backend2" {
                target "127.0.0.1:3001"
                target "127.0.0.1:3002" weight=2
            }
        }

        routes {
            route "api" {
                matches {
                    path-prefix "/api"
                }
                upstream "backend1"
            }
        }
    "#;

    let config = Config::from_kdl(kdl_config).expect("Config should parse");

    assert_eq!(config.upstreams.len(), 2);
    assert!(config.upstreams.contains_key("backend1"));
    assert!(config.upstreams.contains_key("backend2"));
    assert_eq!(config.upstreams["backend2"].targets.len(), 2);
}

#[test]
fn test_config_validation_missing_upstream() {
    // Config with missing upstream reference should fail validation
    let kdl_config = r#"
        server {
            worker-threads 2
        }

        listeners {
            listener "http" {
                address "0.0.0.0:8080"
                protocol "http"
            }
        }

        routes {
            route "api" {
                matches {
                    path-prefix "/api"
                }
                upstream "nonexistent"
            }
        }
    "#;

    let result = Config::from_kdl(kdl_config);
    // This should fail validation because "nonexistent" upstream doesn't exist
    assert!(
        result.is_err() || result.unwrap().validate().is_err(),
        "Config with missing upstream should fail"
    );
}

// ============================================================================
// Agent Protocol Integration Tests
// ============================================================================

#[tokio::test]
async fn test_agent_server_client_roundtrip() {
    let dir = tempdir().unwrap();
    let socket_path = dir.path().join("test-agent.sock");

    // Start test agent server
    let server = UdsAgentServerV2::new(
        "test-agent",
        socket_path.clone(),
        Box::new(TestAgent::new("Test")),
    );

    let server_handle = tokio::spawn(async move {
        let _ = server.run().await;
    });

    // Wait for server to start
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Create client and send request
    let client = AgentClientV2Uds::new(
        "test-client",
        socket_path.to_string_lossy(),
        Duration::from_secs(5),
    )
    .await
    .expect("Client should create");
    client.connect().await.expect("Client should connect");

    let event = RequestHeadersEvent {
        metadata: RequestMetadata {
            correlation_id: "test-corr-123".to_string(),
            request_id: "req-456".to_string(),
            client_ip: "127.0.0.1".to_string(),
            client_port: 12345,
            server_name: Some("example.com".to_string()),
            protocol: "HTTP/1.1".to_string(),
            tls_version: None,
            tls_cipher: None,
            route_id: Some("api".to_string()),
            upstream_id: Some("backend".to_string()),
            timestamp: chrono::Utc::now().to_rfc3339(),
            traceparent: None,
        },
        method: "GET".to_string(),
        uri: "/api/users".to_string(),
        headers: HashMap::new(),
    };

    let response = client
        .send_request_headers("test-corr-123", &event)
        .await
        .expect("Should receive response");

    // Verify response
    assert_eq!(response.decision, Decision::Allow);
    assert!(!response.request_headers.is_empty());
    assert!(response.audit.tags.contains(&"agent:Test".to_string()));

    // Cleanup
    client.close().await.unwrap();
    server_handle.abort();
}

#[tokio::test]
async fn test_blocking_agent_rejects_request() {
    let dir = tempdir().unwrap();
    let socket_path = dir.path().join("block-agent.sock");

    // Start blocking agent server
    let server = UdsAgentServerV2::new(
        "block-agent",
        socket_path.clone(),
        Box::new(BlockingAgent::new(vec!["/admin".to_string()])),
    );

    let server_handle = tokio::spawn(async move {
        let _ = server.run().await;
    });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = AgentClientV2Uds::new(
        "test-client",
        socket_path.to_string_lossy(),
        Duration::from_secs(5),
    )
    .await
    .expect("Client should create");
    client.connect().await.expect("Client should connect");

    // Test blocked path
    let event = RequestHeadersEvent {
        metadata: RequestMetadata {
            correlation_id: "test-123".to_string(),
            request_id: "req-456".to_string(),
            client_ip: "127.0.0.1".to_string(),
            client_port: 12345,
            server_name: None,
            protocol: "HTTP/1.1".to_string(),
            tls_version: None,
            tls_cipher: None,
            route_id: None,
            upstream_id: None,
            timestamp: chrono::Utc::now().to_rfc3339(),
            traceparent: None,
        },
        method: "GET".to_string(),
        uri: "/admin/secret".to_string(),
        headers: HashMap::new(),
    };

    let response = client
        .send_request_headers("test-123", &event)
        .await
        .expect("Should receive response");

    match response.decision {
        Decision::Block { status, .. } => {
            assert_eq!(status, 403);
        }
        _ => panic!("Expected block decision"),
    }

    // Test allowed path
    let event = RequestHeadersEvent {
        metadata: RequestMetadata {
            correlation_id: "test-456".to_string(),
            request_id: "req-789".to_string(),
            client_ip: "127.0.0.1".to_string(),
            client_port: 12345,
            server_name: None,
            protocol: "HTTP/1.1".to_string(),
            tls_version: None,
            tls_cipher: None,
            route_id: None,
            upstream_id: None,
            timestamp: chrono::Utc::now().to_rfc3339(),
            traceparent: None,
        },
        method: "GET".to_string(),
        uri: "/api/users".to_string(),
        headers: HashMap::new(),
    };

    let response = client
        .send_request_headers("test-456", &event)
        .await
        .expect("Should receive response");

    assert_eq!(response.decision, Decision::Allow);

    client.close().await.unwrap();
    server_handle.abort();
}

// ============================================================================
// Decision Merging Tests
// ============================================================================

#[test]
fn test_agent_decision_merge_allow() {
    let mut decision1 = AgentDecision::default_allow();
    let decision2 = AgentDecision::default_allow();

    decision1.merge(decision2);
    assert!(decision1.is_allow());
}

#[test]
fn test_agent_decision_merge_block_wins() {
    let mut decision1 = AgentDecision::default_allow();
    let decision2 = AgentDecision::block(403, "Forbidden");

    decision1.merge(decision2);
    assert!(!decision1.is_allow());
}

#[test]
fn test_agent_decision_headers_accumulate() {
    use grapsus_agent_protocol::HeaderOp;

    let mut decision1 = AgentDecision::default_allow();
    decision1.request_headers.push(HeaderOp::Set {
        name: "X-Header-1".to_string(),
        value: "value1".to_string(),
    });

    let mut decision2 = AgentDecision::default_allow();
    decision2.request_headers.push(HeaderOp::Set {
        name: "X-Header-2".to_string(),
        value: "value2".to_string(),
    });

    decision1.merge(decision2);

    assert!(decision1.is_allow());
    assert_eq!(decision1.request_headers.len(), 2);
}

// ============================================================================
// Multi-file Config Tests
// ============================================================================

#[test]
fn test_config_from_file() {
    let dir = tempdir().unwrap();
    let config_path = dir.path().join("grapsus.kdl");

    // Create config file
    std::fs::write(
        &config_path,
        r#"
        server {
            worker-threads 8
        }

        listeners {
            listener "http" {
                address "0.0.0.0:8080"
                protocol "http"
            }
        }

        upstreams {
            upstream "backend" {
                target "127.0.0.1:3000"
            }
        }

        routes {
            route "api" {
                matches {
                    path-prefix "/api"
                }
                upstream "backend"
            }
        }
    "#,
    )
    .unwrap();

    let config = Config::from_file(&config_path).expect("Should load config from file");

    assert_eq!(config.server.worker_threads, 8);
    assert_eq!(config.upstreams.len(), 1);
    assert_eq!(config.routes.len(), 1);
}

// ============================================================================
// Type Safety Tests
// ============================================================================

#[test]
fn test_correlation_id_type_safety() {
    let corr_id = CorrelationId::new();
    let corr_id_from_string = CorrelationId::from_string("my-correlation-id");

    // These are different types that shouldn't be mixed
    assert_ne!(corr_id.as_str(), corr_id_from_string.as_str());
    assert_eq!(corr_id_from_string.as_str(), "my-correlation-id");
}

#[test]
fn test_route_and_upstream_ids_distinct() {
    use grapsus_common::{RouteId, UpstreamId};

    let route_id = RouteId::new("my-route");
    let upstream_id = UpstreamId::new("my-upstream");

    // These are distinct types - can't accidentally mix them
    assert_eq!(route_id.as_str(), "my-route");
    assert_eq!(upstream_id.as_str(), "my-upstream");
}

// ============================================================================
// Registry Tests
// ============================================================================

#[tokio::test]
async fn test_registry_concurrent_access() {
    use grapsus_common::Registry;

    let registry: Registry<String> = Registry::new();

    // Concurrent insertions
    let mut handles = vec![];
    for i in 0..10 {
        let registry = registry.clone();
        handles.push(tokio::spawn(async move {
            registry
                .insert(format!("key-{}", i), Arc::new(format!("value-{}", i)))
                .await;
        }));
    }

    for handle in handles {
        handle.await.unwrap();
    }

    // Verify all insertions
    for i in 0..10 {
        let value = registry.get(&format!("key-{}", i)).await;
        assert_eq!(value, Some(Arc::new(format!("value-{}", i))));
    }
}

// ============================================================================
// Error Type Tests
// ============================================================================

#[test]
fn test_grapsus_error_display() {
    use grapsus_common::GrapsusError;

    let error = GrapsusError::Config {
        message: "Invalid configuration".to_string(),
        source: None,
    };

    let display = format!("{}", error);
    assert!(display.contains("Invalid configuration"));
}

#[test]
fn test_grapsus_error_to_http_status() {
    use grapsus_common::GrapsusError;

    let config_error = GrapsusError::Config {
        message: "test".to_string(),
        source: None,
    };
    assert_eq!(config_error.to_http_status(), 500);

    let timeout_error = GrapsusError::Timeout {
        operation: "test".to_string(),
        duration_ms: 1000,
        correlation_id: None,
    };
    assert_eq!(timeout_error.to_http_status(), 504);
}