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
//! JWT authentication middleware — validates JSON Web Tokens
//!
//! Extracts and validates JWT tokens from the Authorization header,
//! supporting HS256/HS384/HS512 HMAC algorithms.

use crate::config::MiddlewareConfig;
use crate::error::{GatewayError, Result};
use crate::middleware::{Middleware, RequestContext};
use async_trait::async_trait;
use http::Response;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};

/// Standard JWT claims
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Claims {
    /// Subject (user ID)
    #[serde(default)]
    pub sub: String,
    /// Expiration time (UTC timestamp)
    #[serde(default)]
    pub exp: u64,
    /// Issued at (UTC timestamp)
    #[serde(default)]
    pub iat: u64,
    /// Issuer
    #[serde(default)]
    pub iss: String,
    /// Audience
    #[serde(default)]
    pub aud: String,
}

/// JWT authentication middleware
pub struct JwtAuthMiddleware {
    /// Decoding key (from HMAC secret)
    decoding_key: DecodingKey,
    /// Validation configuration
    validation: Validation,
    /// Header name to extract the token from
    header_name: String,
    /// Token prefix to strip (e.g., "Bearer ")
    token_prefix: String,
}

impl JwtAuthMiddleware {
    /// Create from middleware config
    pub fn new(config: &MiddlewareConfig) -> Result<Self> {
        let secret = config.value.as_deref().ok_or_else(|| {
            GatewayError::Config("JWT middleware requires 'value' field as HMAC secret".to_string())
        })?;

        if secret.is_empty() {
            return Err(GatewayError::Config(
                "JWT secret cannot be empty".to_string(),
            ));
        }

        let header_name = config
            .header
            .clone()
            .unwrap_or_else(|| "Authorization".to_string());

        let decoding_key = DecodingKey::from_secret(secret.as_bytes());

        let mut validation = Validation::new(Algorithm::HS256);
        // Don't validate aud/iss by default
        validation.validate_aud = false;
        // Require exp claim
        validation.required_spec_claims = ["exp"].iter().map(|s| s.to_string()).collect();

        Ok(Self {
            decoding_key,
            validation,
            header_name,
            token_prefix: "Bearer ".to_string(),
        })
    }

    /// Create directly from a secret string (for programmatic use)
    #[allow(dead_code)]
    pub fn from_secret(secret: &str) -> Result<Self> {
        if secret.is_empty() {
            return Err(GatewayError::Config(
                "JWT secret cannot be empty".to_string(),
            ));
        }

        let decoding_key = DecodingKey::from_secret(secret.as_bytes());
        let mut validation = Validation::new(Algorithm::HS256);
        validation.validate_aud = false;
        validation.required_spec_claims = ["exp"].iter().map(|s| s.to_string()).collect();

        Ok(Self {
            decoding_key,
            validation,
            header_name: "Authorization".to_string(),
            token_prefix: "Bearer ".to_string(),
        })
    }

    /// Validate a JWT token string and return the claims
    pub fn validate_token(&self, token: &str) -> std::result::Result<Claims, String> {
        decode::<Claims>(token, &self.decoding_key, &self.validation)
            .map(|data| data.claims)
            .map_err(|e| format!("JWT validation failed: {}", e))
    }

    /// Extract the token from a header value (strips "Bearer " prefix)
    pub fn extract_token<'a>(&self, header_value: &'a str) -> Option<&'a str> {
        if header_value.starts_with(&self.token_prefix) {
            Some(&header_value[self.token_prefix.len()..])
        } else {
            // Try raw token (no prefix)
            Some(header_value)
        }
    }
}

