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];
56
57#[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
71fn 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#[inline]
107pub fn is_dev_mode() -> bool {
108 *DEV_MODE_ENABLED
109}
110
111fn 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#[derive(Clone)]
125pub struct AuthState {
126 pub auth_manager: Arc<AuthManager>,
127}
128
129#[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 egress_rate_limiter: Arc::new(RateLimiter::new(RateLimitConfig {
152 requests_per_minute: 1200,
153 burst_size: 2000,
154 })),
155 }
156 }
157}
158
159#[derive(Debug, Clone)]
161pub struct AuthContext {
162 pub claims: Claims,
163}
164
165impl AuthContext {
166 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 pub fn tenant_id(&self) -> &str {
179 &self.claims.tenant_id
180 }
181
182 pub fn user_id(&self) -> &str {
184 &self.claims.sub
185 }
186}
187
188fn extract_token(headers: &HeaderMap) -> Result<String, AllSourceError> {
190 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 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#[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
238pub async fn auth_middleware(
240 State(auth_state): State<AuthState>,
241 mut request: Request,
242 next: Next,
243) -> Result<Response, AuthError> {
244 let path = request.uri().path();
246 if should_skip_auth(path) {
247 return Ok(next.run(request).await);
248 }
249
250 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 let token = extract_token(headers)?;
274
275 let claims = if token.starts_with("ask_") {
276 auth_state.auth_manager.validate_api_key(&token)?
278 } else {
279 auth_state.auth_manager.validate_token(&token)?
281 };
282
283 let auth_ctx = AuthContext { claims };
284
285 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 request.extensions_mut().insert(auth_ctx);
304
305 Ok(next.run(request).await)
306}
307
308pub 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 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#[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
356pub 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 #[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
383pub 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 #[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
403pub 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 #[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
432pub async fn rate_limit_middleware(
435 State(rate_limit_state): State<RateLimitState>,
436 request: Request,
437 next: Next,
438) -> Result<Response, RateLimitError> {
439 let path = request.uri().path();
441 if should_skip_auth(path) {
442 return Ok(next.run(request).await);
443 }
444
445 if is_dev_mode() {
447 return Ok(next.run(request).await);
448 }
449
450 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 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#[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#[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
554use crate::domain::{entities::Tenant, repositories::TenantRepository, value_objects::TenantId};
559
560#[derive(Clone)]
562pub struct TenantState<R: TenantRepository> {
563 pub tenant_repository: Arc<R>,
564}
565
566#[derive(Debug, Clone)]
571pub struct TenantContext {
572 pub tenant: Tenant,
573}
574
575impl TenantContext {
576 pub fn tenant_id(&self) -> &TenantId {
578 self.tenant.id()
579 }
580
581 pub fn is_active(&self) -> bool {
583 self.tenant.is_active()
584 }
585}
586
587pub 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 let auth_ctx = request
607 .extensions()
608 .get::<AuthContext>()
609 .ok_or(TenantError::Unauthorized)?
610 .clone();
611
612 let tenant_id =
614 TenantId::new(auth_ctx.tenant_id().to_string()).map_err(|_| TenantError::InvalidTenant)?;
615
616 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 if !tenant.is_active() {
626 return Err(TenantError::TenantInactive);
627 }
628
629 request.extensions_mut().insert(TenantContext { tenant });
631
632 Ok(next.run(request).await)
634}
635
636#[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
666use uuid::Uuid;
671
672#[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 pub fn new() -> Self {
685 Self(Uuid::new_v4().to_string())
686 }
687
688 pub fn as_str(&self) -> &str {
690 &self.0
691 }
692}
693
694pub async fn request_id_middleware(mut request: Request, next: Next) -> Response {
709 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 request.extensions_mut().insert(request_id.clone());
718
719 let mut response = next.run(request).await;
721
722 response
724 .headers_mut()
725 .insert("x-request-id", request_id.0.parse().unwrap());
726
727 response
728}
729
730#[derive(Debug, Clone)]
736pub struct SecurityConfig {
737 pub enable_hsts: bool,
739 pub hsts_max_age: u32,
741 pub enable_frame_options: bool,
743 pub frame_options: FrameOptions,
745 pub enable_content_type_options: bool,
747 pub enable_xss_protection: bool,
749 pub csp: Option<String>,
751 pub cors_origins: Vec<String>,
753 pub cors_methods: Vec<String>,
755 pub cors_headers: Vec<String>,
757 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, 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
796pub 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 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 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 if config.enable_content_type_options {
842 headers.insert("x-content-type-options", "nosniff".parse().unwrap());
843 }
844
845 if config.enable_xss_protection {
847 headers.insert("x-xss-protection", "1; mode=block".parse().unwrap());
848 }
849
850 if let Some(csp) = &config.csp {
852 headers.insert("content-security-policy", csp.parse().unwrap());
853 }
854
855 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
876use crate::infrastructure::security::IpFilter;
881use std::net::SocketAddr;
882
883#[derive(Clone)]
884pub struct IpFilterState {
885 pub ip_filter: Arc<IpFilter>,
886}
887
888pub async fn ip_filter_middleware(
900 State(ip_filter_state): State<IpFilterState>,
901 request: Request,
902 next: Next,
903) -> Result<Response, IpFilterError> {
904 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 let result = if let Some(tenant_ctx) = request.extensions().get::<TenantContext>() {
913 ip_filter_state
915 .ip_filter
916 .is_allowed_for_tenant(tenant_ctx.tenant_id(), &client_ip)
917 } else {
918 ip_filter_state.ip_filter.is_allowed(&client_ip)
920 };
921
922 if !result.allowed {
924 return Err(IpFilterError::Blocked {
925 reason: result.reason,
926 });
927 }
928
929 Ok(next.run(request).await)
931}
932
933#[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 #[test]
1012 fn test_service_account_blocked_on_admin_paths() {
1013 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 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 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 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 assert!(is_admin_only_path("/api/v1/auth/api-keys", "POST"));
1081 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 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 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 assert_ne!(id1.as_str(), id2.as_str());
1186 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 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 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 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 assert!(should_skip_auth("/internal/promote"));
1307 assert!(should_skip_auth("/internal/repoint"));
1308 assert!(should_skip_auth("/internal/anything"));
1309
1310 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 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 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 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}