zentinel-proxy 0.6.11

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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# Agent Integration

External processing integration for WAF, auth, and custom logic.

## Overview

Agents are external processes that can inspect and mutate requests/responses at various lifecycle phases. This SPOE/ext_proc-inspired design keeps complex processing logic out of the core proxy while maintaining low latency.

## Architecture

```
┌─────────────────────────────────────────────────────────────────────┐
│                        Zentinel Proxy                                │
│                                                                      │
│  ┌────────────────────────────────────────────────────────────────┐ │
│  │                     AgentManager                                │ │
│  │                                                                 │ │
│  │   ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌─────────┐      │ │
│  │   │  WAF    │   │  Auth   │   │ Custom  │   │   Log   │      │ │
│  │   │ Agent   │   │ Agent   │   │ Agent   │   │ Agent   │      │ │
│  │   └────┬────┘   └────┬────┘   └────┬────┘   └────┬────┘      │ │
│  │        │             │             │             │            │ │
│  │   ┌────┴────┐   ┌────┴────┐   ┌────┴────┐   ┌────┴────┐      │ │
│  │   │Semaphore│   │Semaphore│   │Semaphore│   │Semaphore│      │ │
│  │   │  (100)  │   │  (100)  │   │  (100)  │   │  (100)  │      │ │
│  │   └────┬────┘   └────┬────┘   └────┬────┘   └────┬────┘      │ │
│  │        │             │             │             │            │ │
│  │   ┌────┴────┐   ┌────┴────┐   ┌────┴────┐   ┌────┴────┐      │ │
│  │   │ Circuit │   │ Circuit │   │ Circuit │   │ Circuit │      │ │
│  │   │ Breaker │   │ Breaker │   │ Breaker │   │ Breaker │      │ │
│  │   └────┬────┘   └────┬────┘   └────┬────┘   └────┬────┘      │ │
│  │        │             │             │             │            │ │
│  │   ┌────┴────┐   ┌────┴────┐   ┌────┴────┐   ┌────┴────┐      │ │
│  │   │  Conn   │   │  Conn   │   │  Conn   │   │  Conn   │      │ │
│  │   │  Pool   │   │  Pool   │   │  Pool   │   │  Pool   │      │ │
│  │   └────┬────┘   └────┬────┘   └────┬────┘   └────┬────┘      │ │
│  │        │             │             │             │            │ │
│  └────────┼─────────────┼─────────────┼─────────────┼────────────┘ │
│           │             │             │             │              │
└───────────┼─────────────┼─────────────┼─────────────┼──────────────┘
            │             │             │             │
            ▼             ▼             ▼             ▼
      ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐
      │   WAF    │  │   Auth   │  │  Custom  │  │   Log    │
      │ Process  │  │ Process  │  │ Process  │  │ Process  │
      │  (UDS)   │  │ (gRPC)   │  │  (UDS)   │  │  (UDS)   │
      └──────────┘  └──────────┘  └──────────┘  └──────────┘
```

## Configuration

### Agent Definition

```kdl
agents {
    // Unix Domain Socket transport
    agent "waf-agent" {
        type "waf"
        transport {
            unix-socket "/var/run/waf-agent.sock"
        }
        events ["request-headers", "request-body"]
        timeout-ms 50
        failure-mode "open"
        max-request-body-bytes 1048576

        circuit-breaker {
            failure-threshold 5
            recovery-timeout-secs 30
        }
    }

    // gRPC transport
    agent "auth-agent" {
        type "auth"
        transport {
            grpc {
                address "localhost:50051"
                tls {
                    insecure-skip-verify false
                    ca-cert "/etc/ssl/certs/ca.crt"
                }
            }
        }
        events ["request-headers"]
        timeout-ms 100
        failure-mode "closed"

        circuit-breaker {
            failure-threshold 5
            recovery-timeout-secs 30
        }
    }
}
```

### Attaching Agents to Routes

```kdl
routes {
    route "api" {
        matches {
            path-prefix "/api"
        }
        upstream "backend"
        filters ["auth", "waf"]  // Agent filters
    }
}

filters {
    filter "auth" {
        type "agent"
        agent "auth-agent"
        phase "request"
        failure-mode "closed"
    }

    filter "waf" {
        type "agent"
        agent "waf-agent"
        phase "request"
        failure-mode "open"
    }
}
```

## Event Model

### Event Types

| Event | Phase | Description |
|-------|-------|-------------|
| `request-headers` | Request | Called after headers parsed, before body |
| `request-body` | Request | Called with request body (buffered or streamed) |
| `request-body-chunk` | Request | Called per chunk for streaming bodies |
| `response-headers` | Response | Called after upstream response headers |
| `response-body` | Response | Called with response body |
| `response-body-chunk` | Response | Called per chunk for streaming responses |
| `log` | Logging | Called at request completion for logging |
| `configure` | Startup | Called at startup/reload for agent config |

### Event Flow

