arqen 0.3.0

Backend infrastructure for agent-ready applications
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
590
591
592
593
594
595
596
597
598
599
600
//! Authentication module for Arqen.
//!
//! Provides pluggable authentication with API keys, JWT, and session adapters.

use std::collections::HashMap;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use crate::core::{AppError, ErrorKind};

/// Authentication error type.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuthError {
    /// No credentials provided.
    Missing,
    /// Credentials are invalid.
    Invalid,
    /// Token has expired.
    Expired,
    /// User is not authorized for this resource.
    Unauthorized(String),
}

impl std::fmt::Display for AuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuthError::Missing => write!(f, "authentication required"),
            AuthError::Invalid => write!(f, "invalid credentials"),
            AuthError::Expired => write!(f, "credentials expired"),
            AuthError::Unauthorized(msg) => write!(f, "unauthorized: {}", msg),
        }
    }
}

impl std::error::Error for AuthError {}

impl From<AuthError> for AppError {
    fn from(e: AuthError) -> Self {
        match e {
            AuthError::Missing | AuthError::Invalid | AuthError::Expired => {
                AppError::new(ErrorKind::Authentication, e.to_string())
            }
            AuthError::Unauthorized(msg) => {
                AppError::new(ErrorKind::Authorization, msg)
            }
        }
    }
}

/// Authentication context extracted from requests.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthContext {
    /// Subject identifier (user ID, API key ID, etc.).
    pub subject: String,
    /// Claims or permissions.
    pub claims: HashMap<String, serde_json::Value>,
    /// Which adapter authenticated this request.
    pub adapter: String,
}

impl AuthContext {
    /// Create a new auth context.
    pub fn new(subject: impl Into<String>, adapter: impl Into<String>) -> Self {
        Self {
            subject: subject.into(),
            claims: HashMap::new(),
            adapter: adapter.into(),
        }
    }

    /// Add a claim.
    pub fn with_claim(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.claims.insert(key.into(), value);
        self
    }

    /// Check if a claim exists.
    pub fn has_claim(&self, key: &str) -> bool {
        self.claims.contains_key(key)
    }

    /// Get a claim value.
    pub fn get_claim(&self, key: &str) -> Option<&serde_json::Value> {
        self.claims.get(key)
    }

    /// Check if user has a specific role.
    pub fn has_role(&self, role: &str) -> bool {
        self.get_claim("roles")
            .and_then(|v| v.as_array())
            .map(|roles| {
                roles
                    .iter()
                    .any(|r| r.as_str() == Some(role))
            })
            .unwrap_or(false)
    }
}

/// Trait for authentication adapters.
#[async_trait]
pub trait Authentication: Send + Sync {
    /// Authenticate a request from headers.
    async fn authenticate(&self, headers: &axum::http::HeaderMap) -> Result<AuthContext, AuthError>;
}

/// API key authentication adapter.
///
/// Validates API keys from the `Authorization: Bearer <key>` header
/// or `X-API-Key` header.
pub struct ApiKeyAuth {
    /// Valid API keys mapped to subject IDs.
    keys: HashMap<String, String>,
}

impl ApiKeyAuth {
    /// Create a new API key auth adapter.
    pub fn new() -> Self {
        Self {
            keys: HashMap::new(),
        }
    }

    /// Add an API key.
    pub fn with_key(mut self, key: impl Into<String>, subject: impl Into<String>) -> Self {
        self.keys.insert(key.into(), subject.into());
        self
    }

    /// Add multiple API keys.
    pub fn with_keys(mut self, keys: HashMap<String, String>) -> Self {
        self.keys.extend(keys);
        self
    }
}

