allsource-core 0.19.1

High-performance event store core built in Rust
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
use crate::{
    error::AllSourceError,
    infrastructure::security::{
        auth::{AuthManager, Claims, Permission, Role},
        rate_limit::RateLimiter,
    },
};
use axum::{
    extract::{Request, State},
    http::{HeaderMap, StatusCode},
    middleware::Next,
    response::{IntoResponse, Response},
};
use std::sync::{Arc, LazyLock};

/// Paths that bypass authentication (exact match)
pub const AUTH_SKIP_PATHS: &[&str] = &[
    "/health",
    "/metrics",
    "/api/v1/auth/register",
    "/api/v1/auth/login",
    "/api/v1/demo/seed",
];

/// Path prefixes that bypass authentication and rate limiting.
///
/// Internal endpoints are used by the sentinel process for automated failover
/// (promote, repoint). They must not require API keys or be rate-limited,
/// otherwise failover can timeout or fail when credentials are unavailable.
pub const AUTH_SKIP_PREFIXES: &[&str] = &["/internal/"];

/// Check if a path should skip authentication and rate limiting.
#[inline]
pub fn should_skip_auth(path: &str) -> bool {
    AUTH_SKIP_PATHS.contains(&path) || AUTH_SKIP_PREFIXES.iter().any(|pfx| path.starts_with(pfx))
}

/// Check if development mode is enabled via environment variable.
/// When enabled, authentication and rate limiting are bypassed for local
/// development (e.g., MCP server integration, quick curl queries against
/// `/api/v1/events/query` without generating a JWT).
///
/// Set any of the following to `true`/`1` to enable:
/// - `ALLSOURCE_DEV_MODE` — historical name, still supported
/// - `ALLSOURCE_AUTH_DISABLED` — explicit "turn auth off" alias (issue #131)
///
/// **WARNING**: Never enable this in production environments! The feature
/// grants admin context to any request that arrives without a token.
fn env_flag_enabled(name: &str) -> bool {
    std::env::var(name)
        .map(|v| matches!(v.to_lowercase().as_str(), "true" | "1" | "yes"))
        .unwrap_or(false)
}

static DEV_MODE_ENABLED: LazyLock<bool> = LazyLock::new(|| {
    let via_dev = env_flag_enabled("ALLSOURCE_DEV_MODE");
    let via_auth_off = env_flag_enabled("ALLSOURCE_AUTH_DISABLED");
    let enabled = via_dev || via_auth_off;
    if enabled {
        let source = if via_auth_off && via_dev {
            "ALLSOURCE_DEV_MODE + ALLSOURCE_AUTH_DISABLED"
        } else if via_auth_off {
            "ALLSOURCE_AUTH_DISABLED"
        } else {
            "ALLSOURCE_DEV_MODE"
        };
        tracing::warn!(
            "⚠️  Auth disabled via {source} — all requests run as admin with no rate limits. DO NOT use in production."
        );
    }
    enabled
});

/// Check if dev mode is enabled
#[inline]
pub fn is_dev_mode() -> bool {
    *DEV_MODE_ENABLED
}

/// Create a development-mode AuthContext with admin privileges
fn dev_mode_auth_context() -> AuthContext {
    AuthContext {
        claims: Claims::new(
            "dev-user".to_string(),
            "dev-tenant".to_string(),
            Role::Admin,
            chrono::Duration::hours(24),
        ),
    }
}

/// Authentication state shared across requests
#[derive(Clone)]
pub struct AuthState {
    pub auth_manager: Arc<AuthManager>,
}

/// Rate limiting state
#[derive(Clone)]
pub struct RateLimitState {
    pub rate_limiter: Arc<RateLimiter>,
}

/// Authenticated request context
#[derive(Debug, Clone)]
pub struct AuthContext {
    pub claims: Claims,
}

impl AuthContext {
    /// Check if user has required permission
    pub fn require_permission(&self, permission: Permission) -> Result<(), AllSourceError> {
        if self.claims.has_permission(permission) {
            Ok(())
        } else {
            Err(AllSourceError::ValidationError(
                "Insufficient permissions".to_string(),
            ))
        }
    }

    /// Get tenant ID from context
    pub fn tenant_id(&self) -> &str {
        &self.claims.tenant_id
    }

    /// Get user ID from context
    pub fn user_id(&self) -> &str {
        &self.claims.sub
    }
}