```
        Request Phase                    Response Phase
             │                                 │
             ▼                                 ▼
    ┌─────────────────┐              ┌─────────────────┐
    │ request-headers │              │ response-headers│
    └────────┬────────┘              └────────┬────────┘
             │                                 │
             ▼                                 ▼
    ┌─────────────────┐              ┌─────────────────┐
    │  request-body   │              │  response-body  │
    │ (or body-chunk) │              │ (or body-chunk) │
    └────────┬────────┘              └────────┬────────┘
             │                                 │
             └──────────┬──────────────────────┘
                 ┌────────────┐
                 │    log     │
                 └────────────┘
```

## Decision Model

### Decision Types

```rust
pub enum AgentDecision {
    // Allow request to continue
    Allow {
        mutations: Option<Mutations>,
        tags: Vec<String>,
    },

    // Block the request
    Block {
        status_code: u16,
        body: Option<String>,
        headers: HashMap<String, String>,
        reason: String,
        rule_id: Option<String>,
    },

    // Redirect the client
    Redirect {
        location: String,
        status_code: u16,  // 301, 302, 307, 308
    },

    // Challenge the client (e.g., CAPTCHA)
    Challenge {
        challenge_type: String,
        challenge_url: String,
    },
}
```

### Mutations

```rust
pub struct Mutations {
    // Request header modifications
    pub request_headers: HeaderMutations,

    // Response header modifications
    pub response_headers: HeaderMutations,

    // Request body replacement (if buffered)
    pub request_body: Option<Bytes>,

    // Response body replacement (if buffered)
    pub response_body: Option<Bytes>,

    // Routing metadata
    pub routing: Option<RoutingMutations>,
}

pub struct HeaderMutations {
    pub set: HashMap<String, String>,
    pub append: HashMap<String, Vec<String>>,
    pub remove: Vec<String>,
}

pub struct RoutingMutations {
    pub upstream_override: Option<String>,
    pub route_override: Option<String>,
    pub tags: Vec<String>,
}
```

## Failure Handling

### Failure Modes

| Mode | Behavior |
|------|----------|
| `open` | Allow request if agent fails (fail-open) |
| `closed` | Block request if agent fails (fail-closed) |

### Circuit Breaker

Each agent has an independent circuit breaker:

```
┌────────────────────────────────────────────────────────┐
│                  Circuit Breaker                        │
├────────────────────────────────────────────────────────┤
│                                                         │
│   CLOSED ──── failures >= threshold ───▶ OPEN          │
│      ▲                                     │            │
│      │                                     │            │
│      │                           timeout   │            │
│      │                                     ▼            │
│      │                               HALF-OPEN         │
│      │                                     │            │
│      └─────── success >= threshold ────────┘            │
│                                                         │
│   Config:                                               │
│   - failure_threshold: 5                                │
│   - success_threshold: 2                                │
│   - timeout_secs: 30                                    │
│                                                         │
└────────────────────────────────────────────────────────┘
```

### Timeout Handling

```kdl
agent "waf-agent" {
    // Hard timeout for all agent calls
    timeout-ms 50

    // Per-event timeouts (optional, overrides global)
    event-timeouts {
        request-headers 30
        request-body 100
        response-headers 30
    }
}
```

## Queue Isolation

Each agent has its own concurrency semaphore to prevent "noisy neighbor" problems:

```
┌─────────────────────────────────────────────────────────┐
│                Queue Isolation                           │
├─────────────────────────────────────────────────────────┤
│                                                          │
│  Request 1 ──▶ [WAF Semaphore: 99/100] ──▶ WAF Agent   │
│  Request 2 ──▶ [Auth Semaphore: 98/100] ──▶ Auth Agent │
│  Request 3 ──▶ [WAF Semaphore: 98/100] ──▶ WAF Agent   │
│                                                          │
│  If WAF agent is slow:                                   │
│  - WAF semaphore fills up                                │
│  - Auth agent unaffected (own semaphore)                │
│  - Request 4 to WAF waits or times out                  │
│  - Request 5 to Auth proceeds normally                  │
│                                                          │
└─────────────────────────────────────────────────────────┘
```

Configuration:

```kdl
agent "waf-agent" {
    max-concurrent-calls 100  // Semaphore size
}
```

## Body Handling

### Body Modes

| Mode | Description | Use Case |
|------|-------------|----------|
| `buffer` | Buffer entire body before calling agent | WAF inspection |
| `stream` | Stream body chunks to agent | Large uploads |
| `skip` | Don't send body to agent | Header-only checks |

### Configuration

```kdl
agent "waf-agent" {
    events ["request-headers", "request-body"]

    body-handling {
        mode "buffer"
        max-bytes 1048576  // 1MB limit
        content-types [
            "application/json",
            "application/x-www-form-urlencoded",
            "multipart/form-data"
        ]
    }
}
```

### Streaming Body Handling

For large bodies, use chunk-based processing:

```kdl
agent "content-filter" {
    events ["request-headers", "request-body-chunk"]

    body-handling {
        mode "stream"
        chunk-size 65536  // 64KB chunks
        chunk-timeout-ms 5000
    }
}
```

## Connection Pooling