impl Default for ApiKeyAuth {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Authentication for ApiKeyAuth {
    async fn authenticate(&self, headers: &axum::http::HeaderMap) -> Result<AuthContext, AuthError> {
        // Try X-API-Key header first
        if let Some(key) = headers.get("x-api-key") {
            let key = key.to_str().map_err(|_| AuthError::Invalid)?;
            if let Some(subject) = self.keys.get(key) {
                return Ok(AuthContext::new(subject, "api_key"));
            }
            return Err(AuthError::Invalid);
        }

        // Try Authorization: Bearer <key>
        if let Some(auth) = headers.get("authorization") {
            let auth = auth.to_str().map_err(|_| AuthError::Invalid)?;
            if let Some(key) = auth.strip_prefix("Bearer ") {
                if let Some(subject) = self.keys.get(key) {
                    return Ok(AuthContext::new(subject, "api_key"));
                }
                return Err(AuthError::Invalid);
            }
        }

        Err(AuthError::Missing)
    }
}

/// JWT authentication adapter.
///
/// Validates JWT tokens from the `Authorization: Bearer <token>` header.
/// This is a placeholder implementation - in production, use a proper JWT library.
pub struct JwtAuth {
    /// Valid tokens mapped to auth contexts.
    tokens: HashMap<String, AuthContext>,
}

impl JwtAuth {
    /// Create a new JWT auth adapter.
    pub fn new() -> Self {
        Self {
            tokens: HashMap::new(),
        }
    }

    /// Add a valid token with its auth context.
    pub fn with_token(mut self, token: impl Into<String>, context: AuthContext) -> Self {
        self.tokens.insert(token.into(), context);
        self
    }
}

impl Default for JwtAuth {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Authentication for JwtAuth {
    async fn authenticate(&self, headers: &axum::http::HeaderMap) -> Result<AuthContext, AuthError> {
        let auth = headers
            .get("authorization")
            .ok_or(AuthError::Missing)?
            .to_str()
            .map_err(|_| AuthError::Invalid)?;

        let token = auth
            .strip_prefix("Bearer ")
            .ok_or(AuthError::Invalid)?;

        self.tokens
            .get(token)
            .cloned()
            .ok_or(AuthError::Invalid)
    }
}

/// Session-based authentication adapter.
///
/// Validates sessions from cookies.
pub struct SessionAuth {
    /// Valid session tokens mapped to auth contexts.
    sessions: HashMap<String, AuthContext>,
    /// Cookie name to look for.
    cookie_name: String,
}

impl SessionAuth {
    /// Create a new session auth adapter.
    pub fn new(cookie_name: impl Into<String>) -> Self {
        Self {
            sessions: HashMap::new(),
            cookie_name: cookie_name.into(),
        }
    }

    /// Add a valid session.
    pub fn with_session(mut self, token: impl Into<String>, context: AuthContext) -> Self {
        self.sessions.insert(token.into(), context);
        self
    }
}

#[async_trait]
impl Authentication for SessionAuth {
    async fn authenticate(&self, headers: &axum::http::HeaderMap) -> Result<AuthContext, AuthError> {
        let cookie_header = headers
            .get("cookie")
            .ok_or(AuthError::Missing)?
            .to_str()
            .map_err(|_| AuthError::Invalid)?;

        // Parse cookie header to find session token
        for part in cookie_header.split(';') {
            let part = part.trim();
            if let Some((name, value)) = part.split_once('=') {
                if name == self.cookie_name {
                    return self.sessions
                        .get(value)
                        .cloned()
                        .ok_or(AuthError::Invalid);
                }
            }
        }

        Err(AuthError::Missing)
    }
}

/// Policy trait for authorization.
pub trait Policy: Send + Sync {
    /// Check if an auth context is authorized for a resource.
    fn check(&self, context: &AuthContext, resource: &str) -> Result<(), AuthError>;
}

/// Policy that allows all requests.
pub struct AllowAll;

impl Policy for AllowAll {
    fn check(&self, _context: &AuthContext, _resource: &str) -> Result<(), AuthError> {
        Ok(())
    }
}

/// Policy that denies all requests.
pub struct DenyAll;

impl Policy for DenyAll {
    fn check(&self, _context: &AuthContext, _resource: &str) -> Result<(), AuthError> {
        Err(AuthError::Unauthorized("access denied".to_string()))
    }
}

/// Policy that checks for a specific role.
pub struct RequireRole {
    role: String,
}

impl RequireRole {
    pub fn new(role: impl Into<String>) -> Self {
        Self { role: role.into() }
    }
}

impl Policy for RequireRole {
    fn check(&self, context: &AuthContext, _resource: &str) -> Result<(), AuthError> {
        if context.has_role(&self.role) {
            Ok(())
        } else {
            Err(AuthError::Unauthorized(format!(
                "requires role: {}",
                self.role
            )))
        }
    }
}

/// Compose multiple policies (all must pass).
pub struct AllOf {
    policies: Vec<Box<dyn Policy>>,
}

impl AllOf {
    pub fn new() -> Self {
        Self {
            policies: Vec::new(),
        }
    }