/// Extract token from Authorization header, with X-API-Key fallback for backwards compatibility.
fn extract_token(headers: &HeaderMap) -> Result<String, AllSourceError> {
    // Primary: Authorization header (Bearer <token> or plain <token>)
    // Fallback: X-API-Key header (legacy, deprecated)
    let auth_header = if let Some(val) = headers.get("authorization") {
        val.to_str()
            .map_err(|_| {
                AllSourceError::ValidationError("Invalid authorization header".to_string())
            })?
            .to_string()
    } else if let Some(val) = headers.get("x-api-key") {
        val.to_str()
            .map_err(|_| AllSourceError::ValidationError("Invalid X-API-Key header".to_string()))?
            .to_string()
    } else {
        return Err(AllSourceError::ValidationError(
            "Missing authorization header".to_string(),
        ));
    };

    // Support both "Bearer <token>" and "<token>" formats
    let token = if auth_header.starts_with("Bearer ") {
        auth_header.trim_start_matches("Bearer ").trim()
    } else if auth_header.starts_with("bearer ") {
        auth_header.trim_start_matches("bearer ").trim()
    } else {
        auth_header.trim()
    };

    if token.is_empty() {
        return Err(AllSourceError::ValidationError(
            "Empty authorization token".to_string(),
        ));
    }

    Ok(token.to_string())
}

/// Returns true for paths that require Admin permission regardless of other checks.
///
/// - POST /api/v1/auth/api-keys — key creation (agents must not self-replicate)
/// - /api/v1/tenants/* — tenant management (agents must not alter tenants)
///
/// Note: /api/v1/auth/register is in AUTH_SKIP_PATHS (public self-registration) and
/// additionally enforces Admin at the handler level when any auth token is present.
#[inline]
pub fn is_admin_only_path(path: &str, method: &str) -> bool {
    (path == "/api/v1/auth/api-keys" && method == "POST") || path.starts_with("/api/v1/tenants")
}

/// Authentication middleware
pub async fn auth_middleware(
    State(auth_state): State<AuthState>,
    mut request: Request,
    next: Next,
) -> Result<Response, AuthError> {
    // Skip authentication for public and internal paths
    let path = request.uri().path();
    if should_skip_auth(path) {
        return Ok(next.run(request).await);
    }

    // Dev mode: if a valid token is present, authenticate normally so that
    // /me returns the real tenant_id (not a hardcoded "dev-tenant").
    // Fall back to the synthetic dev context only when no token is provided.
    if is_dev_mode() {
        let headers = request.headers();
        let auth_ctx = match extract_token(headers) {
            Ok(token) => {
                let claims = if token.starts_with("ask_") {
                    auth_state.auth_manager.validate_api_key(&token).ok()
                } else {
                    auth_state.auth_manager.validate_token(&token).ok()
                };
                claims.map_or_else(dev_mode_auth_context, |c| AuthContext { claims: c })
            }
            Err(_) => dev_mode_auth_context(),
        };
        request.extensions_mut().insert(auth_ctx);
        return Ok(next.run(request).await);
    }

    let headers = request.headers();

    // Extract and validate token (JWT or API key)
    let token = extract_token(headers)?;

    let claims = if token.starts_with("ask_") {
        // API Key authentication
        auth_state.auth_manager.validate_api_key(&token)?
    } else {
        // JWT authentication
        auth_state.auth_manager.validate_token(&token)?
    };

    let auth_ctx = AuthContext { claims };

    // Enforce that service accounts (agent API keys) cannot access admin-only paths.
    // Admin-only paths: user registration, API key creation, and all tenant management.
    // These are also enforced at handler level; this middleware block provides defence-in-depth.
    let path = request.uri().path();
    let method = request.method().as_str();
    let is_admin_only_path = is_admin_only_path(path, method);

    if is_admin_only_path {
        auth_ctx
            .require_permission(Permission::Admin)
            .map_err(|_| {
                AuthError(AllSourceError::ValidationError(
                    "Admin permission required".to_string(),
                ))
            })?;
    }

    // Insert auth context into request extensions
    request.extensions_mut().insert(auth_ctx);

    Ok(next.run(request).await)
}

/// Optional authentication middleware (allows unauthenticated requests)
pub async fn optional_auth_middleware(
    State(auth_state): State<AuthState>,
    mut request: Request,
    next: Next,
) -> Response {
    let headers = request.headers();

    if let Ok(token) = extract_token(headers) {
        // Try to authenticate, but don't fail if invalid
        let claims = if token.starts_with("ask_") {
            auth_state.auth_manager.validate_api_key(&token).ok()
        } else {
            auth_state.auth_manager.validate_token(&token).ok()
        };

        if let Some(claims) = claims {
            request.extensions_mut().insert(AuthContext { claims });
        }
    }

    next.run(request).await
}

/// Error type for authentication failures
#[derive(Debug)]
pub struct AuthError(AllSourceError);

