a3s-gateway 0.2.5

A3S Gateway - AI-native API gateway with reverse proxy, routing, and agent orchestration
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
//! Middleware pipeline — composable request/response transformations
//!
//! Middlewares are applied in order before the request reaches the backend,
//! and in reverse order for the response.

mod auth;
mod body_limit;
pub mod circuit_breaker;
pub mod compress;
mod cors;
mod forward_auth;
mod headers;
mod ip_allow;
pub mod ip_matcher;
pub mod jwt_auth;
mod rate_limit;
#[cfg(feature = "redis")]
mod rate_limit_redis;
mod retry;
mod strip_prefix;
mod tcp_filter;

pub use auth::AuthMiddleware;
pub use body_limit::BodyLimitMiddleware;
pub use circuit_breaker::CircuitBreakerMiddleware;
pub use compress::CompressMiddleware;
pub use cors::CorsMiddleware;
pub use forward_auth::ForwardAuthMiddleware;
pub use headers::HeadersMiddleware;
pub use ip_allow::IpAllowMiddleware;
pub use jwt_auth::JwtAuthMiddleware;
pub use rate_limit::RateLimitMiddleware;
#[cfg(feature = "redis")]
pub use rate_limit_redis::RedisRateLimitMiddleware;
pub use retry::RetryMiddleware;
pub use strip_prefix::StripPrefixMiddleware;
pub use tcp_filter::TcpFilter;

use crate::config::MiddlewareConfig;
use crate::error::{GatewayError, Result};
use async_trait::async_trait;
use http::Response;
use std::collections::HashMap;
use std::sync::Arc;

/// Request context passed through the middleware pipeline
#[derive(Debug, Clone)]
pub struct RequestContext {
    /// Client IP address
    pub client_ip: String,
    /// Entrypoint name
    #[allow(dead_code)]
    pub entrypoint: String,
    /// Router name that matched
    #[cfg_attr(not(feature = "redis"), allow(dead_code))]
    pub router: String,
}

/// Middleware trait — process a request and optionally short-circuit
#[async_trait]
pub trait Middleware: Send + Sync {
    /// Process the request. Return Ok(None) to continue the pipeline,
    /// or Ok(Some(response)) to short-circuit with an immediate response.
    async fn handle_request(
        &self,
        req: &mut http::request::Parts,
        ctx: &RequestContext,
    ) -> Result<Option<Response<Vec<u8>>>>;

    /// Process the response (optional, default is pass-through)
    async fn handle_response(&self, _resp: &mut http::response::Parts) -> Result<()> {
        Ok(())
    }

    /// Middleware name for logging
    fn name(&self) -> &str;
}

/// Ordered middleware pipeline
pub struct Pipeline {
    middlewares: Vec<Arc<dyn Middleware>>,
}

impl Pipeline {
    /// Build a pipeline from middleware names and configurations
    pub fn from_config(
        names: &[String],
        configs: &HashMap<String, MiddlewareConfig>,
    ) -> Result<Self> {
        let mut middlewares: Vec<Arc<dyn Middleware>> = Vec::new();

        for name in names {
            let config = configs.get(name).ok_or_else(|| {
                GatewayError::Config(format!("Middleware '{}' not found in config", name))
            })?;

            let mw: Arc<dyn Middleware> = match config.middleware_type.as_str() {
                "api-key" => Arc::new(AuthMiddleware::api_key(config)?),
                "basic-auth" => Arc::new(AuthMiddleware::basic_auth(config)?),
                "rate-limit" => Arc::new(RateLimitMiddleware::new(config)?),
                "cors" => Arc::new(CorsMiddleware::new(config)),
                "headers" => Arc::new(HeadersMiddleware::new(config)),
                "strip-prefix" => Arc::new(StripPrefixMiddleware::new(config)),
                "ip-allow" => Arc::new(IpAllowMiddleware::new(config)?),
                "retry" => Arc::new(RetryMiddleware::new(config)?),
                "jwt" => Arc::new(JwtAuthMiddleware::new(config)?),
                "circuit-breaker" => Arc::new(CircuitBreakerMiddleware::new(
                    circuit_breaker::CircuitBreakerConfig {
                        failure_threshold: config.failure_threshold.unwrap_or(5),
                        cooldown: std::time::Duration::from_secs(
                            config.cooldown_secs.unwrap_or(30),
                        ),
                        success_threshold: config.success_threshold.unwrap_or(1),
                    },
                )),
                "compress" => Arc::new(CompressMiddleware::default()),
                "body-limit" => Arc::new(BodyLimitMiddleware::new(config)?),
                "forward-auth" => Arc::new(ForwardAuthMiddleware::new(config)?),
                #[cfg(feature = "redis")]
                "rate-limit-redis" => Arc::new(RedisRateLimitMiddleware::new(config)?),
                #[cfg(not(feature = "redis"))]
                "rate-limit-redis" => {
                    return Err(GatewayError::Config(
                        "rate-limit-redis requires the 'redis' feature flag: cargo build --features redis".to_string(),
                    ));
                }
                other => {
                    return Err(GatewayError::Config(format!(
                        "Unknown middleware type: '{}'",
                        other
                    )));
                }
            };

            middlewares.push(mw);
        }

        Ok(Self { middlewares })
    }