    pub fn with_policy(mut self, policy: impl Policy + 'static) -> Self {
        self.policies.push(Box::new(policy));
        self
    }
}

impl Default for AllOf {
    fn default() -> Self {
        Self::new()
    }
}

impl Policy for AllOf {
    fn check(&self, context: &AuthContext, resource: &str) -> Result<(), AuthError> {
        for policy in &self.policies {
            policy.check(context, resource)?;
        }
        Ok(())
    }
}

/// Compose multiple policies (any must pass).
pub struct AnyOf {
    policies: Vec<Box<dyn Policy>>,
}

impl AnyOf {
    pub fn new() -> Self {
        Self {
            policies: Vec::new(),
        }
    }

    pub fn with_policy(mut self, policy: impl Policy + 'static) -> Self {
        self.policies.push(Box::new(policy));
        self
    }
}

impl Default for AnyOf {
    fn default() -> Self {
        Self::new()
    }
}

impl Policy for AnyOf {
    fn check(&self, context: &AuthContext, resource: &str) -> Result<(), AuthError> {
        for policy in &self.policies {
            if policy.check(context, resource).is_ok() {
                return Ok(());
            }
        }
        Err(AuthError::Unauthorized("no matching policy".to_string()))
    }
}

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

    #[test]
    fn test_auth_context_new() {
        let ctx = AuthContext::new("user-123", "api_key");
        assert_eq!(ctx.subject, "user-123");
        assert_eq!(ctx.adapter, "api_key");
        assert!(ctx.claims.is_empty());
    }

    #[test]
    fn test_auth_context_with_claim() {
        let ctx = AuthContext::new("user-123", "api_key")
            .with_claim("roles", serde_json::json!(["admin"]));
        assert!(ctx.has_claim("roles"));
        assert_eq!(
            ctx.get_claim("roles"),
            Some(&serde_json::json!(["admin"]))
        );
    }

    #[test]
    fn test_auth_context_has_role() {
        let ctx = AuthContext::new("user-123", "api_key")
            .with_claim("roles", serde_json::json!(["admin", "user"]));
        assert!(ctx.has_role("admin"));
        assert!(ctx.has_role("user"));
        assert!(!ctx.has_role("superadmin"));
    }

    #[test]
    fn test_auth_context_no_roles() {
        let ctx = AuthContext::new("user-123", "api_key");
        assert!(!ctx.has_role("admin"));
    }

    #[tokio::test]
    async fn test_api_key_auth_valid() {
        let auth = ApiKeyAuth::new()
            .with_key("test-key", "user-123");

        let mut headers = axum::http::HeaderMap::new();
        headers.insert("x-api-key", "test-key".parse().unwrap());

        let ctx = auth.authenticate(&headers).await.unwrap();
        assert_eq!(ctx.subject, "user-123");
        assert_eq!(ctx.adapter, "api_key");
    }

    #[tokio::test]
    async fn test_api_key_auth_invalid() {
        let auth = ApiKeyAuth::new()
            .with_key("test-key", "user-123");

        let mut headers = axum::http::HeaderMap::new();
        headers.insert("x-api-key", "wrong-key".parse().unwrap());

        let err = auth.authenticate(&headers).await.unwrap_err();
        assert_eq!(err, AuthError::Invalid);
    }

    #[tokio::test]
    async fn test_api_key_auth_missing() {
        let auth = ApiKeyAuth::new()
            .with_key("test-key", "user-123");

        let headers = axum::http::HeaderMap::new();

        let err = auth.authenticate(&headers).await.unwrap_err();
        assert_eq!(err, AuthError::Missing);
    }

    #[tokio::test]
    async fn test_api_key_auth_bearer() {
        let auth = ApiKeyAuth::new()
            .with_key("test-key", "user-123");

        let mut headers = axum::http::HeaderMap::new();
        headers.insert("authorization", "Bearer test-key".parse().unwrap());

        let ctx = auth.authenticate(&headers).await.unwrap();
        assert_eq!(ctx.subject, "user-123");
    }