impl From<AllSourceError> for AuthError {
    fn from(err: AllSourceError) -> Self {
        AuthError(err)
    }
}

impl IntoResponse for AuthError {
    fn into_response(self) -> Response {
        let (status, message) = match self.0 {
            AllSourceError::ValidationError(msg) => (StatusCode::UNAUTHORIZED, msg),
            _ => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Internal server error".to_string(),
            ),
        };

        (status, message).into_response()
    }
}

/// Axum extractor for authenticated requests
pub struct Authenticated(pub AuthContext);

impl<S> axum::extract::FromRequestParts<S> for Authenticated
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        parts
            .extensions
            .get::<AuthContext>()
            .cloned()
            .map(Authenticated)
            .ok_or((StatusCode::UNAUTHORIZED, "Unauthorized"))
    }
}

/// Axum extractor for optional authentication (never rejects, returns Option)
/// Use this for routes that work with or without authentication
pub struct OptionalAuth(pub Option<AuthContext>);

impl<S> axum::extract::FromRequestParts<S> for OptionalAuth
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        Ok(OptionalAuth(parts.extensions.get::<AuthContext>().cloned()))
    }
}

/// Axum extractor for admin-only requests
pub struct Admin(pub AuthContext);

impl<S> axum::extract::FromRequestParts<S> for Admin
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        let auth_ctx = parts
            .extensions
            .get::<AuthContext>()
            .cloned()
            .ok_or((StatusCode::UNAUTHORIZED, "Unauthorized"))?;

        auth_ctx
            .require_permission(Permission::Admin)
            .map_err(|_| (StatusCode::FORBIDDEN, "Admin permission required"))?;

        Ok(Admin(auth_ctx))
    }
}

/// Rate limiting middleware
/// Checks rate limits based on tenant_id from auth context
pub async fn rate_limit_middleware(
    State(rate_limit_state): State<RateLimitState>,
    request: Request,
    next: Next,
) -> Result<Response, RateLimitError> {
    // Skip rate limiting for public and internal paths
    let path = request.uri().path();
    if should_skip_auth(path) {
        return Ok(next.run(request).await);
    }

    // Dev mode: bypass rate limiting entirely
    if is_dev_mode() {
        return Ok(next.run(request).await);
    }

    // Extract auth context from request
    let auth_ctx = request
        .extensions()
        .get::<AuthContext>()
        .ok_or(RateLimitError::Unauthorized)?;

    // Check rate limit for this tenant
    let result = rate_limit_state
        .rate_limiter
        .check_rate_limit(auth_ctx.tenant_id());

    if !result.allowed {
        return Err(RateLimitError::RateLimitExceeded {
            retry_after: result.retry_after.unwrap_or_default().as_secs(),
            limit: result.limit,
        });
    }

    // Add rate limit headers to response
    let mut response = next.run(request).await;
    let headers = response.headers_mut();
    headers.insert(
        "X-RateLimit-Limit",
        result.limit.to_string().parse().unwrap(),
    );
    headers.insert(
        "X-RateLimit-Remaining",
        result.remaining.to_string().parse().unwrap(),
    );

    Ok(response)
}

/// Error type for rate limiting failures
#[derive(Debug)]
pub enum RateLimitError {
    RateLimitExceeded { retry_after: u64, limit: u32 },
    Unauthorized,
}

impl IntoResponse for RateLimitError {
    fn into_response(self) -> Response {
        match self {
            RateLimitError::RateLimitExceeded { retry_after, limit } => {
                let mut response = (
                    StatusCode::TOO_MANY_REQUESTS,
                    format!("Rate limit exceeded. Limit: {limit} requests/min"),
                )
                    .into_response();

                if retry_after > 0 {
                    response
                        .headers_mut()
                        .insert("Retry-After", retry_after.to_string().parse().unwrap());
                }

                response
            }
            RateLimitError::Unauthorized => (
                StatusCode::UNAUTHORIZED,
                "Authentication required for rate limiting",
            )
                .into_response(),
        }
    }
}

/// Helper macro to require specific permission
#[macro_export]
macro_rules! require_permission {
    ($auth:expr, $perm:expr) => {
        $auth.0.require_permission($perm).map_err(|_| {
            (
                axum::http::StatusCode::FORBIDDEN,
                "Insufficient permissions",
            )
        })?
    };
}

// ============================================================================
// Tenant Isolation Middleware (Phase 5B)
// ============================================================================

use crate::domain::{entities::Tenant, repositories::TenantRepository, value_objects::TenantId};

/// Tenant isolation state for middleware
#[derive(Clone)]
pub struct TenantState<R: TenantRepository> {
    pub tenant_repository: Arc<R>,
}