    /// Create an empty pipeline
    #[allow(dead_code)]
    pub fn empty() -> Self {
        Self {
            middlewares: Vec::new(),
        }
    }

    /// Execute the request through all middlewares.
    /// Returns Some(response) if any middleware short-circuits.
    pub async fn process_request(
        &self,
        parts: &mut http::request::Parts,
        ctx: &RequestContext,
    ) -> Result<Option<Response<Vec<u8>>>> {
        for mw in &self.middlewares {
            if let Some(response) = mw.handle_request(parts, ctx).await? {
                tracing::debug!(middleware = mw.name(), "Middleware short-circuited request");
                return Ok(Some(response));
            }
        }
        Ok(None)
    }

    /// Execute the response through all middlewares (reverse order)
    #[allow(dead_code)]
    pub async fn process_response(&self, parts: &mut http::response::Parts) -> Result<()> {
        for mw in self.middlewares.iter().rev() {
            mw.handle_response(parts).await?;
        }
        Ok(())
    }

    /// Number of middlewares in the pipeline
    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.middlewares.len()
    }

    /// Whether the pipeline is empty
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.middlewares.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_pipeline() {
        let pipeline = Pipeline::empty();
        assert!(pipeline.is_empty());
        assert_eq!(pipeline.len(), 0);
    }

    #[test]
    fn test_pipeline_from_config() {
        let mut configs = HashMap::new();
        configs.insert(
            "rate-limit".to_string(),
            MiddlewareConfig {
                middleware_type: "rate-limit".to_string(),
                rate: Some(100),
                burst: Some(50),
                ..default_mw_config()
            },
        );
        configs.insert(
            "cors".to_string(),
            MiddlewareConfig {
                middleware_type: "cors".to_string(),
                allowed_origins: vec!["*".to_string()],
                ..default_mw_config()
            },
        );

        let names = vec!["rate-limit".to_string(), "cors".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 2);
    }

    #[test]
    fn test_pipeline_from_config_compress() {
        let mut configs = HashMap::new();
        configs.insert(
            "compress".to_string(),
            MiddlewareConfig {
                middleware_type: "compress".to_string(),
                ..default_mw_config()
            },
        );
        let names = vec!["compress".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
    }

    #[test]
    fn test_pipeline_from_config_headers() {
        let mut configs = HashMap::new();
        configs.insert(
            "headers".to_string(),
            MiddlewareConfig {
                middleware_type: "headers".to_string(),
                ..default_mw_config()
            },
        );
        let names = vec!["headers".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
    }

    #[test]
    fn test_pipeline_from_config_strip_prefix() {
        let mut configs = HashMap::new();
        configs.insert(
            "strip".to_string(),
            MiddlewareConfig {
                middleware_type: "strip-prefix".to_string(),
                prefixes: vec!["/api".to_string()],
                ..default_mw_config()
            },
        );
        let names = vec!["strip".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
    }

    #[test]
    fn test_pipeline_from_config_ip_allow() {
        let mut configs = HashMap::new();
        configs.insert(
            "ip-allow".to_string(),
            MiddlewareConfig {
                middleware_type: "ip-allow".to_string(),
                allowed_ips: vec!["127.0.0.1".to_string()],
                ..default_mw_config()
            },
        );
        let names = vec!["ip-allow".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
    }

    #[test]
    fn test_pipeline_from_config_retry() {
        let mut configs = HashMap::new();
        configs.insert(
            "retry".to_string(),
            MiddlewareConfig {
                middleware_type: "retry".to_string(),
                max_retries: Some(3),
                retry_interval_ms: Some(100),
                ..default_mw_config()
            },
        );
        let names = vec!["retry".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
    }

    #[test]
    fn test_pipeline_from_config_jwt() {
        let mut configs = HashMap::new();
        configs.insert(
            "jwt".to_string(),
            MiddlewareConfig {
                middleware_type: "jwt".to_string(),
                ..default_mw_config()
            },
        );
        let names = vec!["jwt".to_string()];
        // JWT requires JWKS URL or secret - using empty config will fail
        // But we test that jwt is a recognized middleware type
        let result = Pipeline::from_config(&names, &configs);
        // This will fail because jwt middleware requires specific config
        // But it proves the middleware type is recognized
        assert!(result.is_err() || result.is_ok());
    }

    #[test]
    fn test_pipeline_from_config_body_limit() {
        let mut configs = HashMap::new();
        configs.insert(
            "body-limit".to_string(),
            MiddlewareConfig {
                middleware_type: "body-limit".to_string(),
                max_body_bytes: Some(1048576),
                ..default_mw_config()
            },
        );
        let names = vec!["body-limit".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
    }

    #[test]
    fn test_pipeline_unknown_middleware_name() {
        let configs = HashMap::new();
        let names = vec!["nonexistent".to_string()];
        let result = Pipeline::from_config(&names, &configs);
        assert!(result.is_err());
    }

    #[test]
    fn test_pipeline_unknown_middleware_type() {
        let mut configs = HashMap::new();
        configs.insert(
            "bad".to_string(),
            MiddlewareConfig {
                middleware_type: "unknown-type".to_string(),
                ..default_mw_config()
            },
        );
        let names = vec!["bad".to_string()];
        let result = Pipeline::from_config(&names, &configs);
        assert!(result.is_err());
        match result {
            Err(e) => assert!(e.to_string().contains("Unknown middleware type")),
            Ok(_) => panic!("Expected error"),
        }
    }

    #[tokio::test]
    async fn test_empty_pipeline_passthrough() {
        let pipeline = Pipeline::empty();
        let (mut parts, _) = http::Request::builder()
            .uri("/test")
            .body(())
            .unwrap()
            .into_parts();
        let ctx = RequestContext {
            client_ip: "127.0.0.1".to_string(),
            entrypoint: "web".to_string(),
            router: "test".to_string(),
        };
        let result = pipeline.process_request(&mut parts, &ctx).await.unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_pipeline_circuit_breaker_default_config() {
        let mut configs = HashMap::new();
        configs.insert(
            "cb".to_string(),
            MiddlewareConfig {
                middleware_type: "circuit-breaker".to_string(),
                ..default_mw_config()
            },
        );
        let names = vec!["cb".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
    }

    #[test]
    fn test_pipeline_circuit_breaker_custom_config() {
        let mut configs = HashMap::new();
        configs.insert(
            "cb".to_string(),
            MiddlewareConfig {
                middleware_type: "circuit-breaker".to_string(),
                failure_threshold: Some(3),
                cooldown_secs: Some(60),
                success_threshold: Some(2),
                ..default_mw_config()
            },
        );
        let names = vec!["cb".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
    }

    #[tokio::test]
    async fn test_circuit_breaker_allows_when_closed() {
        let mut configs = HashMap::new();
        configs.insert(
            "cb".to_string(),
            MiddlewareConfig {
                middleware_type: "circuit-breaker".to_string(),
                failure_threshold: Some(3),
                cooldown_secs: Some(30),
                success_threshold: Some(1),
                ..default_mw_config()
            },
        );
        let names = vec!["cb".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();

        let (mut parts, _) = http::Request::builder()
            .uri("/test")
            .body(())
            .unwrap()
            .into_parts();
        let ctx = RequestContext {
            client_ip: "127.0.0.1".to_string(),
            entrypoint: "web".to_string(),
            router: "test".to_string(),
        };
        // Fresh circuit breaker is closed — request should pass through
        let result = pipeline.process_request(&mut parts, &ctx).await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_pipeline_process_response() {
        let mut configs = HashMap::new();
        configs.insert(
            "cb".to_string(),
            MiddlewareConfig {
                middleware_type: "circuit-breaker".to_string(),
                failure_threshold: Some(3),
                cooldown_secs: Some(30),
                success_threshold: Some(1),
                ..default_mw_config()
            },
        );
        let names = vec!["cb".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();

        // Process a response through the pipeline
        let (mut resp_parts, _) = http::Response::builder()
            .status(200)
            .body(())
            .unwrap()
            .into_parts();

        // Should not error
        let result = pipeline.process_response(&mut resp_parts).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_pipeline_is_empty() {
        let pipeline = Pipeline::empty();
        assert!(pipeline.is_empty());
        assert_eq!(pipeline.len(), 0);
    }

    #[test]
    fn test_pipeline_len() {
        let mut configs = HashMap::new();
        configs.insert(
            "cors".to_string(),
            MiddlewareConfig {
                middleware_type: "cors".to_string(),
                allowed_origins: vec!["*".to_string()],
                ..default_mw_config()
            },
        );
        let names = vec!["cors".to_string()];
        let pipeline = Pipeline::from_config(&names, &configs).unwrap();
        assert_eq!(pipeline.len(), 1);
        assert!(!pipeline.is_empty());
    }

    fn default_mw_config() -> MiddlewareConfig {
        MiddlewareConfig::default()
    }
}