    #[tokio::test]
    async fn test_jwt_auth_valid() {
        let ctx = AuthContext::new("user-123", "jwt")
            .with_claim("exp", serde_json::json!(1234567890));

        let auth = JwtAuth::new()
            .with_token("valid-token", ctx);

        let mut headers = axum::http::HeaderMap::new();
        headers.insert("authorization", "Bearer valid-token".parse().unwrap());

        let ctx = auth.authenticate(&headers).await.unwrap();
        assert_eq!(ctx.subject, "user-123");
    }

    #[tokio::test]
    async fn test_jwt_auth_invalid() {
        let auth = JwtAuth::new();

        let mut headers = axum::http::HeaderMap::new();
        headers.insert("authorization", "Bearer invalid-token".parse().unwrap());

        let err = auth.authenticate(&headers).await.unwrap_err();
        assert_eq!(err, AuthError::Invalid);
    }

    #[tokio::test]
    async fn test_session_auth_valid() {
        let ctx = AuthContext::new("user-123", "session");

        let auth = SessionAuth::new("session_id")
            .with_session("abc123", ctx);

        let mut headers = axum::http::HeaderMap::new();
        headers.insert("cookie", "session_id=abc123".parse().unwrap());

        let ctx = auth.authenticate(&headers).await.unwrap();
        assert_eq!(ctx.subject, "user-123");
    }

    #[tokio::test]
    async fn test_session_auth_missing() {
        let auth = SessionAuth::new("session_id");

        let headers = axum::http::HeaderMap::new();

        let err = auth.authenticate(&headers).await.unwrap_err();
        assert_eq!(err, AuthError::Missing);
    }

    #[test]
    fn test_allow_all_policy() {
        let policy = AllowAll;
        let ctx = AuthContext::new("user-123", "test");
        assert!(policy.check(&ctx, "resource").is_ok());
    }

    #[test]
    fn test_deny_all_policy() {
        let policy = DenyAll;
        let ctx = AuthContext::new("user-123", "test");
        assert!(policy.check(&ctx, "resource").is_err());
    }

    #[test]
    fn test_require_role_policy() {
        let policy = RequireRole::new("admin");
        let ctx = AuthContext::new("user-123", "test")
            .with_claim("roles", serde_json::json!(["admin"]));
        assert!(policy.check(&ctx, "resource").is_ok());

        let ctx = AuthContext::new("user-123", "test")
            .with_claim("roles", serde_json::json!(["user"]));
        assert!(policy.check(&ctx, "resource").is_err());
    }

    #[test]
    fn test_all_of_policy() {
        let policy = AllOf::new()
            .with_policy(AllowAll)
            .with_policy(RequireRole::new("admin"));

        let ctx = AuthContext::new("user-123", "test")
            .with_claim("roles", serde_json::json!(["admin"]));
        assert!(policy.check(&ctx, "resource").is_ok());

        let ctx = AuthContext::new("user-123", "test")
            .with_claim("roles", serde_json::json!(["user"]));
        assert!(policy.check(&ctx, "resource").is_err());
    }

    #[test]
    fn test_any_of_policy() {
        let policy = AnyOf::new()
            .with_policy(DenyAll)
            .with_policy(RequireRole::new("admin"));

        let ctx = AuthContext::new("user-123", "test")
            .with_claim("roles", serde_json::json!(["admin"]));
        assert!(policy.check(&ctx, "resource").is_ok());

        let ctx = AuthContext::new("user-123", "test")
            .with_claim("roles", serde_json::json!(["user"]));
        assert!(policy.check(&ctx, "resource").is_err());
    }

    #[test]
    fn test_auth_error_display() {
        assert_eq!(format!("{}", AuthError::Missing), "authentication required");
        assert_eq!(format!("{}", AuthError::Invalid), "invalid credentials");
        assert_eq!(format!("{}", AuthError::Expired), "credentials expired");
        assert_eq!(
            format!("{}", AuthError::Unauthorized("denied".to_string())),
            "unauthorized: denied"
        );
    }

    #[test]
    fn test_auth_error_to_app_error() {
        let err: AppError = AuthError::Missing.into();
        assert_eq!(err.kind, ErrorKind::Authentication);

        let err: AppError = AuthError::Unauthorized("denied".to_string()).into();
        assert_eq!(err.kind, ErrorKind::Authorization);
    }
}