/// Validated tenant context injected into requests
///
/// This context is created by the tenant_isolation_middleware after
/// validating that the tenant exists and is active.
#[derive(Debug, Clone)]
pub struct TenantContext {
    pub tenant: Tenant,
}

impl TenantContext {
    /// Get the tenant ID
    pub fn tenant_id(&self) -> &TenantId {
        self.tenant.id()
    }

    /// Check if tenant is active
    pub fn is_active(&self) -> bool {
        self.tenant.is_active()
    }
}

/// Tenant isolation middleware
///
/// Validates that the authenticated tenant exists and is active.
/// Injects TenantContext into the request for use by handlers.
///
/// # Phase 5B: Tenant Isolation
/// This middleware enforces tenant boundaries by:
/// 1. Extracting tenant_id from AuthContext
/// 2. Loading tenant from repository
/// 3. Validating tenant is active
/// 4. Injecting TenantContext into request extensions
///
/// Must be applied after auth_middleware.
pub async fn tenant_isolation_middleware<R: TenantRepository + 'static>(
    State(tenant_state): State<TenantState<R>>,
    mut request: Request,
    next: Next,
) -> Result<Response, TenantError> {
    // Extract auth context (must be authenticated)
    let auth_ctx = request
        .extensions()
        .get::<AuthContext>()
        .ok_or(TenantError::Unauthorized)?
        .clone();

    // Parse tenant ID
    let tenant_id =
        TenantId::new(auth_ctx.tenant_id().to_string()).map_err(|_| TenantError::InvalidTenant)?;

    // Load tenant from repository
    let tenant = tenant_state
        .tenant_repository
        .find_by_id(&tenant_id)
        .await
        .map_err(|e| TenantError::RepositoryError(e.to_string()))?
        .ok_or(TenantError::TenantNotFound)?;

    // Validate tenant is active
    if !tenant.is_active() {
        return Err(TenantError::TenantInactive);
    }

    // Inject tenant context into request
    request.extensions_mut().insert(TenantContext { tenant });

    // Continue to next middleware/handler
    Ok(next.run(request).await)
}

/// Error type for tenant isolation failures
#[derive(Debug)]
pub enum TenantError {
    Unauthorized,
    InvalidTenant,
    TenantNotFound,
    TenantInactive,
    RepositoryError(String),
}

impl IntoResponse for TenantError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            TenantError::Unauthorized => (
                StatusCode::UNAUTHORIZED,
                "Authentication required for tenant access",
            ),
            TenantError::InvalidTenant => (StatusCode::BAD_REQUEST, "Invalid tenant identifier"),
            TenantError::TenantNotFound => (StatusCode::NOT_FOUND, "Tenant not found"),
            TenantError::TenantInactive => (StatusCode::FORBIDDEN, "Tenant is inactive"),
            TenantError::RepositoryError(_) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to validate tenant",
            ),
        };

        (status, message).into_response()
    }
}

// ============================================================================
// Request ID Middleware (Phase 5C)
// ============================================================================

use uuid::Uuid;

/// Request context with unique ID for tracing
#[derive(Debug, Clone)]
pub struct RequestId(pub String);

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

impl RequestId {
    /// Generate a new request ID
    pub fn new() -> Self {
        Self(Uuid::new_v4().to_string())
    }