Each agent uses the v2 protocol's built-in connection pool with configurable
connections per agent, load balancing, and health checking. The pool is managed
internally by the agent and handles reconnection automatically.

Configuration:

```kdl
agent "waf-agent" {
    pool {
        connections-per-agent 4
        load-balance-strategy "round_robin"
        connect-timeout-ms 5000
        health-check-interval-ms 10000
    }
}
```

## Metrics

Agent metrics are exported for monitoring:

```
# Call latency
zentinel_agent_latency_ms{agent="waf-agent", event="request-headers", quantile="0.99"} 12.5

# Call counts
zentinel_agent_calls_total{agent="waf-agent", event="request-headers", result="success"} 10000
zentinel_agent_calls_total{agent="waf-agent", event="request-headers", result="timeout"} 5
zentinel_agent_calls_total{agent="waf-agent", event="request-headers", result="error"} 2

# Circuit breaker state
zentinel_agent_circuit_breaker_state{agent="waf-agent"} 0  # 0=closed, 1=open, 2=half-open
zentinel_agent_circuit_breaker_opens_total{agent="waf-agent"} 3

# Queue depth
zentinel_agent_queue_depth{agent="waf-agent"} 5
zentinel_agent_queue_rejections_total{agent="waf-agent"} 0

# Decision counts
zentinel_agent_decisions_total{agent="waf-agent", decision="allow"} 9990
zentinel_agent_decisions_total{agent="waf-agent", decision="block"} 10
```

## Multi-Agent Pipeline

When multiple agents are attached to a route, they form a pipeline:

```
Request
┌─────────────┐
│   Agent 1   │──── BLOCK ────▶ Return block response
│   (Auth)    │
└──────┬──────┘
       │ ALLOW
┌─────────────┐
│   Agent 2   │──── BLOCK ────▶ Return block response
│   (WAF)     │
└──────┬──────┘
       │ ALLOW
┌─────────────┐
│   Agent 3   │──── BLOCK ────▶ Return block response
│  (Custom)   │
└──────┬──────┘
       │ ALLOW
   Continue to upstream
```

### Decision Merging

- **First BLOCK wins** - Pipeline stops at first blocking decision
- **Mutations merge** - Header mutations from all agents are combined
- **Tags accumulate** - All agent tags are collected

```rust
pub fn merge_decisions(decisions: Vec<AgentDecision>) -> AgentDecision {
    let mut merged_mutations = Mutations::default();
    let mut merged_tags = Vec::new();

    for decision in decisions {
        match decision {
            AgentDecision::Block { .. } => return decision,
            AgentDecision::Redirect { .. } => return decision,
            AgentDecision::Challenge { .. } => return decision,
            AgentDecision::Allow { mutations, tags } => {
                if let Some(m) = mutations {
                    merged_mutations.merge(m);
                }
                merged_tags.extend(tags);
            }
        }
    }

    AgentDecision::Allow {
        mutations: Some(merged_mutations),
        tags: merged_tags,
    }
}
```

## Example: WAF Agent Integration

Complete configuration for WAF agent:

```kdl
agents {
    agent "waf-agent" {
        type "waf"
        transport {
            unix-socket "/var/run/waf-agent.sock"
        }
        events ["request-headers", "request-body"]
        timeout-ms 50
        failure-mode "open"

        body-handling {
            mode "buffer"
            max-bytes 1048576
            content-types [
                "application/json",
                "application/x-www-form-urlencoded",
                "multipart/form-data",
                "text/xml",
                "application/xml"
            ]
        }

        circuit-breaker {
            failure-threshold 5
            recovery-timeout-secs 30
        }

        connection-pool {
            max-connections 10
            idle-timeout-secs 60
        }

        max-concurrent-calls 100
    }
}

filters {
    filter "waf" {
        type "agent"
        agent "waf-agent"
        phase "request"
        failure-mode "open"
    }
}

routes {
    route "protected-api" {
        matches {
            path-prefix "/api"
        }
        upstream "backend"
        filters ["waf"]
        waf-enabled true
    }
}
```

## Example: Auth Agent Integration

Complete configuration for authentication agent:

```kdl
agents {
    agent "auth-agent" {
        type "auth"
        transport {
            grpc {
                address "localhost:50051"
                tls {
                    ca-cert "/etc/ssl/certs/ca.crt"
                }
            }
        }
        events ["request-headers"]
        timeout-ms 100
        failure-mode "closed"  // Block if auth fails

        circuit-breaker {
            failure-threshold 5
            recovery-timeout-secs 30
        }
    }
}

filters {
    filter "auth" {
        type "agent"
        agent "auth-agent"
        phase "request"
        failure-mode "closed"
    }
}

routes {
    route "authenticated-api" {
        matches {
            path-prefix "/api/v1"
        }
        upstream "backend"
        filters ["auth"]
    }

    route "public-api" {
        matches {
            path-prefix "/public"
        }
        upstream "backend"
        // No auth filter
    }
}
```

## Building Custom Agents

See the [`agent-protocol`](../../agent-protocol/README.md) crate for:

- Protocol specification
- Handler trait implementation
- Client and server libraries
- Example agents