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
16pub 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
25pub 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#[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
72fn 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#[inline]
108pub fn is_dev_mode() -> bool {
109 *DEV_MODE_ENABLED
110}
111
112fn 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#[derive(Clone)]
126pub struct AuthState {
127 pub auth_manager: Arc<AuthManager>,
128}
129
130#[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 egress_rate_limiter: Arc::new(RateLimiter::new(RateLimitConfig {
153 requests_per_minute: 1200,
154 burst_size: 2000,
155 })),
156 }
157 }
158}
159
160#[derive(Debug, Clone)]
162pub struct AuthContext {
163 pub claims: Claims,
164}
165
166impl AuthContext {
167 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 pub fn tenant_id(&self) -> &str {
180 &self.claims.tenant_id
181 }
182
183 pub fn user_id(&self) -> &str {
185 &self.claims.sub
186 }
187}
188
189fn extract_token(headers: &HeaderMap) -> Result<String, AllSourceError> {
191 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 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#[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
239pub async fn auth_middleware(
241 State(auth_state): State<AuthState>,
242 mut request: Request,
243 next: Next,
244) -> Result<Response, AuthError> {
245 let path = request.uri().path();
247 if should_skip_auth(path) {
248 return Ok(next.run(request).await);
249 }
250
251 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 let token = extract_token(headers)?;
275
276 let claims = if token.starts_with("ask_") {
277 auth_state.auth_manager.validate_api_key(&token)?
279 } else {
280 auth_state.auth_manager.validate_token(&token)?
282 };
283
284 let auth_ctx = AuthContext { claims };
285
286 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 request.extensions_mut().insert(auth_ctx);
305
306 Ok(next.run(request).await)
307}
308
309pub 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 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#[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
357pub 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 #[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
384pub 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 #[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
404pub 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 #[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
433pub async fn rate_limit_middleware(
436 State(rate_limit_state): State<RateLimitState>,
437 request: Request,
438 next: Next,
439) -> Result<Response, RateLimitError> {
440 let path = request.uri().path();
442 if should_skip_auth(path) {
443 return Ok(next.run(request).await);
444 }
445
446 if is_dev_mode() {
448 return Ok(next.run(request).await);
449 }
450
451 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 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#[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#[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
555use crate::domain::{entities::Tenant, repositories::TenantRepository, value_objects::TenantId};
560
561#[derive(Clone)]
563pub struct TenantState<R: TenantRepository> {
564 pub tenant_repository: Arc<R>,
565}
566
567#[derive(Debug, Clone)]
572pub struct TenantContext {
573 pub tenant: Tenant,
574}
575
576impl TenantContext {
577 pub fn tenant_id(&self) -> &TenantId {
579 self.tenant.id()
580 }
581
582 pub fn is_active(&self) -> bool {
584 self.tenant.is_active()
585 }
586}
587
588pub 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 let auth_ctx = request
608 .extensions()
609 .get::<AuthContext>()
610 .ok_or(TenantError::Unauthorized)?
611 .clone();
612
613 let tenant_id =
615 TenantId::new(auth_ctx.tenant_id().to_string()).map_err(|_| TenantError::InvalidTenant)?;
616
617 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 if !tenant.is_active() {
627 return Err(TenantError::TenantInactive);
628 }
629
630 request.extensions_mut().insert(TenantContext { tenant });
632
633 Ok(next.run(request).await)
635}
636
637#[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
667use uuid::Uuid;
672
673#[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 pub fn new() -> Self {
686 Self(Uuid::new_v4().to_string())
687 }
688
689 pub fn as_str(&self) -> &str {
691 &self.0
692 }
693}
694
695pub async fn request_id_middleware(mut request: Request, next: Next) -> Response {
710 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 request.extensions_mut().insert(request_id.clone());
719
720 let mut response = next.run(request).await;
722
723 response
725 .headers_mut()
726 .insert("x-request-id", request_id.0.parse().unwrap());
727
728 response
729}
730
731#[derive(Debug, Clone)]
737pub struct SecurityConfig {
738 pub enable_hsts: bool,
740 pub hsts_max_age: u32,
742 pub enable_frame_options: bool,
744 pub frame_options: FrameOptions,
746 pub enable_content_type_options: bool,
748 pub enable_xss_protection: bool,
750 pub csp: Option<String>,
752 pub cors_origins: Vec<String>,
754 pub cors_methods: Vec<String>,
756 pub cors_headers: Vec<String>,
758 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, 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
797pub 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 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 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 if config.enable_content_type_options {
843 headers.insert("x-content-type-options", "nosniff".parse().unwrap());
844 }
845
846 if config.enable_xss_protection {
848 headers.insert("x-xss-protection", "1; mode=block".parse().unwrap());
849 }
850
851 if let Some(csp) = &config.csp {
853 headers.insert("content-security-policy", csp.parse().unwrap());
854 }
855
856 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
877use crate::infrastructure::security::IpFilter;
882use std::net::SocketAddr;
883
884#[derive(Clone)]
885pub struct IpFilterState {
886 pub ip_filter: Arc<IpFilter>,
887}
888
889pub async fn ip_filter_middleware(
901 State(ip_filter_state): State<IpFilterState>,
902 request: Request,
903 next: Next,
904) -> Result<Response, IpFilterError> {
905 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 let result = if let Some(tenant_ctx) = request.extensions().get::<TenantContext>() {
914 ip_filter_state
916 .ip_filter
917 .is_allowed_for_tenant(tenant_ctx.tenant_id(), &client_ip)
918 } else {
919 ip_filter_state.ip_filter.is_allowed(&client_ip)
921 };
922
923 if !result.allowed {
925 return Err(IpFilterError::Blocked {
926 reason: result.reason,
927 });
928 }
929
930 Ok(next.run(request).await)
932}
933
934#[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 #[test]
1013 fn test_service_account_blocked_on_admin_paths() {
1014 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 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 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 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 assert!(is_admin_only_path("/api/v1/auth/api-keys", "POST"));
1082 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 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 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 assert_ne!(id1.as_str(), id2.as_str());
1187 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 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 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 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 assert!(should_skip_auth("/internal/promote"));
1308 assert!(should_skip_auth("/internal/repoint"));
1309 assert!(should_skip_auth("/internal/anything"));
1310
1311 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 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 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 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}