    /// Get the request ID as a string
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Request ID middleware
///
/// Generates a unique request ID for each request and injects it into:
/// - Request extensions (for use in handlers/logging)
/// - Response headers (X-Request-ID)
///
/// If the request already has an X-Request-ID header, it will be used instead.
///
/// # Phase 5C: Request Tracing
/// This middleware enables distributed tracing by:
/// 1. Generating unique IDs for each request
/// 2. Propagating IDs through the request lifecycle
/// 3. Returning IDs in response headers
/// 4. Supporting client-provided request IDs
pub async fn request_id_middleware(mut request: Request, next: Next) -> Response {
    // Check if request already has a request ID
    let request_id = request
        .headers()
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .map_or_else(RequestId::new, |s| RequestId(s.to_string()));

    // Store request ID in extensions
    request.extensions_mut().insert(request_id.clone());

    // Process request
    let mut response = next.run(request).await;

    // Add request ID to response headers
    response
        .headers_mut()
        .insert("x-request-id", request_id.0.parse().unwrap());

    response
}

// ============================================================================
// Security Headers Middleware (Phase 5C)
// ============================================================================

/// Security headers configuration
#[derive(Debug, Clone)]
pub struct SecurityConfig {
    /// Enable HSTS (HTTP Strict Transport Security)
    pub enable_hsts: bool,
    /// HSTS max age in seconds
    pub hsts_max_age: u32,
    /// Enable X-Frame-Options
    pub enable_frame_options: bool,
    /// X-Frame-Options value
    pub frame_options: FrameOptions,
    /// Enable X-Content-Type-Options
    pub enable_content_type_options: bool,
    /// Enable X-XSS-Protection
    pub enable_xss_protection: bool,
    /// Content Security Policy
    pub csp: Option<String>,
    /// CORS allowed origins
    pub cors_origins: Vec<String>,
    /// CORS allowed methods
    pub cors_methods: Vec<String>,
    /// CORS allowed headers
    pub cors_headers: Vec<String>,
    /// CORS max age
    pub cors_max_age: u32,
}

#[derive(Debug, Clone)]
pub enum FrameOptions {
    Deny,
    SameOrigin,
    AllowFrom(String),
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            enable_hsts: true,
            hsts_max_age: 31_536_000, // 1 year
            enable_frame_options: true,
            frame_options: FrameOptions::Deny,
            enable_content_type_options: true,
            enable_xss_protection: true,
            csp: Some("default-src 'self'".to_string()),
            cors_origins: vec!["*".to_string()],
            cors_methods: vec![
                "GET".to_string(),
                "POST".to_string(),
                "PUT".to_string(),
                "DELETE".to_string(),
            ],
            cors_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
            cors_max_age: 3600,
        }
    }
}

#[derive(Clone)]
pub struct SecurityState {
    pub config: SecurityConfig,
}

/// Security headers middleware
///
/// Adds security-related HTTP headers to all responses:
/// - HSTS (Strict-Transport-Security)
/// - X-Frame-Options
/// - X-Content-Type-Options
/// - X-XSS-Protection
/// - Content-Security-Policy
/// - CORS headers
///
/// # Phase 5C: Security Hardening
/// This middleware provides defense-in-depth by:
/// 1. Preventing clickjacking (X-Frame-Options)
/// 2. Preventing MIME sniffing (X-Content-Type-Options)
/// 3. Enforcing HTTPS (HSTS)
/// 4. Preventing XSS (CSP, X-XSS-Protection)
/// 5. Enabling CORS for controlled access
pub async fn security_headers_middleware(
    State(security_state): State<SecurityState>,
    request: Request,
    next: Next,
) -> Response {
    let mut response = next.run(request).await;
    let headers = response.headers_mut();
    let config = &security_state.config;

    // HSTS
    if config.enable_hsts {
        headers.insert(
            "strict-transport-security",
            format!("max-age={}", config.hsts_max_age).parse().unwrap(),
        );
    }

    // X-Frame-Options
    if config.enable_frame_options {
        let value = match &config.frame_options {
            FrameOptions::Deny => "DENY",
            FrameOptions::SameOrigin => "SAMEORIGIN",
            FrameOptions::AllowFrom(origin) => origin,
        };
        headers.insert("x-frame-options", value.parse().unwrap());
    }

    // X-Content-Type-Options
    if config.enable_content_type_options {
        headers.insert("x-content-type-options", "nosniff".parse().unwrap());
    }

    // X-XSS-Protection
    if config.enable_xss_protection {
        headers.insert("x-xss-protection", "1; mode=block".parse().unwrap());
    }

    // Content-Security-Policy
    if let Some(csp) = &config.csp {
        headers.insert("content-security-policy", csp.parse().unwrap());
    }

    // CORS headers
    headers.insert(
        "access-control-allow-origin",
        config.cors_origins.join(", ").parse().unwrap(),
    );
    headers.insert(
        "access-control-allow-methods",
        config.cors_methods.join(", ").parse().unwrap(),
    );
    headers.insert(
        "access-control-allow-headers",
        config.cors_headers.join(", ").parse().unwrap(),
    );
    headers.insert(
        "access-control-max-age",
        config.cors_max_age.to_string().parse().unwrap(),
    );

    response
}

// ============================================================================
// IP Filtering Middleware (Phase 5C)
// ============================================================================

use crate::infrastructure::security::IpFilter;
use std::net::SocketAddr;

#[derive(Clone)]
pub struct IpFilterState {
    pub ip_filter: Arc<IpFilter>,
}

