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