Skip to main content

allsource_core/infrastructure/security/
middleware.rs

1use crate::{
2    error::AllSourceError,
3    infrastructure::security::{
4        auth::{AuthManager, Claims, Permission, Role},
5        rate_limit::{RateLimitConfig, RateLimiter},
6    },
7};
8use axum::{
9    extract::{Request, State},
10    http::{HeaderMap, StatusCode},
11    middleware::Next,
12    response::{IntoResponse, Response},
13};
14use std::sync::{Arc, LazyLock};
15
16/// Paths that bypass authentication (exact match)
17pub const AUTH_SKIP_PATHS: &[&str] = &[
18    "/health",
19    "/metrics",
20    "/api/v1/auth/register",
21    "/api/v1/auth/login",
22    "/api/v1/demo/seed",
23];
24
25/// Path prefixes that bypass authentication and rate limiting.
26///
27/// - `/internal/` — sentinel failover endpoints; must not require API keys or
28///   be rate-limited, otherwise failover can timeout or fail when credentials
29///   are unavailable.
30/// - `/api/v1/events`, `/api/v1/projections`, `/api/v1/schemas`,
31///   `/api/v1/consumers`, `/api/v1/stats`, `/api/v1/entities`,
32///   `/api/v1/duplicates`, `/api/v1/streams`, `/api/v1/replay`,
33///   `/api/v1/webhooks`, `/api/v1/compaction`, `/api/v1/pipelines`,
34///   `/api/v1/graphql`, `/api/v1/read-costs` — data-plane routes. Core is internal-only; the gateway
35///   authenticates the caller and injects its `tenant_id` (query parameter, or
36///   the ingest body) before forwarding, so no auth context reaches these
37///   handlers and that injected `tenant_id` is the only tenant they see.
38///   `/api/v1/event-feed` and `/api/v1/read-models` are not listed: they
39///   authenticate here and take the tenant from the credential.
40pub const AUTH_SKIP_PREFIXES: &[&str] = &[
41    "/internal/",
42    "/api/v1/events",
43    "/api/v1/projections",
44    "/api/v1/schemas",
45    "/api/v1/consumers",
46    "/api/v1/stats",
47    "/api/v1/entities",
48    "/api/v1/duplicates",
49    "/api/v1/streams",
50    "/api/v1/replay",
51    "/api/v1/webhooks",
52    "/api/v1/compaction",
53    "/api/v1/pipelines",
54    "/api/v1/graphql",
55    "/api/v1/read-costs",
56];
57
58/// Check if a path should skip authentication and rate limiting.
59///
60/// Paths that STILL require auth after the internal-only cutover:
61/// - `/api/v1/auth/me` — used by CP's ValidateAPIKey fallback for legacy keys
62/// - `/api/v1/auth/api-keys` — admin-only; used by CP's CreateCoreAPIKey
63/// - `/api/v1/tenants/*` — admin-only tenant management
64///
65/// Everything else is skipped: internal network trust + handler-level
66/// tenant-from-body is the security model now.
67#[inline]
68pub fn should_skip_auth(path: &str) -> bool {
69    AUTH_SKIP_PATHS.contains(&path) || AUTH_SKIP_PREFIXES.iter().any(|pfx| path.starts_with(pfx))
70}
71
72/// Check if development mode is enabled via environment variable.
73/// When enabled, authentication and rate limiting are bypassed for local
74/// development (e.g., MCP server integration, quick curl queries against
75/// `/api/v1/events/query` without generating a JWT).
76///
77/// Set any of the following to `true`/`1` to enable:
78/// - `ALLSOURCE_DEV_MODE` — historical name, still supported
79/// - `ALLSOURCE_AUTH_DISABLED` — explicit "turn auth off" alias (issue #131)
80///
81/// **WARNING**: Never enable this in production environments! The feature
82/// grants admin context to any request that arrives without a token.
83fn env_flag_enabled(name: &str) -> bool {
84    std::env::var(name).is_ok_and(|v| matches!(v.to_lowercase().as_str(), "true" | "1" | "yes"))
85}
86
87static DEV_MODE_ENABLED: LazyLock<bool> = LazyLock::new(|| {
88    let via_dev = env_flag_enabled("ALLSOURCE_DEV_MODE");
89    let via_auth_off = env_flag_enabled("ALLSOURCE_AUTH_DISABLED");
90    let enabled = via_dev || via_auth_off;
91    if enabled {
92        let source = if via_auth_off && via_dev {
93            "ALLSOURCE_DEV_MODE + ALLSOURCE_AUTH_DISABLED"
94        } else if via_auth_off {
95            "ALLSOURCE_AUTH_DISABLED"
96        } else {
97            "ALLSOURCE_DEV_MODE"
98        };
99        tracing::warn!(
100            "⚠️  Auth disabled via {source} — all requests run as admin with no rate limits. DO NOT use in production."
101        );
102    }
103    enabled
104});
105
106/// Check if dev mode is enabled
107#[inline]
108pub fn is_dev_mode() -> bool {
109    *DEV_MODE_ENABLED
110}
111
112/// Create a development-mode AuthContext with admin privileges
113fn dev_mode_auth_context() -> AuthContext {
114    AuthContext {
115        claims: Claims::new(
116            "dev-user".to_string(),
117            "dev-tenant".to_string(),
118            Role::Admin,
119            chrono::Duration::hours(24),
120        ),
121    }
122}
123
124/// Authentication state shared across requests
125#[derive(Clone)]
126pub struct AuthState {
127    pub auth_manager: Arc<AuthManager>,
128}
129
130/// Rate limiting state
131#[derive(Clone)]
132pub struct RateLimitState {
133    pub rate_limiter: Arc<RateLimiter>,
134    pub egress_rate_limiter: Arc<RateLimiter>,
135    pub read_model_reads: Arc<RateLimiter>,
136    pub read_model_writes: Arc<RateLimiter>,
137}
138
139impl RateLimitState {
140    pub fn new(rate_limiter: Arc<RateLimiter>) -> Self {
141        Self {
142            rate_limiter,
143            read_model_reads: Arc::new(RateLimiter::new(RateLimitConfig {
144                requests_per_minute: 6000,
145                burst_size: 1000,
146            })),
147            read_model_writes: Arc::new(RateLimiter::new(RateLimitConfig {
148                requests_per_minute: 600,
149                burst_size: 120,
150            })),
151            // Each admitted data response reserves and completes one ledger entry.
152            egress_rate_limiter: Arc::new(RateLimiter::new(RateLimitConfig {
153                requests_per_minute: 1200,
154                burst_size: 2000,
155            })),
156        }
157    }
158}
159
160/// Authenticated request context
161#[derive(Debug, Clone)]
162pub struct AuthContext {
163    pub claims: Claims,
164}
165
166impl AuthContext {
167    /// Check if user has required permission
168    pub fn require_permission(&self, permission: Permission) -> Result<(), AllSourceError> {
169        if self.claims.has_permission(permission) {
170            Ok(())
171        } else {
172            Err(AllSourceError::ValidationError(
173                "Insufficient permissions".to_string(),
174            ))
175        }
176    }
177
178    /// Get tenant ID from context
179    pub fn tenant_id(&self) -> &str {
180        &self.claims.tenant_id
181    }
182
183    /// Get user ID from context
184    pub fn user_id(&self) -> &str {
185        &self.claims.sub
186    }
187}
188
189/// Extract token from Authorization header, with X-API-Key fallback for backwards compatibility.
190fn extract_token(headers: &HeaderMap) -> Result<String, AllSourceError> {
191    // Primary: Authorization header (Bearer <token> or plain <token>)
192    // Fallback: X-API-Key header (legacy, deprecated)
193    let auth_header = if let Some(val) = headers.get("authorization") {
194        val.to_str()
195            .map_err(|_| {
196                AllSourceError::ValidationError("Invalid authorization header".to_string())
197            })?
198            .to_string()
199    } else if let Some(val) = headers.get("x-api-key") {
200        val.to_str()
201            .map_err(|_| AllSourceError::ValidationError("Invalid X-API-Key header".to_string()))?
202            .to_string()
203    } else {
204        return Err(AllSourceError::ValidationError(
205            "Missing authorization header".to_string(),
206        ));
207    };
208
209    // Support both "Bearer <token>" and "<token>" formats
210    let token = if auth_header.starts_with("Bearer ") {
211        auth_header.trim_start_matches("Bearer ").trim()
212    } else if auth_header.starts_with("bearer ") {
213        auth_header.trim_start_matches("bearer ").trim()
214    } else {
215        auth_header.trim()
216    };
217
218    if token.is_empty() {
219        return Err(AllSourceError::ValidationError(
220            "Empty authorization token".to_string(),
221        ));
222    }
223
224    Ok(token.to_string())
225}
226
227/// Returns true for paths that require Admin permission regardless of other checks.
228///
229/// - POST /api/v1/auth/api-keys — key creation (agents must not self-replicate)
230/// - /api/v1/tenants/* — tenant management (agents must not alter tenants)
231///
232/// Note: /api/v1/auth/register is in AUTH_SKIP_PATHS (public self-registration) and
233/// additionally enforces Admin at the handler level when any auth token is present.
234#[inline]
235pub fn is_admin_only_path(path: &str, method: &str) -> bool {
236    (path == "/api/v1/auth/api-keys" && method == "POST") || path.starts_with("/api/v1/tenants")
237}
238
239/// Authentication middleware
240pub async fn auth_middleware(
241    State(auth_state): State<AuthState>,
242    mut request: Request,
243    next: Next,
244) -> Result<Response, AuthError> {
245    // Skip authentication for public and internal paths
246    let path = request.uri().path();
247    if should_skip_auth(path) {
248        return Ok(next.run(request).await);
249    }
250
251    // Dev mode: if a valid token is present, authenticate normally so that
252    // /me returns the real tenant_id (not a hardcoded "dev-tenant").
253    // Fall back to the synthetic dev context only when no token is provided.
254    if is_dev_mode() {
255        let headers = request.headers();
256        let auth_ctx = match extract_token(headers) {
257            Ok(token) => {
258                let claims = if token.starts_with("ask_") {
259                    auth_state.auth_manager.validate_api_key(&token).ok()
260                } else {
261                    auth_state.auth_manager.validate_token(&token).ok()
262                };
263                claims.map_or_else(dev_mode_auth_context, |c| AuthContext { claims: c })
264            }
265            Err(_) => dev_mode_auth_context(),
266        };
267        request.extensions_mut().insert(auth_ctx);
268        return Ok(next.run(request).await);
269    }
270
271    let headers = request.headers();
272
273    // Extract and validate token (JWT or API key)
274    let token = extract_token(headers)?;
275
276    let claims = if token.starts_with("ask_") {
277        // API Key authentication
278        auth_state.auth_manager.validate_api_key(&token)?
279    } else {
280        // JWT authentication
281        auth_state.auth_manager.validate_token(&token)?
282    };
283
284    let auth_ctx = AuthContext { claims };
285
286    // Enforce that service accounts (agent API keys) cannot access admin-only paths.
287    // Admin-only paths: user registration, API key creation, and all tenant management.
288    // These are also enforced at handler level; this middleware block provides defence-in-depth.
289    let path = request.uri().path();
290    let method = request.method().as_str();
291    let is_admin_only_path = is_admin_only_path(path, method);
292
293    if is_admin_only_path {
294        auth_ctx
295            .require_permission(Permission::Admin)
296            .map_err(|_| {
297                AuthError(AllSourceError::ValidationError(
298                    "Admin permission required".to_string(),
299                ))
300            })?;
301    }
302
303    // Insert auth context into request extensions
304    request.extensions_mut().insert(auth_ctx);
305
306    Ok(next.run(request).await)
307}
308
309/// Optional authentication middleware (allows unauthenticated requests)
310pub async fn optional_auth_middleware(
311    State(auth_state): State<AuthState>,
312    mut request: Request,
313    next: Next,
314) -> Response {
315    let headers = request.headers();
316
317    if let Ok(token) = extract_token(headers) {
318        // Try to authenticate, but don't fail if invalid
319        let claims = if token.starts_with("ask_") {
320            auth_state.auth_manager.validate_api_key(&token).ok()
321        } else {
322            auth_state.auth_manager.validate_token(&token).ok()
323        };
324
325        if let Some(claims) = claims {
326            request.extensions_mut().insert(AuthContext { claims });
327        }
328    }
329
330    next.run(request).await
331}
332
333/// Error type for authentication failures
334#[derive(Debug)]
335pub struct AuthError(AllSourceError);
336
337impl From<AllSourceError> for AuthError {
338    fn from(err: AllSourceError) -> Self {
339        AuthError(err)
340    }
341}
342
343impl IntoResponse for AuthError {
344    fn into_response(self) -> Response {
345        let (status, message) = match self.0 {
346            AllSourceError::ValidationError(msg) => (StatusCode::UNAUTHORIZED, msg),
347            _ => (
348                StatusCode::INTERNAL_SERVER_ERROR,
349                "Internal server error".to_string(),
350            ),
351        };
352
353        (status, message).into_response()
354    }
355}
356
357/// Axum extractor for authenticated requests
358pub struct Authenticated(pub AuthContext);
359
360impl<S> axum::extract::FromRequestParts<S> for Authenticated
361where
362    S: Send + Sync,
363{
364    type Rejection = (StatusCode, &'static str);
365
366    // `async fn` is the signature axum declares for `FromRequestParts`; it is
367    // not ours to change. Extensions are already populated by the auth layer,
368    // so this particular extractor happens to need no `.await` — sibling
369    // extractors that hit the token store do. Keep the trait's shape.
370    #[allow(unknown_lints, clippy::unused_async_trait_impl)]
371    async fn from_request_parts(
372        parts: &mut axum::http::request::Parts,
373        _state: &S,
374    ) -> Result<Self, Self::Rejection> {
375        parts
376            .extensions
377            .get::<AuthContext>()
378            .cloned()
379            .map(Authenticated)
380            .ok_or((StatusCode::UNAUTHORIZED, "Unauthorized"))
381    }
382}
383
384/// Axum extractor for optional authentication (never rejects, returns Option)
385/// Use this for routes that work with or without authentication
386pub struct OptionalAuth(pub Option<AuthContext>);
387
388impl<S> axum::extract::FromRequestParts<S> for OptionalAuth
389where
390    S: Send + Sync,
391{
392    type Rejection = std::convert::Infallible;
393
394    // `async fn` is dictated by axum's `FromRequestParts` trait, not by this body.
395    #[allow(unknown_lints, clippy::unused_async_trait_impl)]
396    async fn from_request_parts(
397        parts: &mut axum::http::request::Parts,
398        _state: &S,
399    ) -> Result<Self, Self::Rejection> {
400        Ok(OptionalAuth(parts.extensions.get::<AuthContext>().cloned()))
401    }
402}
403
404/// Axum extractor for admin-only requests
405pub struct Admin(pub AuthContext);
406
407impl<S> axum::extract::FromRequestParts<S> for Admin
408where
409    S: Send + Sync,
410{
411    type Rejection = (StatusCode, &'static str);
412
413    // `async fn` is dictated by axum's `FromRequestParts` trait, not by this body.
414    #[allow(unknown_lints, clippy::unused_async_trait_impl)]
415    async fn from_request_parts(
416        parts: &mut axum::http::request::Parts,
417        _state: &S,
418    ) -> Result<Self, Self::Rejection> {
419        let auth_ctx = parts
420            .extensions
421            .get::<AuthContext>()
422            .cloned()
423            .ok_or((StatusCode::UNAUTHORIZED, "Unauthorized"))?;
424
425        auth_ctx
426            .require_permission(Permission::Admin)
427            .map_err(|_| (StatusCode::FORBIDDEN, "Admin permission required"))?;
428
429        Ok(Admin(auth_ctx))
430    }
431}
432
433/// Rate limiting middleware
434/// Checks rate limits based on tenant_id from auth context
435pub async fn rate_limit_middleware(
436    State(rate_limit_state): State<RateLimitState>,
437    request: Request,
438    next: Next,
439) -> Result<Response, RateLimitError> {
440    // Skip rate limiting for public and internal paths
441    let path = request.uri().path();
442    if should_skip_auth(path) {
443        return Ok(next.run(request).await);
444    }
445
446    // Dev mode: bypass rate limiting entirely
447    if is_dev_mode() {
448        return Ok(next.run(request).await);
449    }
450
451    // Extract auth context from request
452    let auth_ctx = request
453        .extensions()
454        .get::<AuthContext>()
455        .ok_or(RateLimitError::Unauthorized)?;
456
457    let ledger_tenant = path
458        .strip_prefix("/api/v1/tenants/")
459        .and_then(|suffix| suffix.strip_suffix("/egress"))
460        .filter(|tenant| !tenant.is_empty() && !tenant.contains('/'))
461        .filter(|_| auth_ctx.claims.has_permission(Permission::Admin));
462    let read_model_path = path == "/api/v1/event-feed"
463        || path
464            .strip_prefix("/api/v1/read-models/")
465            .is_some_and(|name| !name.is_empty() && !name.contains('/'));
466    let result = if read_model_path {
467        if request.method() == axum::http::Method::GET {
468            rate_limit_state
469                .read_model_reads
470                .check_rate_limit(auth_ctx.tenant_id())
471        } else {
472            rate_limit_state
473                .read_model_writes
474                .check_rate_limit(auth_ctx.tenant_id())
475        }
476    } else if let Some(tenant) = ledger_tenant {
477        rate_limit_state
478            .egress_rate_limiter
479            .check_rate_limit(tenant)
480    } else {
481        rate_limit_state
482            .rate_limiter
483            .check_rate_limit(auth_ctx.tenant_id())
484    };
485
486    if !result.allowed {
487        return Err(RateLimitError::RateLimitExceeded {
488            retry_after: result.retry_after.unwrap_or_default().as_secs(),
489            limit: result.limit,
490        });
491    }
492
493    // Add rate limit headers to response
494    let mut response = next.run(request).await;
495    let headers = response.headers_mut();
496    headers.insert(
497        "X-RateLimit-Limit",
498        result.limit.to_string().parse().unwrap(),
499    );
500    headers.insert(
501        "X-RateLimit-Remaining",
502        result.remaining.to_string().parse().unwrap(),
503    );
504
505    Ok(response)
506}
507
508/// Error type for rate limiting failures
509#[derive(Debug)]
510pub enum RateLimitError {
511    RateLimitExceeded { retry_after: u64, limit: u32 },
512    Unauthorized,
513}
514
515impl IntoResponse for RateLimitError {
516    fn into_response(self) -> Response {
517        match self {
518            RateLimitError::RateLimitExceeded { retry_after, limit } => {
519                let mut response = (
520                    StatusCode::TOO_MANY_REQUESTS,
521                    format!("Rate limit exceeded. Limit: {limit} requests/min"),
522                )
523                    .into_response();
524
525                if retry_after > 0 {
526                    response
527                        .headers_mut()
528                        .insert("Retry-After", retry_after.to_string().parse().unwrap());
529                }
530
531                response
532            }
533            RateLimitError::Unauthorized => (
534                StatusCode::UNAUTHORIZED,
535                "Authentication required for rate limiting",
536            )
537                .into_response(),
538        }
539    }
540}
541
542/// Helper macro to require specific permission
543#[macro_export]
544macro_rules! require_permission {
545    ($auth:expr, $perm:expr) => {
546        $auth.0.require_permission($perm).map_err(|_| {
547            (
548                axum::http::StatusCode::FORBIDDEN,
549                "Insufficient permissions",
550            )
551        })?
552    };
553}
554
555// ============================================================================
556// Tenant Isolation Middleware (Phase 5B)
557// ============================================================================
558
559use crate::domain::{entities::Tenant, repositories::TenantRepository, value_objects::TenantId};
560
561/// Tenant isolation state for middleware
562#[derive(Clone)]
563pub struct TenantState<R: TenantRepository> {
564    pub tenant_repository: Arc<R>,
565}
566
567/// Validated tenant context injected into requests
568///
569/// This context is created by the tenant_isolation_middleware after
570/// validating that the tenant exists and is active.
571#[derive(Debug, Clone)]
572pub struct TenantContext {
573    pub tenant: Tenant,
574}
575
576impl TenantContext {
577    /// Get the tenant ID
578    pub fn tenant_id(&self) -> &TenantId {
579        self.tenant.id()
580    }
581
582    /// Check if tenant is active
583    pub fn is_active(&self) -> bool {
584        self.tenant.is_active()
585    }
586}
587
588/// Tenant isolation middleware
589///
590/// Validates that the authenticated tenant exists and is active.
591/// Injects TenantContext into the request for use by handlers.
592///
593/// # Phase 5B: Tenant Isolation
594/// This middleware enforces tenant boundaries by:
595/// 1. Extracting tenant_id from AuthContext
596/// 2. Loading tenant from repository
597/// 3. Validating tenant is active
598/// 4. Injecting TenantContext into request extensions
599///
600/// Must be applied after auth_middleware.
601pub async fn tenant_isolation_middleware<R: TenantRepository + 'static>(
602    State(tenant_state): State<TenantState<R>>,
603    mut request: Request,
604    next: Next,
605) -> Result<Response, TenantError> {
606    // Extract auth context (must be authenticated)
607    let auth_ctx = request
608        .extensions()
609        .get::<AuthContext>()
610        .ok_or(TenantError::Unauthorized)?
611        .clone();
612
613    // Parse tenant ID
614    let tenant_id =
615        TenantId::new(auth_ctx.tenant_id().to_string()).map_err(|_| TenantError::InvalidTenant)?;
616
617    // Load tenant from repository
618    let tenant = tenant_state
619        .tenant_repository
620        .find_by_id(&tenant_id)
621        .await
622        .map_err(|e| TenantError::RepositoryError(e.to_string()))?
623        .ok_or(TenantError::TenantNotFound)?;
624
625    // Validate tenant is active
626    if !tenant.is_active() {
627        return Err(TenantError::TenantInactive);
628    }
629
630    // Inject tenant context into request
631    request.extensions_mut().insert(TenantContext { tenant });
632
633    // Continue to next middleware/handler
634    Ok(next.run(request).await)
635}
636
637/// Error type for tenant isolation failures
638#[derive(Debug)]
639pub enum TenantError {
640    Unauthorized,
641    InvalidTenant,
642    TenantNotFound,
643    TenantInactive,
644    RepositoryError(String),
645}
646
647impl IntoResponse for TenantError {
648    fn into_response(self) -> Response {
649        let (status, message) = match self {
650            TenantError::Unauthorized => (
651                StatusCode::UNAUTHORIZED,
652                "Authentication required for tenant access",
653            ),
654            TenantError::InvalidTenant => (StatusCode::BAD_REQUEST, "Invalid tenant identifier"),
655            TenantError::TenantNotFound => (StatusCode::NOT_FOUND, "Tenant not found"),
656            TenantError::TenantInactive => (StatusCode::FORBIDDEN, "Tenant is inactive"),
657            TenantError::RepositoryError(_) => (
658                StatusCode::INTERNAL_SERVER_ERROR,
659                "Failed to validate tenant",
660            ),
661        };
662
663        (status, message).into_response()
664    }
665}
666
667// ============================================================================
668// Request ID Middleware (Phase 5C)
669// ============================================================================
670
671use uuid::Uuid;
672
673/// Request context with unique ID for tracing
674#[derive(Debug, Clone)]
675pub struct RequestId(pub String);
676
677impl Default for RequestId {
678    fn default() -> Self {
679        Self::new()
680    }
681}
682
683impl RequestId {
684    /// Generate a new request ID
685    pub fn new() -> Self {
686        Self(Uuid::new_v4().to_string())
687    }
688
689    /// Get the request ID as a string
690    pub fn as_str(&self) -> &str {
691        &self.0
692    }
693}
694
695/// Request ID middleware
696///
697/// Generates a unique request ID for each request and injects it into:
698/// - Request extensions (for use in handlers/logging)
699/// - Response headers (X-Request-ID)
700///
701/// If the request already has an X-Request-ID header, it will be used instead.
702///
703/// # Phase 5C: Request Tracing
704/// This middleware enables distributed tracing by:
705/// 1. Generating unique IDs for each request
706/// 2. Propagating IDs through the request lifecycle
707/// 3. Returning IDs in response headers
708/// 4. Supporting client-provided request IDs
709pub async fn request_id_middleware(mut request: Request, next: Next) -> Response {
710    // Check if request already has a request ID
711    let request_id = request
712        .headers()
713        .get("x-request-id")
714        .and_then(|v| v.to_str().ok())
715        .map_or_else(RequestId::new, |s| RequestId(s.to_string()));
716
717    // Store request ID in extensions
718    request.extensions_mut().insert(request_id.clone());
719
720    // Process request
721    let mut response = next.run(request).await;
722
723    // Add request ID to response headers
724    response
725        .headers_mut()
726        .insert("x-request-id", request_id.0.parse().unwrap());
727
728    response
729}
730
731// ============================================================================
732// Security Headers Middleware (Phase 5C)
733// ============================================================================
734
735/// Security headers configuration
736#[derive(Debug, Clone)]
737pub struct SecurityConfig {
738    /// Enable HSTS (HTTP Strict Transport Security)
739    pub enable_hsts: bool,
740    /// HSTS max age in seconds
741    pub hsts_max_age: u32,
742    /// Enable X-Frame-Options
743    pub enable_frame_options: bool,
744    /// X-Frame-Options value
745    pub frame_options: FrameOptions,
746    /// Enable X-Content-Type-Options
747    pub enable_content_type_options: bool,
748    /// Enable X-XSS-Protection
749    pub enable_xss_protection: bool,
750    /// Content Security Policy
751    pub csp: Option<String>,
752    /// CORS allowed origins
753    pub cors_origins: Vec<String>,
754    /// CORS allowed methods
755    pub cors_methods: Vec<String>,
756    /// CORS allowed headers
757    pub cors_headers: Vec<String>,
758    /// CORS max age
759    pub cors_max_age: u32,
760}
761
762#[derive(Debug, Clone)]
763pub enum FrameOptions {
764    Deny,
765    SameOrigin,
766    AllowFrom(String),
767}
768
769impl Default for SecurityConfig {
770    fn default() -> Self {
771        Self {
772            enable_hsts: true,
773            hsts_max_age: 31_536_000, // 1 year
774            enable_frame_options: true,
775            frame_options: FrameOptions::Deny,
776            enable_content_type_options: true,
777            enable_xss_protection: true,
778            csp: Some("default-src 'self'".to_string()),
779            cors_origins: vec!["*".to_string()],
780            cors_methods: vec![
781                "GET".to_string(),
782                "POST".to_string(),
783                "PUT".to_string(),
784                "DELETE".to_string(),
785            ],
786            cors_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
787            cors_max_age: 3600,
788        }
789    }
790}
791
792#[derive(Clone)]
793pub struct SecurityState {
794    pub config: SecurityConfig,
795}
796
797/// Security headers middleware
798///
799/// Adds security-related HTTP headers to all responses:
800/// - HSTS (Strict-Transport-Security)
801/// - X-Frame-Options
802/// - X-Content-Type-Options
803/// - X-XSS-Protection
804/// - Content-Security-Policy
805/// - CORS headers
806///
807/// # Phase 5C: Security Hardening
808/// This middleware provides defense-in-depth by:
809/// 1. Preventing clickjacking (X-Frame-Options)
810/// 2. Preventing MIME sniffing (X-Content-Type-Options)
811/// 3. Enforcing HTTPS (HSTS)
812/// 4. Preventing XSS (CSP, X-XSS-Protection)
813/// 5. Enabling CORS for controlled access
814pub async fn security_headers_middleware(
815    State(security_state): State<SecurityState>,
816    request: Request,
817    next: Next,
818) -> Response {
819    let mut response = next.run(request).await;
820    let headers = response.headers_mut();
821    let config = &security_state.config;
822
823    // HSTS
824    if config.enable_hsts {
825        headers.insert(
826            "strict-transport-security",
827            format!("max-age={}", config.hsts_max_age).parse().unwrap(),
828        );
829    }
830
831    // X-Frame-Options
832    if config.enable_frame_options {
833        let value = match &config.frame_options {
834            FrameOptions::Deny => "DENY",
835            FrameOptions::SameOrigin => "SAMEORIGIN",
836            FrameOptions::AllowFrom(origin) => origin,
837        };
838        headers.insert("x-frame-options", value.parse().unwrap());
839    }
840
841    // X-Content-Type-Options
842    if config.enable_content_type_options {
843        headers.insert("x-content-type-options", "nosniff".parse().unwrap());
844    }
845
846    // X-XSS-Protection
847    if config.enable_xss_protection {
848        headers.insert("x-xss-protection", "1; mode=block".parse().unwrap());
849    }
850
851    // Content-Security-Policy
852    if let Some(csp) = &config.csp {
853        headers.insert("content-security-policy", csp.parse().unwrap());
854    }
855
856    // CORS headers
857    headers.insert(
858        "access-control-allow-origin",
859        config.cors_origins.join(", ").parse().unwrap(),
860    );
861    headers.insert(
862        "access-control-allow-methods",
863        config.cors_methods.join(", ").parse().unwrap(),
864    );
865    headers.insert(
866        "access-control-allow-headers",
867        config.cors_headers.join(", ").parse().unwrap(),
868    );
869    headers.insert(
870        "access-control-max-age",
871        config.cors_max_age.to_string().parse().unwrap(),
872    );
873
874    response
875}
876
877// ============================================================================
878// IP Filtering Middleware (Phase 5C)
879// ============================================================================
880
881use crate::infrastructure::security::IpFilter;
882use std::net::SocketAddr;
883
884#[derive(Clone)]
885pub struct IpFilterState {
886    pub ip_filter: Arc<IpFilter>,
887}
888
889/// IP filtering middleware
890///
891/// Blocks or allows requests based on IP address rules.
892/// Supports both global and per-tenant IP filtering.
893///
894/// # Phase 5C: Access Control
895/// This middleware provides IP-based access control by:
896/// 1. Extracting client IP from request
897/// 2. Checking against global and tenant-specific rules
898/// 3. Blocking requests from unauthorized IPs
899/// 4. Supporting both allowlists and blocklists
900pub async fn ip_filter_middleware(
901    State(ip_filter_state): State<IpFilterState>,
902    request: Request,
903    next: Next,
904) -> Result<Response, IpFilterError> {
905    // Extract client IP address
906    let client_ip = request
907        .extensions()
908        .get::<axum::extract::ConnectInfo<SocketAddr>>()
909        .map(|connect_info| connect_info.0.ip())
910        .ok_or(IpFilterError::NoIpAddress)?;
911
912    // Check if this is a tenant-scoped request
913    let result = if let Some(tenant_ctx) = request.extensions().get::<TenantContext>() {
914        // Tenant-specific filtering
915        ip_filter_state
916            .ip_filter
917            .is_allowed_for_tenant(tenant_ctx.tenant_id(), &client_ip)
918    } else {
919        // Global filtering only
920        ip_filter_state.ip_filter.is_allowed(&client_ip)
921    };
922
923    // Block if not allowed
924    if !result.allowed {
925        return Err(IpFilterError::Blocked {
926            reason: result.reason,
927        });
928    }
929
930    // Allow request to proceed
931    Ok(next.run(request).await)
932}
933
934/// Error type for IP filtering failures
935#[derive(Debug)]
936pub enum IpFilterError {
937    NoIpAddress,
938    Blocked { reason: String },
939}
940
941impl IntoResponse for IpFilterError {
942    fn into_response(self) -> Response {
943        match self {
944            IpFilterError::NoIpAddress => (
945                StatusCode::BAD_REQUEST,
946                "Unable to determine client IP address",
947            )
948                .into_response(),
949            IpFilterError::Blocked { reason } => {
950                (StatusCode::FORBIDDEN, format!("Access denied: {reason}")).into_response()
951            }
952        }
953    }
954}
955
956#[cfg(test)]
957mod tests {
958    use super::*;
959    use crate::infrastructure::security::auth::Role;
960
961    #[test]
962    fn test_extract_bearer_token() {
963        let mut headers = HeaderMap::new();
964        headers.insert("authorization", "Bearer test_token_123".parse().unwrap());
965
966        let token = extract_token(&headers).unwrap();
967        assert_eq!(token, "test_token_123");
968    }
969
970    #[test]
971    fn test_extract_lowercase_bearer() {
972        let mut headers = HeaderMap::new();
973        headers.insert("authorization", "bearer test_token_123".parse().unwrap());
974
975        let token = extract_token(&headers).unwrap();
976        assert_eq!(token, "test_token_123");
977    }
978
979    #[test]
980    fn test_extract_plain_token() {
981        let mut headers = HeaderMap::new();
982        headers.insert("authorization", "test_token_123".parse().unwrap());
983
984        let token = extract_token(&headers).unwrap();
985        assert_eq!(token, "test_token_123");
986    }
987
988    #[test]
989    fn test_missing_auth_header() {
990        let headers = HeaderMap::new();
991        assert!(extract_token(&headers).is_err());
992    }
993
994    #[test]
995    fn test_empty_auth_header() {
996        let mut headers = HeaderMap::new();
997        headers.insert("authorization", "".parse().unwrap());
998        assert!(extract_token(&headers).is_err());
999    }
1000
1001    #[test]
1002    fn test_bearer_with_empty_token() {
1003        let mut headers = HeaderMap::new();
1004        headers.insert("authorization", "Bearer ".parse().unwrap());
1005        assert!(extract_token(&headers).is_err());
1006    }
1007
1008    // -------------------------------------------------------------------------
1009    // US-008: Agent Permission Enforcement
1010    // -------------------------------------------------------------------------
1011
1012    #[test]
1013    fn test_service_account_blocked_on_admin_paths() {
1014        // ServiceAccount (agent API key) must NOT have Admin permission.
1015        // The middleware uses require_permission(Permission::Admin) to block them.
1016        let claims = Claims::new(
1017            "agent-key".to_string(),
1018            "tenant1".to_string(),
1019            Role::ServiceAccount,
1020            chrono::Duration::hours(1),
1021        );
1022        let ctx = AuthContext { claims };
1023        assert!(
1024            ctx.require_permission(Permission::Admin).is_err(),
1025            "ServiceAccount must not have Admin permission"
1026        );
1027        // But it should still be able to read/write events
1028        assert!(ctx.require_permission(Permission::Read).is_ok());
1029        assert!(ctx.require_permission(Permission::Write).is_ok());
1030    }
1031
1032    #[test]
1033    fn test_admin_role_passes_admin_paths() {
1034        // Admin role must have Admin permission — passes admin-only paths.
1035        let claims = Claims::new(
1036            "admin-user".to_string(),
1037            "tenant1".to_string(),
1038            Role::Admin,
1039            chrono::Duration::hours(1),
1040        );
1041        let ctx = AuthContext { claims };
1042        assert!(
1043            ctx.require_permission(Permission::Admin).is_ok(),
1044            "Admin must have Admin permission"
1045        );
1046    }
1047
1048    #[test]
1049    fn test_developer_blocked_on_admin_paths() {
1050        // Developer role cannot access admin-only paths.
1051        let claims = Claims::new(
1052            "dev-user".to_string(),
1053            "tenant1".to_string(),
1054            Role::Developer,
1055            chrono::Duration::hours(1),
1056        );
1057        let ctx = AuthContext { claims };
1058        assert!(
1059            ctx.require_permission(Permission::Admin).is_err(),
1060            "Developer must not have Admin permission"
1061        );
1062    }
1063
1064    #[test]
1065    fn test_readonly_blocked_on_admin_paths() {
1066        let claims = Claims::new(
1067            "ro-user".to_string(),
1068            "tenant1".to_string(),
1069            Role::ReadOnly,
1070            chrono::Duration::hours(1),
1071        );
1072        let ctx = AuthContext { claims };
1073        assert!(ctx.require_permission(Permission::Admin).is_err());
1074        assert!(ctx.require_permission(Permission::Read).is_ok());
1075        assert!(ctx.require_permission(Permission::Write).is_err());
1076    }
1077
1078    #[test]
1079    fn test_is_admin_only_path_api_keys_create() {
1080        // POST to api-keys is admin-only (agent keys must not self-replicate)
1081        assert!(is_admin_only_path("/api/v1/auth/api-keys", "POST"));
1082        // Other methods on api-keys are NOT admin-only (GET to list keys)
1083        assert!(!is_admin_only_path("/api/v1/auth/api-keys", "GET"));
1084        assert!(!is_admin_only_path("/api/v1/auth/api-keys", "DELETE"));
1085    }
1086
1087    #[test]
1088    fn test_is_admin_only_path_tenants() {
1089        // All tenant management paths are admin-only
1090        assert!(is_admin_only_path("/api/v1/tenants", "GET"));
1091        assert!(is_admin_only_path("/api/v1/tenants", "POST"));
1092        assert!(is_admin_only_path("/api/v1/tenants/some-id", "DELETE"));
1093        assert!(is_admin_only_path("/api/v1/tenants/some-id/config", "PUT"));
1094    }
1095
1096    #[test]
1097    fn test_is_admin_only_path_normal_paths() {
1098        // Normal event/query paths are NOT admin-only
1099        assert!(!is_admin_only_path("/api/v1/events", "POST"));
1100        assert!(!is_admin_only_path("/api/v1/events/query", "GET"));
1101        assert!(!is_admin_only_path("/api/v1/auth/me", "GET"));
1102        assert!(!is_admin_only_path("/api/v1/auth/login", "POST"));
1103        assert!(!is_admin_only_path("/api/v1/schemas", "GET"));
1104    }
1105
1106    #[test]
1107    fn test_auth_context_permissions() {
1108        let claims = Claims::new(
1109            "user1".to_string(),
1110            "tenant1".to_string(),
1111            Role::Developer,
1112            chrono::Duration::hours(1),
1113        );
1114
1115        let ctx = AuthContext { claims };
1116
1117        assert!(ctx.require_permission(Permission::Read).is_ok());
1118        assert!(ctx.require_permission(Permission::Write).is_ok());
1119        assert!(ctx.require_permission(Permission::Admin).is_err());
1120    }
1121
1122    #[test]
1123    fn test_auth_context_admin_permissions() {
1124        let claims = Claims::new(
1125            "admin1".to_string(),
1126            "tenant1".to_string(),
1127            Role::Admin,
1128            chrono::Duration::hours(1),
1129        );
1130
1131        let ctx = AuthContext { claims };
1132
1133        assert!(ctx.require_permission(Permission::Read).is_ok());
1134        assert!(ctx.require_permission(Permission::Write).is_ok());
1135        assert!(ctx.require_permission(Permission::Admin).is_ok());
1136    }
1137
1138    #[test]
1139    fn test_auth_context_readonly_permissions() {
1140        let claims = Claims::new(
1141            "readonly1".to_string(),
1142            "tenant1".to_string(),
1143            Role::ReadOnly,
1144            chrono::Duration::hours(1),
1145        );
1146
1147        let ctx = AuthContext { claims };
1148
1149        assert!(ctx.require_permission(Permission::Read).is_ok());
1150        assert!(ctx.require_permission(Permission::Write).is_err());
1151        assert!(ctx.require_permission(Permission::Admin).is_err());
1152    }
1153
1154    #[test]
1155    fn test_auth_context_tenant_id() {
1156        let claims = Claims::new(
1157            "user1".to_string(),
1158            "my-tenant".to_string(),
1159            Role::Developer,
1160            chrono::Duration::hours(1),
1161        );
1162
1163        let ctx = AuthContext { claims };
1164        assert_eq!(ctx.tenant_id(), "my-tenant");
1165    }
1166
1167    #[test]
1168    fn test_auth_context_user_id() {
1169        let claims = Claims::new(
1170            "my-user".to_string(),
1171            "tenant1".to_string(),
1172            Role::Developer,
1173            chrono::Duration::hours(1),
1174        );
1175
1176        let ctx = AuthContext { claims };
1177        assert_eq!(ctx.user_id(), "my-user");
1178    }
1179
1180    #[test]
1181    fn test_request_id_new() {
1182        let id1 = RequestId::new();
1183        let id2 = RequestId::new();
1184
1185        // IDs should be unique
1186        assert_ne!(id1.as_str(), id2.as_str());
1187        // IDs should be valid UUIDs (36 chars with hyphens)
1188        assert_eq!(id1.as_str().len(), 36);
1189    }
1190
1191    #[test]
1192    fn test_request_id_default() {
1193        let id = RequestId::default();
1194        assert_eq!(id.as_str().len(), 36);
1195    }
1196
1197    #[test]
1198    fn test_security_config_default() {
1199        let config = SecurityConfig::default();
1200
1201        assert!(config.enable_hsts);
1202        assert_eq!(config.hsts_max_age, 31536000);
1203        assert!(config.enable_frame_options);
1204        assert!(config.enable_content_type_options);
1205        assert!(config.enable_xss_protection);
1206        assert!(config.csp.is_some());
1207    }
1208
1209    #[test]
1210    fn test_frame_options_variants() {
1211        let deny = FrameOptions::Deny;
1212        let same_origin = FrameOptions::SameOrigin;
1213        let allow_from = FrameOptions::AllowFrom("https://example.com".to_string());
1214
1215        // Check that variants are distinct via debug formatting
1216        assert!(format!("{deny:?}").contains("Deny"));
1217        assert!(format!("{same_origin:?}").contains("SameOrigin"));
1218        assert!(format!("{allow_from:?}").contains("AllowFrom"));
1219    }
1220
1221    #[test]
1222    fn test_auth_error_from_validation_error() {
1223        let error = AllSourceError::ValidationError("test error".to_string());
1224        let auth_error = AuthError::from(error);
1225        assert!(format!("{auth_error:?}").contains("ValidationError"));
1226    }
1227
1228    #[test]
1229    fn test_rate_limit_error_display() {
1230        let error = RateLimitError::RateLimitExceeded {
1231            retry_after: 60,
1232            limit: 100,
1233        };
1234        assert!(format!("{error:?}").contains("RateLimitExceeded"));
1235
1236        let unauth_error = RateLimitError::Unauthorized;
1237        assert!(format!("{unauth_error:?}").contains("Unauthorized"));
1238    }
1239
1240    #[test]
1241    fn test_tenant_error_variants() {
1242        let errors = vec![
1243            TenantError::Unauthorized,
1244            TenantError::InvalidTenant,
1245            TenantError::TenantNotFound,
1246            TenantError::TenantInactive,
1247            TenantError::RepositoryError("test".to_string()),
1248        ];
1249
1250        for error in errors {
1251            // Ensure each variant can be debug-formatted
1252            let _ = format!("{error:?}");
1253        }
1254    }
1255
1256    #[test]
1257    fn test_ip_filter_error_variants() {
1258        let errors = vec![
1259            IpFilterError::NoIpAddress,
1260            IpFilterError::Blocked {
1261                reason: "blocked".to_string(),
1262            },
1263        ];
1264
1265        for error in errors {
1266            let _ = format!("{error:?}");
1267        }
1268    }
1269
1270    #[test]
1271    fn test_security_state_clone() {
1272        let config = SecurityConfig::default();
1273        let state = SecurityState {
1274            config: config.clone(),
1275        };
1276        let cloned = state.clone();
1277        assert_eq!(cloned.config.hsts_max_age, config.hsts_max_age);
1278    }
1279
1280    #[test]
1281    fn test_auth_state_clone() {
1282        let auth_manager = Arc::new(AuthManager::new("test-secret"));
1283        let state = AuthState { auth_manager };
1284        let cloned = state.clone();
1285        assert!(Arc::ptr_eq(&state.auth_manager, &cloned.auth_manager));
1286    }
1287
1288    #[test]
1289    fn test_rate_limit_state_clone() {
1290        use crate::infrastructure::security::rate_limit::RateLimitConfig;
1291        let rate_limiter = Arc::new(RateLimiter::new(RateLimitConfig::free_tier()));
1292        let state = RateLimitState::new(rate_limiter);
1293        let cloned = state.clone();
1294        assert!(Arc::ptr_eq(&state.rate_limiter, &cloned.rate_limiter));
1295    }
1296
1297    #[test]
1298    fn test_auth_skip_paths_contains_expected() {
1299        // Verify public paths are configured for auth/rate-limit skipping
1300        assert!(should_skip_auth("/health"));
1301        assert!(should_skip_auth("/metrics"));
1302        assert!(should_skip_auth("/api/v1/auth/register"));
1303        assert!(should_skip_auth("/api/v1/auth/login"));
1304        assert!(should_skip_auth("/api/v1/demo/seed"));
1305
1306        // Verify internal endpoints bypass auth (sentinel failover)
1307        assert!(should_skip_auth("/internal/promote"));
1308        assert!(should_skip_auth("/internal/repoint"));
1309        assert!(should_skip_auth("/internal/anything"));
1310
1311        // Data-plane paths skip auth (Core is internal-only; gateway handles
1312        // authentication; handlers read tenant_id from body/query).
1313        assert!(should_skip_auth("/api/v1/events"));
1314        assert!(should_skip_auth("/api/v1/events/query"));
1315        assert!(should_skip_auth("/api/v1/events/batch"));
1316        assert!(should_skip_auth("/api/v1/projections/foo/bar"));
1317        assert!(!should_skip_auth("/api/v1/snapshots"));
1318        assert!(!should_skip_auth("/api/v1/read-models/foo"));
1319        assert!(!should_skip_auth("/api/v1/event-feed"));
1320
1321        // These still require auth — CP depends on them.
1322        assert!(!should_skip_auth("/api/v1/auth/me"));
1323        assert!(!should_skip_auth("/api/v1/auth/api-keys"));
1324        assert!(!should_skip_auth("/api/v1/tenants"));
1325        assert!(!should_skip_auth("/api/v1/tenants/abc"));
1326    }
1327
1328    #[test]
1329    fn test_dev_mode_auth_context() {
1330        let ctx = dev_mode_auth_context();
1331
1332        // Dev user should have admin privileges
1333        assert_eq!(ctx.tenant_id(), "dev-tenant");
1334        assert_eq!(ctx.user_id(), "dev-user");
1335        assert!(ctx.require_permission(Permission::Admin).is_ok());
1336        assert!(ctx.require_permission(Permission::Read).is_ok());
1337        assert!(ctx.require_permission(Permission::Write).is_ok());
1338    }
1339
1340    #[test]
1341    fn test_dev_mode_disabled_by_default() {
1342        // Dev mode should be disabled by default (env var not set in tests)
1343        // Note: This test may fail if ALLSOURCE_DEV_MODE is set in the test environment
1344        // In a clean environment, dev mode is disabled
1345        let env_value = std::env::var("ALLSOURCE_DEV_MODE").unwrap_or_default();
1346        if env_value.is_empty() {
1347            assert!(!is_dev_mode());
1348        }
1349    }
1350}