/// IP filtering middleware
///
/// Blocks or allows requests based on IP address rules.
/// Supports both global and per-tenant IP filtering.
///
/// # Phase 5C: Access Control
/// This middleware provides IP-based access control by:
/// 1. Extracting client IP from request
/// 2. Checking against global and tenant-specific rules
/// 3. Blocking requests from unauthorized IPs
/// 4. Supporting both allowlists and blocklists
pub async fn ip_filter_middleware(
    State(ip_filter_state): State<IpFilterState>,
    request: Request,
    next: Next,
) -> Result<Response, IpFilterError> {
    // Extract client IP address
    let client_ip = request
        .extensions()
        .get::<axum::extract::ConnectInfo<SocketAddr>>()
        .map(|connect_info| connect_info.0.ip())
        .ok_or(IpFilterError::NoIpAddress)?;

    // Check if this is a tenant-scoped request
    let result = if let Some(tenant_ctx) = request.extensions().get::<TenantContext>() {
        // Tenant-specific filtering
        ip_filter_state
            .ip_filter
            .is_allowed_for_tenant(tenant_ctx.tenant_id(), &client_ip)
    } else {
        // Global filtering only
        ip_filter_state.ip_filter.is_allowed(&client_ip)
    };

    // Block if not allowed
    if !result.allowed {
        return Err(IpFilterError::Blocked {
            reason: result.reason,
        });
    }

    // Allow request to proceed
    Ok(next.run(request).await)
}

/// Error type for IP filtering failures
#[derive(Debug)]
pub enum IpFilterError {
    NoIpAddress,
    Blocked { reason: String },
}

impl IntoResponse for IpFilterError {
    fn into_response(self) -> Response {
        match self {
            IpFilterError::NoIpAddress => (
                StatusCode::BAD_REQUEST,
                "Unable to determine client IP address",
            )
                .into_response(),
            IpFilterError::Blocked { reason } => {
                (StatusCode::FORBIDDEN, format!("Access denied: {reason}")).into_response()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::infrastructure::security::auth::Role;

    #[test]
    fn test_extract_bearer_token() {
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "Bearer test_token_123".parse().unwrap());

        let token = extract_token(&headers).unwrap();
        assert_eq!(token, "test_token_123");
    }

    #[test]
    fn test_extract_lowercase_bearer() {
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "bearer test_token_123".parse().unwrap());

        let token = extract_token(&headers).unwrap();
        assert_eq!(token, "test_token_123");
    }

    #[test]
    fn test_extract_plain_token() {
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "test_token_123".parse().unwrap());

        let token = extract_token(&headers).unwrap();
        assert_eq!(token, "test_token_123");
    }

    #[test]
    fn test_missing_auth_header() {
        let headers = HeaderMap::new();
        assert!(extract_token(&headers).is_err());
    }