#[async_trait]
impl Middleware for JwtAuthMiddleware {
    async fn handle_request(
        &self,
        req: &mut http::request::Parts,
        _ctx: &RequestContext,
    ) -> Result<Option<Response<Vec<u8>>>> {
        let header_value = match req.headers.get(&self.header_name) {
            Some(v) => match v.to_str() {
                Ok(s) => s.to_string(),
                Err(_) => {
                    return Ok(Some(
                        Response::builder()
                            .status(401)
                            .body(r#"{"error":"Invalid authorization header"}"#.as_bytes().to_vec())
                            .unwrap(),
                    ));
                }
            },
            None => {
                return Ok(Some(
                    Response::builder()
                        .status(401)
                        .body(r#"{"error":"Missing authorization header"}"#.as_bytes().to_vec())
                        .unwrap(),
                ));
            }
        };

        let token = match self.extract_token(&header_value) {
            Some(t) if !t.is_empty() => t.to_string(),
            _ => {
                return Ok(Some(
                    Response::builder()
                        .status(401)
                        .body(r#"{"error":"Missing token"}"#.as_bytes().to_vec())
                        .unwrap(),
                ));
            }
        };

        match self.validate_token(&token) {
            Ok(claims) => {
                // Inject claims as headers for downstream services
                if !claims.sub.is_empty() {
                    if let Ok(v) = claims.sub.parse() {
                        req.headers.insert("x-jwt-subject", v);
                    }
                }
                Ok(None) // Continue pipeline
            }
            Err(e) => {
                tracing::debug!(error = %e, "JWT validation failed");
                Ok(Some(
                    Response::builder()
                        .status(401)
                        .body(format!(r#"{{"error":"{}"}}"#, e).as_bytes().to_vec())
                        .unwrap(),
                ))
            }
        }
    }

    fn name(&self) -> &str {
        "jwt-auth"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use jsonwebtoken::{encode, EncodingKey, Header};

    const TEST_SECRET: &str = "test-secret-key-for-unit-tests";

    fn make_token(claims: &Claims) -> String {
        encode(
            &Header::default(),
            claims,
            &EncodingKey::from_secret(TEST_SECRET.as_bytes()),
        )
        .unwrap()
    }

    fn valid_claims() -> Claims {
        Claims {
            sub: "user-123".to_string(),
            exp: (chrono::Utc::now().timestamp() + 3600) as u64,
            iat: chrono::Utc::now().timestamp() as u64,
            iss: "test".to_string(),
            aud: "".to_string(),
        }
    }

    fn expired_claims() -> Claims {
        Claims {
            sub: "user-123".to_string(),
            exp: 1000, // Long expired
            iat: 999,
            iss: "test".to_string(),
            aud: "".to_string(),
        }
    }

    fn jwt_config(secret: &str) -> MiddlewareConfig {
        MiddlewareConfig {
            middleware_type: "jwt".to_string(),
            value: Some(secret.to_string()),
            ..Default::default()
        }
    }

    // --- Construction tests ---

    #[test]
    fn test_jwt_name() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        assert_eq!(mw.name(), "jwt-auth");
    }

    #[test]
    fn test_from_config() {
        let mw = JwtAuthMiddleware::new(&jwt_config(TEST_SECRET));
        assert!(mw.is_ok());
    }

    #[test]
    fn test_from_config_missing_secret() {
        let mut config = jwt_config(TEST_SECRET);
        config.value = None;
        let result = JwtAuthMiddleware::new(&config);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_config_empty_secret() {
        let result = JwtAuthMiddleware::new(&jwt_config(""));
        assert!(result.is_err());
    }

    #[test]
    fn test_from_secret_empty() {
        let result = JwtAuthMiddleware::from_secret("");
        assert!(result.is_err());
    }

    #[test]
    fn test_from_config_custom_header() {
        let mut config = jwt_config(TEST_SECRET);
        config.header = Some("X-Auth-Token".to_string());
        let mw = JwtAuthMiddleware::new(&config).unwrap();
        assert_eq!(mw.header_name, "X-Auth-Token");
    }

    // --- Token validation tests ---

    #[test]
    fn test_validate_valid_token() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        let token = make_token(&valid_claims());
        let result = mw.validate_token(&token);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().sub, "user-123");
    }

    #[test]
    fn test_validate_expired_token() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        let token = make_token(&expired_claims());
        let result = mw.validate_token(&token);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("expired") || err.contains("Expired") || err.contains("ExpiredSignature"),
            "Unexpected error message: {}",
            err
        );
    }

    #[test]
    fn test_validate_wrong_secret() {
        let mw = JwtAuthMiddleware::from_secret("wrong-secret").unwrap();
        let token = make_token(&valid_claims());
        let result = mw.validate_token(&token);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_malformed_token() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        let result = mw.validate_token("not.a.valid.jwt");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_empty_token() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        let result = mw.validate_token("");
        assert!(result.is_err());
    }

    // --- Token extraction tests ---

    #[test]
    fn test_extract_bearer_token() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        assert_eq!(mw.extract_token("Bearer abc123"), Some("abc123"));
    }

    #[test]
    fn test_extract_raw_token() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        assert_eq!(mw.extract_token("abc123"), Some("abc123"));
    }

    // --- Middleware request handling tests ---

    #[tokio::test]
    async fn test_request_with_valid_token() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        let token = make_token(&valid_claims());
        let (mut parts, _) = http::Request::builder()
            .uri("/api/data")
            .header("Authorization", format!("Bearer {}", token))
            .body(())
            .unwrap()
            .into_parts();
        let ctx = RequestContext {
            client_ip: "127.0.0.1".to_string(),
            entrypoint: "web".to_string(),
            router: "api".to_string(),
        };
        let result = mw.handle_request(&mut parts, &ctx).await.unwrap();
        assert!(result.is_none()); // Should pass through
        assert_eq!(parts.headers.get("x-jwt-subject").unwrap(), "user-123");
    }

    #[tokio::test]
    async fn test_request_with_expired_token() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        let token = make_token(&expired_claims());
        let (mut parts, _) = http::Request::builder()
            .uri("/api/data")
            .header("Authorization", format!("Bearer {}", token))
            .body(())
            .unwrap()
            .into_parts();
        let ctx = RequestContext {
            client_ip: "127.0.0.1".to_string(),
            entrypoint: "web".to_string(),
            router: "api".to_string(),
        };
        let result = mw.handle_request(&mut parts, &ctx).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().status(), 401);
    }

    #[tokio::test]
    async fn test_request_missing_header() {
        let mw = JwtAuthMiddleware::from_secret(TEST_SECRET).unwrap();
        let (mut parts, _) = http::Request::builder()
            .uri("/api/data")
            .body(())
            .unwrap()
            .into_parts();
        let ctx = RequestContext {
            client_ip: "127.0.0.1".to_string(),
            entrypoint: "web".to_string(),
            router: "api".to_string(),
        };
        let result = mw.handle_request(&mut parts, &ctx).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().status(), 401);
    }

    #[tokio::test]
    async fn test_request_wrong_secret() {
        let mw = JwtAuthMiddleware::from_secret("different-secret").unwrap();
        let token = make_token(&valid_claims());
        let (mut parts, _) = http::Request::builder()
            .uri("/api/data")
            .header("Authorization", format!("Bearer {}", token))
            .body(())
            .unwrap()
            .into_parts();
        let ctx = RequestContext {
            client_ip: "127.0.0.1".to_string(),
            entrypoint: "web".to_string(),
            router: "api".to_string(),
        };
        let result = mw.handle_request(&mut parts, &ctx).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().status(), 401);
    }

    // --- Claims serialization ---

    #[test]
    fn test_claims_serialization() {
        let claims = valid_claims();
        let json = serde_json::to_string(&claims).unwrap();
        let parsed: Claims = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.sub, "user-123");
    }
}