    #[test]
    fn test_empty_auth_header() {
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "".parse().unwrap());
        assert!(extract_token(&headers).is_err());
    }

    #[test]
    fn test_bearer_with_empty_token() {
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "Bearer ".parse().unwrap());
        assert!(extract_token(&headers).is_err());
    }

    // -------------------------------------------------------------------------
    // US-008: Agent Permission Enforcement
    // -------------------------------------------------------------------------

    #[test]
    fn test_service_account_blocked_on_admin_paths() {
        // ServiceAccount (agent API key) must NOT have Admin permission.
        // The middleware uses require_permission(Permission::Admin) to block them.
        let claims = Claims::new(
            "agent-key".to_string(),
            "tenant1".to_string(),
            Role::ServiceAccount,
            chrono::Duration::hours(1),
        );
        let ctx = AuthContext { claims };
        assert!(
            ctx.require_permission(Permission::Admin).is_err(),
            "ServiceAccount must not have Admin permission"
        );
        // But it should still be able to read/write events
        assert!(ctx.require_permission(Permission::Read).is_ok());
        assert!(ctx.require_permission(Permission::Write).is_ok());
    }

    #[test]
    fn test_admin_role_passes_admin_paths() {
        // Admin role must have Admin permission — passes admin-only paths.
        let claims = Claims::new(
            "admin-user".to_string(),
            "tenant1".to_string(),
            Role::Admin,
            chrono::Duration::hours(1),
        );
        let ctx = AuthContext { claims };
        assert!(
            ctx.require_permission(Permission::Admin).is_ok(),
            "Admin must have Admin permission"
        );
    }

    #[test]
    fn test_developer_blocked_on_admin_paths() {
        // Developer role cannot access admin-only paths.
        let claims = Claims::new(
            "dev-user".to_string(),
            "tenant1".to_string(),
            Role::Developer,
            chrono::Duration::hours(1),
        );
        let ctx = AuthContext { claims };
        assert!(
            ctx.require_permission(Permission::Admin).is_err(),
            "Developer must not have Admin permission"
        );
    }

    #[test]
    fn test_readonly_blocked_on_admin_paths() {
        let claims = Claims::new(
            "ro-user".to_string(),
            "tenant1".to_string(),
            Role::ReadOnly,
            chrono::Duration::hours(1),
        );
        let ctx = AuthContext { claims };
        assert!(ctx.require_permission(Permission::Admin).is_err());
        assert!(ctx.require_permission(Permission::Read).is_ok());
        assert!(ctx.require_permission(Permission::Write).is_err());
    }

    #[test]
    fn test_is_admin_only_path_api_keys_create() {
        // POST to api-keys is admin-only (agent keys must not self-replicate)
        assert!(is_admin_only_path("/api/v1/auth/api-keys", "POST"));
        // Other methods on api-keys are NOT admin-only (GET to list keys)
        assert!(!is_admin_only_path("/api/v1/auth/api-keys", "GET"));
        assert!(!is_admin_only_path("/api/v1/auth/api-keys", "DELETE"));
    }

    #[test]
    fn test_is_admin_only_path_tenants() {
        // All tenant management paths are admin-only
        assert!(is_admin_only_path("/api/v1/tenants", "GET"));
        assert!(is_admin_only_path("/api/v1/tenants", "POST"));
        assert!(is_admin_only_path("/api/v1/tenants/some-id", "DELETE"));
        assert!(is_admin_only_path("/api/v1/tenants/some-id/config", "PUT"));
    }

    #[test]
    fn test_is_admin_only_path_normal_paths() {
        // Normal event/query paths are NOT admin-only
        assert!(!is_admin_only_path("/api/v1/events", "POST"));
        assert!(!is_admin_only_path("/api/v1/events/query", "GET"));
        assert!(!is_admin_only_path("/api/v1/auth/me", "GET"));
        assert!(!is_admin_only_path("/api/v1/auth/login", "POST"));
        assert!(!is_admin_only_path("/api/v1/schemas", "GET"));
    }

    #[test]
    fn test_auth_context_permissions() {
        let claims = Claims::new(
            "user1".to_string(),
            "tenant1".to_string(),
            Role::Developer,
            chrono::Duration::hours(1),
        );

        let ctx = AuthContext { claims };

        assert!(ctx.require_permission(Permission::Read).is_ok());
        assert!(ctx.require_permission(Permission::Write).is_ok());
        assert!(ctx.require_permission(Permission::Admin).is_err());
    }

    #[test]
    fn test_auth_context_admin_permissions() {
        let claims = Claims::new(
            "admin1".to_string(),
            "tenant1".to_string(),
            Role::Admin,
            chrono::Duration::hours(1),
        );

        let ctx = AuthContext { claims };

        assert!(ctx.require_permission(Permission::Read).is_ok());
        assert!(ctx.require_permission(Permission::Write).is_ok());
        assert!(ctx.require_permission(Permission::Admin).is_ok());
    }

    #[test]
    fn test_auth_context_readonly_permissions() {
        let claims = Claims::new(
            "readonly1".to_string(),
            "tenant1".to_string(),
            Role::ReadOnly,
            chrono::Duration::hours(1),
        );

        let ctx = AuthContext { claims };

        assert!(ctx.require_permission(Permission::Read).is_ok());
        assert!(ctx.require_permission(Permission::Write).is_err());
        assert!(ctx.require_permission(Permission::Admin).is_err());
    }

    #[test]
    fn test_auth_context_tenant_id() {
        let claims = Claims::new(
            "user1".to_string(),
            "my-tenant".to_string(),
            Role::Developer,
            chrono::Duration::hours(1),
        );

        let ctx = AuthContext { claims };
        assert_eq!(ctx.tenant_id(), "my-tenant");
    }

    #[test]
    fn test_auth_context_user_id() {
        let claims = Claims::new(
            "my-user".to_string(),
            "tenant1".to_string(),
            Role::Developer,
            chrono::Duration::hours(1),
        );

        let ctx = AuthContext { claims };
        assert_eq!(ctx.user_id(), "my-user");
    }

    #[test]
    fn test_request_id_new() {
        let id1 = RequestId::new();
        let id2 = RequestId::new();

        // IDs should be unique
        assert_ne!(id1.as_str(), id2.as_str());
        // IDs should be valid UUIDs (36 chars with hyphens)
        assert_eq!(id1.as_str().len(), 36);
    }

    #[test]
    fn test_request_id_default() {
        let id = RequestId::default();
        assert_eq!(id.as_str().len(), 36);
    }

    #[test]
    fn test_security_config_default() {
        let config = SecurityConfig::default();

        assert!(config.enable_hsts);
        assert_eq!(config.hsts_max_age, 31536000);
        assert!(config.enable_frame_options);
        assert!(config.enable_content_type_options);
        assert!(config.enable_xss_protection);
        assert!(config.csp.is_some());
    }

    #[test]
    fn test_frame_options_variants() {
        let deny = FrameOptions::Deny;
        let same_origin = FrameOptions::SameOrigin;
        let allow_from = FrameOptions::AllowFrom("https://example.com".to_string());

        // Check that variants are distinct via debug formatting
        assert!(format!("{deny:?}").contains("Deny"));
        assert!(format!("{same_origin:?}").contains("SameOrigin"));
        assert!(format!("{allow_from:?}").contains("AllowFrom"));
    }

    #[test]
    fn test_auth_error_from_validation_error() {
        let error = AllSourceError::ValidationError("test error".to_string());
        let auth_error = AuthError::from(error);
        assert!(format!("{auth_error:?}").contains("ValidationError"));
    }

    #[test]
    fn test_rate_limit_error_display() {
        let error = RateLimitError::RateLimitExceeded {
            retry_after: 60,
            limit: 100,
        };
        assert!(format!("{error:?}").contains("RateLimitExceeded"));

        let unauth_error = RateLimitError::Unauthorized;
        assert!(format!("{unauth_error:?}").contains("Unauthorized"));
    }

    #[test]
    fn test_tenant_error_variants() {
        let errors = vec![
            TenantError::Unauthorized,
            TenantError::InvalidTenant,
            TenantError::TenantNotFound,
            TenantError::TenantInactive,
            TenantError::RepositoryError("test".to_string()),
        ];

        for error in errors {
            // Ensure each variant can be debug-formatted
            let _ = format!("{error:?}");
        }
    }

    #[test]
    fn test_ip_filter_error_variants() {
        let errors = vec![
            IpFilterError::NoIpAddress,
            IpFilterError::Blocked {
                reason: "blocked".to_string(),
            },
        ];

        for error in errors {
            let _ = format!("{error:?}");
        }
    }

    #[test]
    fn test_security_state_clone() {
        let config = SecurityConfig::default();
        let state = SecurityState {
            config: config.clone(),
        };
        let cloned = state.clone();
        assert_eq!(cloned.config.hsts_max_age, config.hsts_max_age);
    }

    #[test]
    fn test_auth_state_clone() {
        let auth_manager = Arc::new(AuthManager::new("test-secret"));
        let state = AuthState { auth_manager };
        let cloned = state.clone();
        assert!(Arc::ptr_eq(&state.auth_manager, &cloned.auth_manager));
    }

    #[test]
    fn test_rate_limit_state_clone() {
        use crate::infrastructure::security::rate_limit::RateLimitConfig;
        let rate_limiter = Arc::new(RateLimiter::new(RateLimitConfig::free_tier()));
        let state = RateLimitState { rate_limiter };
        let cloned = state.clone();
        assert!(Arc::ptr_eq(&state.rate_limiter, &cloned.rate_limiter));
    }

    #[test]
    fn test_auth_skip_paths_contains_expected() {
        // Verify public paths are configured for auth/rate-limit skipping
        assert!(should_skip_auth("/health"));
        assert!(should_skip_auth("/metrics"));
        assert!(should_skip_auth("/api/v1/auth/register"));
        assert!(should_skip_auth("/api/v1/auth/login"));
        assert!(should_skip_auth("/api/v1/demo/seed"));

        // Verify internal endpoints bypass auth (sentinel failover)
        assert!(should_skip_auth("/internal/promote"));
        assert!(should_skip_auth("/internal/repoint"));
        assert!(should_skip_auth("/internal/anything"));

        // Verify protected paths are NOT in skip list
        assert!(!should_skip_auth("/api/v1/events"));
        assert!(!should_skip_auth("/api/v1/auth/me"));
        assert!(!should_skip_auth("/api/v1/tenants"));
    }

    #[test]
    fn test_dev_mode_auth_context() {
        let ctx = dev_mode_auth_context();

        // Dev user should have admin privileges
        assert_eq!(ctx.tenant_id(), "dev-tenant");
        assert_eq!(ctx.user_id(), "dev-user");
        assert!(ctx.require_permission(Permission::Admin).is_ok());
        assert!(ctx.require_permission(Permission::Read).is_ok());
        assert!(ctx.require_permission(Permission::Write).is_ok());
    }

    #[test]
    fn test_dev_mode_disabled_by_default() {
        // Dev mode should be disabled by default (env var not set in tests)
        // Note: This test may fail if ALLSOURCE_DEV_MODE is set in the test environment
        // In a clean environment, dev mode is disabled
        let env_value = std::env::var("ALLSOURCE_DEV_MODE").unwrap_or_default();
        if env_value.is_empty() {
            assert!(!is_dev_mode());
        }
    }
}