cedros-login-server 0.0.45

Authentication server for cedros-login with email/password, Google OAuth, and Solana wallet sign-in
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
#![recursion_limit = "256"]

//! # Cedros Login Server
//!
//! Authentication server library with email/password, Google OAuth, and Solana wallet sign-in.
//!
//! ## Features
//!
//! - **Email/Password**: Traditional registration and login with argon2id password hashing
//! - **Google OAuth**: Social sign-in via Google ID token verification
//! - **Solana Wallet**: Sign-in by signing a challenge message with an ed25519 wallet
//!
//! ## Usage
//!
//! ### Standalone Server
//!
//! Run the binary directly:
//! ```bash
//! cedros-login-server
//! ```
//!
//! ### Embedded Library
//!
//! Integrate into your own Axum application:
//! ```text
//! use cedros_login::{router, Config, NoopCallback};
//! use std::sync::Arc;
//!
//! let config = Config::from_env()?;
//! let callback = Arc::new(NoopCallback);
//! let auth_router = router(config, callback);
//!
//! let app = Router::new()
//!     .nest("/auth", auth_router)
//!     .layer(/* your middleware */);
//! ```

pub mod callback;
pub mod config;
pub mod errors;
pub mod handlers;
pub mod middleware;
pub mod models;
pub mod repositories;
pub mod services;
pub mod storage;
pub mod utils;

mod router;

#[cfg(test)]
pub(crate) mod test_env;

pub use callback::{AuthCallback, AuthCallbackPayload, NoopCallback, ReferralRewardPayload};
pub use config::{Config, DatabaseConfig, NotificationConfig};
pub use errors::AppError;
pub use router::create_router;
// Re-export NotificationService trait for create_withdrawal_worker
pub use services::NotificationService;
pub use services::ReferralPayoutWorker;
pub use services::{
    EmailService, InstantLinkEmailData, LogEmailService, NoopEmailService, PasswordResetEmailData,
    VerificationEmailData,
};
#[cfg(feature = "postgres")]
pub use sqlx::PgPool;
pub use storage::Storage;

use axum::Router;
use repositories::{
    ApiKeyRepository, AuditLogRepository, CredentialRepository, CreditHoldRepository,
    CreditRefundRequestRepository, CreditRepository, CustomRoleRepository, DepositRepository,
    DerivedWalletRepository, InviteRepository, LoginAttemptConfig, LoginAttemptRepository,
    MembershipRepository, NonceRepository, OrgRepository, OutboxRepository, PolicyRepository,
    PrivacyNoteRepository, ReferralCodeHistoryRepository, ReferralPayoutRepository,
    SessionRepository, SystemSettingsRepository, TotpRepository, TreasuryConfigRepository,
    UserRepository, UserWithdrawalLogRepository, VerificationRepository, WalletMaterialRepository,
    WalletRotationHistoryRepository, WebAuthnRepository,
};
use services::{
    create_wallet_unlock_cache, AppleService, AuditService, CommsService, DepositCreditService,
    DepositFeeService, EncryptionService, GoogleService, JupiterSwapService, JwtService,
    MfaAttemptService, NoteEncryptionService, OidcService, PasswordService, PrivacySidecarClient,
    SanctionsService, SettingsService, SidecarClientConfig, SignupGatingService, SolPriceService,
    SolanaService, StepUpService, TokenGatingService, TotpService, WalletSigningService,
    WalletUnlockCache, WebAuthnService,
};
use std::sync::Arc;
use utils::TokenCipher;

fn build_privacy_sidecar_client(config: &Config) -> Result<PrivacySidecarClient, AppError> {
    let api_key = config
        .privacy
        .sidecar_api_key
        .clone()
        .ok_or_else(|| AppError::Config("SIDECAR_API_KEY is required".into()))?;
    PrivacySidecarClient::new(SidecarClientConfig {
        base_url: config.privacy.sidecar_url.clone(),
        timeout_ms: config.privacy.sidecar_timeout_ms,
        api_key,
    })
}

fn decode_note_encryption_key(key: &str) -> Result<Vec<u8>, base64::DecodeError> {
    use base64::{engine::general_purpose::STANDARD, Engine as _};

    STANDARD.decode(key)
}

fn build_note_encryption_service(
    key_bytes: &[u8],
    key_id: &str,
) -> Result<NoteEncryptionService, AppError> {
    NoteEncryptionService::new(key_bytes, key_id)
}

fn preload_settings_cache(settings_service: &Arc<SettingsService>) {
    if let Ok(handle) = tokio::runtime::Handle::try_current() {
        if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread {
            tokio::task::block_in_place(|| {
                if let Err(error) = handle.block_on(settings_service.refresh()) {
                    tracing::warn!(error = %error, "Failed to preload settings cache during router setup");
                }
            });
        }
    }
}

/// Auto-generate sidecar secrets in system_settings if they are empty.
///
/// Called during startup so a fresh deploy has working defaults.
/// - `sidecar_api_key`: 32 random bytes, hex-encoded (64 chars)
/// - `note_encryption_key`: 32 random bytes, base64-encoded
fn auto_generate_sidecar_secrets(
    repo: &Arc<dyn SystemSettingsRepository>,
    encryption: &EncryptionService,
) {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    use rand::{rngs::OsRng, RngCore};

    let Ok(handle) = tokio::runtime::Handle::try_current() else {
        return;
    };
    if handle.runtime_flavor() != tokio::runtime::RuntimeFlavor::MultiThread {
        return;
    }

    tokio::task::block_in_place(|| {
        handle.block_on(async {
            let keys_to_generate: Vec<(&str, Box<dyn Fn() -> String>)> = vec![
                (
                    "sidecar_api_key",
                    Box::new(|| {
                        let mut bytes = [0u8; 32];
                        OsRng.fill_bytes(&mut bytes);
                        hex::encode(bytes)
                    }),
                ),
                (
                    "note_encryption_key",
                    Box::new(|| {
                        let mut bytes = [0u8; 32];
                        OsRng.fill_bytes(&mut bytes);
                        STANDARD.encode(bytes)
                    }),
                ),
            ];

            for (key, generate) in keys_to_generate {
                // Check current value
                match repo.get_by_key(key).await {
                    Ok(Some(setting)) if !setting.value.is_empty() => {
                        tracing::debug!(key, "Sidecar secret already set, skipping auto-generation");
                    }
                    Ok(_) => {
                        // Empty or not found — generate and persist
                        let raw_value = generate();
                        let encrypted_value = match encryption.encrypt(&raw_value) {
                            Ok(v) => v,
                            Err(e) => {
                                tracing::error!(key, error = %e, "Failed to encrypt auto-generated sidecar secret");
                                continue;
                            }
                        };
                        let setting = repositories::SystemSetting {
                            key: key.to_string(),
                            value: encrypted_value,
                            category: "privacy".to_string(),
                            description: None,
                            is_secret: true,
                            encryption_version: Some("v1".to_string()),
                            updated_at: chrono::Utc::now(),
                            updated_by: None,
                        };
                        match repo.upsert_many(vec![setting]).await {
                            Ok(_) => tracing::info!(key, "Auto-generated sidecar secret"),
                            Err(e) => tracing::error!(key, error = %e, "Failed to persist auto-generated sidecar secret"),
                        }
                    }
                    Err(e) => {
                        tracing::warn!(key, error = %e, "Failed to check sidecar secret, skipping auto-generation");
                    }
                }
            }
        });
    });
}

/// Read a sidecar secret from system_settings, decrypting it.
/// Returns None if the key doesn't exist or is empty.
fn read_sidecar_secret_sync(settings_service: &Arc<SettingsService>, key: &str) -> Option<String> {
    let Ok(handle) = tokio::runtime::Handle::try_current() else {
        return None;
    };
    if handle.runtime_flavor() != tokio::runtime::RuntimeFlavor::MultiThread {
        return None;
    }
    tokio::task::block_in_place(|| {
        handle.block_on(async {
            match settings_service.get_secret(key).await {
                Ok(Some(v)) if !v.is_empty() => Some(v),
                _ => None,
            }
        })
    })
}

/// Application state shared across all handlers
pub struct AppState<C: AuthCallback, E: EmailService = LogEmailService> {
    pub config: Config,
    pub callback: Arc<C>,
    pub jwt_service: JwtService,
    pub password_service: PasswordService,
    pub google_service: GoogleService,
    pub apple_service: AppleService,
    pub solana_service: SolanaService,
    pub totp_service: TotpService,
    pub webauthn_service: WebAuthnService,
    pub oidc_service: OidcService,
    pub encryption_service: EncryptionService,
    pub phantom_email: std::marker::PhantomData<E>,
    pub audit_service: AuditService,
    pub comms_service: CommsService,
    pub user_repo: Arc<dyn UserRepository>,
    pub session_repo: Arc<dyn SessionRepository>,
    pub nonce_repo: Arc<dyn NonceRepository>,
    pub verification_repo: Arc<dyn VerificationRepository>,
    pub org_repo: Arc<dyn OrgRepository>,
    pub membership_repo: Arc<dyn MembershipRepository>,
    pub invite_repo: Arc<dyn InviteRepository>,
    pub audit_repo: Arc<dyn AuditLogRepository>,
    pub login_attempt_repo: Arc<dyn LoginAttemptRepository>,
    pub login_attempt_config: LoginAttemptConfig,
    pub totp_repo: Arc<dyn TotpRepository>,
    pub custom_role_repo: Arc<dyn CustomRoleRepository>,
    pub policy_repo: Arc<dyn PolicyRepository>,
    pub outbox_repo: Arc<dyn OutboxRepository>,
    pub api_key_repo: Arc<dyn ApiKeyRepository>,
    pub wallet_material_repo: Arc<dyn WalletMaterialRepository>,
    pub derived_wallet_repo: Arc<dyn DerivedWalletRepository>,
    pub wallet_rotation_history_repo: Arc<dyn WalletRotationHistoryRepository>,
    pub credential_repo: Arc<dyn CredentialRepository>,
    pub webauthn_repo: Arc<dyn WebAuthnRepository>,
    pub deposit_repo: Arc<dyn DepositRepository>,
    pub credit_repo: Arc<dyn CreditRepository>,
    pub credit_hold_repo: Arc<dyn CreditHoldRepository>,
    pub credit_refund_request_repo: Arc<dyn CreditRefundRequestRepository>,
    pub privacy_note_repo: Arc<dyn PrivacyNoteRepository>,
    /// System settings repository for runtime-configurable values
    pub system_settings_repo: Arc<dyn SystemSettingsRepository>,
    /// Treasury configuration repository for micro deposit batching
    pub treasury_config_repo: Arc<dyn TreasuryConfigRepository>,
    /// User withdrawal log repository for tracking user-initiated withdrawals
    pub user_withdrawal_log_repo: Arc<dyn UserWithdrawalLogRepository>,
    /// Referral payout repository for direct on-chain referral payouts
    pub referral_payout_repo: Arc<dyn ReferralPayoutRepository>,
    /// Referral code history repository for preserving retired codes
    pub referral_code_history_repo: Arc<dyn ReferralCodeHistoryRepository>,
    /// Settings service with caching for runtime configuration
    pub settings_service: Arc<SettingsService>,
    /// SEC-04: Per-user MFA attempt tracking to prevent brute-force
    pub mfa_attempt_service: MfaAttemptService,
    pub step_up_service: StepUpService,
    /// Wallet signing service for server-side transaction signing
    pub wallet_signing_service: WalletSigningService,
    /// Wallet unlock cache for session-based credential caching
    pub wallet_unlock_cache: Arc<WalletUnlockCache>,
    /// Storage layer for accessing repositories
    pub storage: Storage,
    /// Privacy Cash sidecar client (None if privacy not enabled)
    pub privacy_sidecar_client: Option<Arc<PrivacySidecarClient>>,
    /// Note encryption service for privacy notes (None if privacy not enabled)
    pub note_encryption_service: Option<Arc<NoteEncryptionService>>,
    /// SOL price service for fetching current SOL/USD price
    pub sol_price_service: Arc<SolPriceService>,
    /// Jupiter swap service for public deposits (None if company wallet not configured)
    pub jupiter_swap_service: Option<Arc<JupiterSwapService>>,
    /// Deposit credit service for calculating credits from deposits
    pub deposit_credit_service: Arc<DepositCreditService>,
    /// KYC verification service (None if KYC not configured)
    pub kyc_service: Option<Arc<services::KycService>>,
    /// Accredited investor verification service
    pub accreditation_service: Option<Arc<services::AccreditationService>>,
    /// Sanctions screening service — always present; disabled state handled internally
    pub sanctions_service: Arc<SanctionsService>,
    /// Token gating service — always present; disabled state handled internally
    pub token_gating_service: Arc<TokenGatingService>,
    /// Signup gating service — always present; checks disabled state internally
    pub signup_gating_service: Arc<SignupGatingService>,
    #[cfg(feature = "postgres")]
    pub postgres_pool: Option<PgPool>,
}

/// Create the authentication router with in-memory storage.
///
/// This is the simplest entry point, useful for development and testing.
/// For production with PostgreSQL, use `router_with_storage` instead.
pub fn router<C: AuthCallback + 'static>(config: Config, callback: Arc<C>) -> Router {
    router_with_storage(config, callback, Storage::in_memory())
}

/// Create the authentication router with custom storage backend.
///
/// Use this when you need PostgreSQL or a custom storage implementation.
///
/// ## Example with PostgreSQL
///
/// ```text
/// use cedros_login::{router_with_storage, Config, Storage, NoopCallback};
/// use std::sync::Arc;
///
/// let config = Config::from_env()?;
/// let storage = Storage::from_config(&config.database).await?;
/// let callback = Arc::new(NoopCallback);
/// let auth_router = router_with_storage(config, callback, storage);
/// ```
pub fn router_with_storage<C: AuthCallback + 'static>(
    config: Config,
    callback: Arc<C>,
    storage: Storage,
) -> Router {
    // Create SettingsService for runtime configuration (created early so other services can use it)
    // Note: The cache starts empty. Sync cache accessors used during router setup
    // (e.g., rate limit configuration) will return None and fall back to config defaults.
    // The cache is populated on first async access (e.g., deposit handler, withdrawal worker).
    let settings_service = Arc::new(SettingsService::new(storage.system_settings_repo.clone()));
    preload_settings_cache(&settings_service);

    // Auto-generate sidecar secrets if empty (needs encryption_service first)
    let encryption_service = EncryptionService::from_secret(&config.jwt.secret);
    auto_generate_sidecar_secrets(&storage.system_settings_repo, &encryption_service);
    // Refresh cache so newly generated secrets are available
    preload_settings_cache(&settings_service);

    // Create SettingsService with encryption for secret decryption
    let settings_service = Arc::new(SettingsService::with_encryption(
        storage.system_settings_repo.clone(),
        encryption_service.clone(),
    ));
    preload_settings_cache(&settings_service);

    let jwt_service = JwtService::new(&config.jwt);
    let password_service = PasswordService::default();
    let google_service = GoogleService::new(&config.google);
    let apple_service = AppleService::new(&config.apple);
    let solana_service = SolanaService::new(&config.solana);
    let totp_service = TotpService::new("Cedros");
    let webauthn_service = WebAuthnService::new(&config.webauthn, settings_service.clone());
    let audit_service = AuditService::new(storage.audit_repo.clone(), config.server.trust_proxy);
    let step_up_service = StepUpService::new(storage.session_repo.clone());

    // Create SSO services
    // SEC-02: Use HTTPS for SSO callback URL when frontend URL is HTTPS
    let protocol = if config
        .server
        .frontend_url
        .as_ref()
        .map(|u| u.starts_with("https://"))
        .unwrap_or(false)
    {
        "https"
    } else {
        "http"
    };
    let sso_callback_url = config.server.sso_callback_url.clone().unwrap_or_else(|| {
        format!(
            "{}://{}:{}/auth/sso/callback",
            protocol, config.server.host, config.server.port
        )
    });
    let oidc_service = OidcService::new(sso_callback_url);

    // Create CommsService for async email/notification delivery
    let base_url = config
        .server
        .frontend_url
        .clone()
        .unwrap_or_else(|| "http://localhost:3000".to_string());
    let token_cipher = TokenCipher::new(&config.jwt.secret);
    let comms_service = CommsService::new(storage.outbox_repo.clone(), base_url, token_cipher);

    // Create privacy services if enabled
    // Env vars take precedence; fall back to auto-generated values in system_settings
    let (privacy_sidecar_client, note_encryption_service) = if config.privacy.enabled {
        let mut errors = Vec::new();

        // Resolve sidecar API key: env var → system_settings
        let resolved_api_key = config
            .privacy
            .sidecar_api_key
            .clone()
            .or_else(|| read_sidecar_secret_sync(&settings_service, "sidecar_api_key"));

        let sidecar = match resolved_api_key {
            Some(api_key) => match PrivacySidecarClient::new(SidecarClientConfig {
                base_url: config.privacy.sidecar_url.clone(),
                timeout_ms: config.privacy.sidecar_timeout_ms,
                api_key,
            }) {
                Ok(s) => Some(Arc::new(s)),
                Err(e) => {
                    errors.push(format!("Failed to create privacy sidecar client: {}", e));
                    None
                }
            },
            None => {
                errors.push("SIDECAR_API_KEY is required (env var or system_settings)".to_string());
                None
            }
        };

        // Resolve note encryption key: env var → system_settings
        let resolved_note_key = config
            .privacy
            .note_encryption_key
            .clone()
            .or_else(|| read_sidecar_secret_sync(&settings_service, "note_encryption_key"));

        let note_encryption = match resolved_note_key.as_deref() {
            Some(key) => match decode_note_encryption_key(key) {
                Ok(key_bytes) => match build_note_encryption_service(
                    &key_bytes,
                    &config.privacy.note_encryption_key_id,
                ) {
                    Ok(n) => Some(Arc::new(n)),
                    Err(e) => {
                        errors.push(format!("Failed to create note encryption service: {}", e));
                        None
                    }
                },
                Err(e) => {
                    errors.push(format!("Invalid base64 in note_encryption_key: {}", e));
                    None
                }
            },
            None => {
                errors.push("note_encryption_key is required when privacy is enabled (env var or system_settings)".to_string());
                None
            }
        };

        // S-04: Fail startup when privacy is enabled but required services can't be created.
        // Silently disabling would allow the server to accept deposits it cannot process.
        if !errors.is_empty() {
            for error in &errors {
                tracing::error!("{}", error);
            }
            panic!(
                "Privacy is enabled but required services failed to initialize: {}",
                errors.join("; ")
            );
        } else {
            (sidecar, note_encryption)
        }
    } else {
        (None, None)
    };

    // Build Jupiter swap service if company wallet is configured (for public deposits)
    let jupiter_swap_service = config
        .privacy
        .company_wallet_address
        .as_ref()
        .and_then(|wallet| {
            match JupiterSwapService::new(
                wallet.clone(),
                &config.privacy.company_currency,
                None, // API key from env could be added later
            ) {
                Ok(service) => Some(Arc::new(service)),
                Err(e) => {
                    tracing::error!(error = %e, "Failed to create Jupiter swap service, swap features disabled");
                    None
                }
            }
        });

    // Create SOL price service (shared across deposit services)
    let sol_price_service = Arc::new(SolPriceService::new());

    // Create deposit fee and credit services
    let fee_service = Arc::new(DepositFeeService::new(settings_service.clone()));
    let deposit_credit_service = Arc::new(DepositCreditService::new(
        sol_price_service.clone(),
        fee_service,
        config.privacy.company_currency.clone(),
    ));

    let state = Arc::new(AppState {
        config,
        callback,
        jwt_service,
        password_service,
        google_service,
        apple_service,
        solana_service,
        totp_service,
        webauthn_service,
        oidc_service,
        encryption_service,
        phantom_email: std::marker::PhantomData::<LogEmailService>,
        audit_service,
        comms_service,
        user_repo: storage.user_repo.clone(),
        session_repo: storage.session_repo.clone(),
        nonce_repo: storage.nonce_repo.clone(),
        verification_repo: storage.verification_repo.clone(),
        org_repo: storage.org_repo.clone(),
        membership_repo: storage.membership_repo.clone(),
        invite_repo: storage.invite_repo.clone(),
        audit_repo: storage.audit_repo.clone(),
        login_attempt_repo: storage.login_attempt_repo.clone(),
        login_attempt_config: LoginAttemptConfig::default(),
        totp_repo: storage.totp_repo.clone(),
        custom_role_repo: storage.custom_role_repo.clone(),
        policy_repo: storage.policy_repo.clone(),
        outbox_repo: storage.outbox_repo.clone(),
        api_key_repo: storage.api_key_repo.clone(),
        wallet_material_repo: storage.wallet_material_repo.clone(),
        derived_wallet_repo: storage.derived_wallet_repo.clone(),
        wallet_rotation_history_repo: storage.wallet_rotation_history_repo.clone(),
        credential_repo: storage.credential_repo.clone(),
        webauthn_repo: storage.webauthn_repo.clone(),
        deposit_repo: storage.deposit_repo.clone(),
        credit_repo: storage.credit_repo.clone(),
        credit_hold_repo: storage.credit_hold_repo.clone(),
        credit_refund_request_repo: storage.credit_refund_request_repo.clone(),
        privacy_note_repo: storage.privacy_note_repo.clone(),
        system_settings_repo: storage.system_settings_repo.clone(),
        treasury_config_repo: storage.treasury_config_repo.clone(),
        user_withdrawal_log_repo: storage.user_withdrawal_log_repo.clone(),
        referral_payout_repo: storage.referral_payout_repo.clone(),
        referral_code_history_repo: storage.referral_code_history_repo.clone(),
        settings_service: settings_service.clone(),
        mfa_attempt_service: MfaAttemptService::new(),
        step_up_service,
        wallet_signing_service: WalletSigningService::new(),
        wallet_unlock_cache: create_wallet_unlock_cache(),
        privacy_sidecar_client,
        note_encryption_service,
        sol_price_service,
        jupiter_swap_service,
        deposit_credit_service,
        kyc_service: Some(Arc::new(services::KycService::new(
            storage.kyc_repo.clone(),
            storage.user_repo.clone(),
            settings_service.clone(),
        ))),
        accreditation_service: Some(Arc::new(services::AccreditationService::new(
            storage.accreditation_repo.clone(),
            storage.user_repo.clone(),
            settings_service.clone(),
        ))),
        sanctions_service: Arc::new(SanctionsService::new(settings_service.clone())),
        token_gating_service: Arc::new(TokenGatingService::new(
            settings_service.clone(),
            storage.user_repo.clone(),
            storage.wallet_material_repo.clone(),
        )),
        signup_gating_service: Arc::new(SignupGatingService::new(
            storage.access_code_repo.clone(),
            storage.user_repo.clone(),
            settings_service.clone(),
        )),
        #[cfg(feature = "postgres")]
        postgres_pool: storage.pg_pool.clone(),
        storage,
    });
    create_router(state)
}

/// Create a withdrawal worker for Privacy Cash deposits.
///
/// Returns `Some(JoinHandle)` if privacy is enabled, `None` otherwise.
/// The worker will poll for completed deposits and withdraw them to the company wallet.
///
/// Runtime-tunable settings (poll_interval, batch_size, timeout, retries, percentage,
/// partial_withdrawal_*) are read from the database via SettingsService.
pub fn create_withdrawal_worker(
    config: &Config,
    storage: &Storage,
    settings_service: Arc<SettingsService>,
    notification_service: Arc<dyn services::NotificationService>,
    cancel_token: tokio_util::sync::CancellationToken,
) -> Option<tokio::task::JoinHandle<()>> {
    if !config.privacy.enabled {
        return None;
    }

    // Create sidecar client
    let sidecar = match build_privacy_sidecar_client(config) {
        Ok(s) => Arc::new(s),
        Err(e) => {
            tracing::error!(error = %e, "Failed to create privacy sidecar client for withdrawal worker");
            return None;
        }
    };

    // S-05: Gracefully handle missing key instead of panicking
    let encryption_key = match config.privacy.note_encryption_key.as_ref() {
        Some(k) => k,
        None => {
            tracing::error!("note_encryption_key is required when privacy is enabled");
            return None;
        }
    };
    let key_bytes = match decode_note_encryption_key(encryption_key) {
        Ok(k) => k,
        Err(e) => {
            tracing::error!(error = %e, "Invalid base64 in note_encryption_key");
            return None;
        }
    };
    let note_encryption = match build_note_encryption_service(
        &key_bytes,
        &config.privacy.note_encryption_key_id,
    ) {
        Ok(s) => Arc::new(s),
        Err(e) => {
            tracing::error!(error = %e, "Failed to create note encryption service for withdrawal worker");
            return None;
        }
    };

    // Create withdrawal worker - runtime settings come from SettingsService (DB)
    // Only company_currency stays in config (env var)
    use services::{WithdrawalWorker, WithdrawalWorkerConfig};
    let worker_config = WithdrawalWorkerConfig {
        company_currency: config.privacy.company_currency.clone(),
    };
    let worker = WithdrawalWorker::new(
        storage.deposit_repo.clone(),
        storage.withdrawal_history_repo.clone(),
        sidecar,
        note_encryption,
        notification_service,
        settings_service,
        worker_config,
    );

    Some(worker.start(cancel_token))
}

/// Create a micro batch worker for SOL micro deposits.
///
/// Returns `Some(JoinHandle)` if privacy is enabled and treasury is configured,
/// `None` otherwise. The worker polls for pending micro deposits and batches them
/// when the accumulated value reaches the threshold ($10).
///
/// Runtime-tunable settings (poll_interval, threshold_usd) are read from the database
/// via SettingsService.
pub fn create_micro_batch_worker(
    config: &Config,
    storage: &Storage,
    settings_service: Arc<SettingsService>,
    cancel_token: tokio_util::sync::CancellationToken,
) -> Option<tokio::task::JoinHandle<()>> {
    if !config.privacy.enabled {
        return None;
    }

    // Create sidecar client
    let sidecar = match build_privacy_sidecar_client(config) {
        Ok(s) => Arc::new(s),
        Err(e) => {
            tracing::error!(error = %e, "Failed to create privacy sidecar client for micro batch worker");
            return None;
        }
    };

    // S-05: Gracefully handle missing key instead of panicking
    let encryption_key = match config.privacy.note_encryption_key.as_ref() {
        Some(k) => k,
        None => {
            tracing::error!("note_encryption_key is required when privacy is enabled");
            return None;
        }
    };
    let key_bytes = match decode_note_encryption_key(encryption_key) {
        Ok(k) => k,
        Err(e) => {
            tracing::error!(error = %e, "Invalid base64 in note_encryption_key");
            return None;
        }
    };
    let note_encryption = match build_note_encryption_service(
        &key_bytes,
        &config.privacy.note_encryption_key_id,
    ) {
        Ok(s) => Arc::new(s),
        Err(e) => {
            tracing::error!(error = %e, "Failed to create note encryption service for micro batch worker");
            return None;
        }
    };

    // Create sol price service
    let sol_price_service = Arc::new(services::SolPriceService::new());

    // Create the worker
    use services::MicroBatchWorker;
    let worker = MicroBatchWorker::new(
        storage.deposit_repo.clone(),
        storage.treasury_config_repo.clone(),
        sidecar,
        sol_price_service,
        note_encryption,
        settings_service,
        config.privacy.company_currency.clone(),
    );

    Some(worker.start(cancel_token))
}

/// Create a referral payout worker for automated on-chain payouts.
///
/// Returns `Some(JoinHandle)` if privacy is enabled, `None` otherwise.
/// The worker polls for pending referral payouts and processes them
/// using the treasury wallet.
///
/// Runtime-tunable settings (payout_auto_enabled, payout_poll_interval_secs,
/// payout_batch_size) are read from the database via SettingsService.
pub fn create_referral_payout_worker(
    config: &Config,
    storage: &Storage,
    settings_service: Arc<SettingsService>,
    cancel_token: tokio_util::sync::CancellationToken,
) -> Option<tokio::task::JoinHandle<()>> {
    if !config.privacy.enabled {
        return None;
    }

    let sidecar = match build_privacy_sidecar_client(config) {
        Ok(s) => Arc::new(s),
        Err(e) => {
            tracing::error!(error = %e, "Failed to create sidecar client for referral payout worker");
            return None;
        }
    };

    let encryption_key = match config.privacy.note_encryption_key.as_ref() {
        Some(k) => k,
        None => {
            tracing::error!("note_encryption_key is required for referral payout worker");
            return None;
        }
    };
    let key_bytes = match decode_note_encryption_key(encryption_key) {
        Ok(k) => k,
        Err(e) => {
            tracing::error!(error = %e, "Invalid base64 in note_encryption_key");
            return None;
        }
    };
    let note_encryption = match build_note_encryption_service(
        &key_bytes,
        &config.privacy.note_encryption_key_id,
    ) {
        Ok(s) => Arc::new(s),
        Err(e) => {
            tracing::error!(error = %e, "Failed to create note encryption for referral payout worker");
            return None;
        }
    };

    let worker = ReferralPayoutWorker::new(
        storage.referral_payout_repo.clone(),
        storage.treasury_config_repo.clone(),
        sidecar,
        note_encryption,
        settings_service,
    );

    Some(worker.start(cancel_token))
}

/// Create a hold expiration worker for credit holds.
///
/// This worker periodically expires stale credit holds that have exceeded their TTL,
/// releasing the held credits back to users' available balance.
///
/// Returns the JoinHandle for the background task.
pub fn create_hold_expiration_worker(
    storage: &Storage,
    cancel_token: tokio_util::sync::CancellationToken,
) -> tokio::task::JoinHandle<()> {
    use services::{HoldExpirationConfig, HoldExpirationWorker};

    let worker = HoldExpirationWorker::new(
        storage.credit_repo.clone(),
        storage.credit_hold_repo.clone(),
        HoldExpirationConfig::default(),
    );

    worker.start(cancel_token)
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine;

    fn base_config() -> Config {
        use crate::config::{
            default_access_expiry, default_audience, default_issuer, default_refresh_expiry,
            AppleConfig, CookieConfig, CorsConfig, DatabaseConfig, EmailConfig, GoogleConfig,
            JwtConfig, NotificationConfig, PrivacyConfig, RateLimitConfig, ServerConfig,
            SolanaConfig, SsoConfig, WalletConfig, WebAuthnConfig, WebhookConfig,
        };

        Config {
            server: ServerConfig::default(),
            jwt: JwtConfig {
                secret: "s".repeat(32),
                rsa_private_key_pem: None,
                issuer: default_issuer(),
                audience: default_audience(),
                access_token_expiry: default_access_expiry(),
                refresh_token_expiry: default_refresh_expiry(),
            },
            email: EmailConfig::default(),
            google: GoogleConfig {
                enabled: false,
                client_id: None,
            },
            apple: AppleConfig {
                enabled: false,
                client_id: None,
                team_id: None,
                ..AppleConfig::default()
            },
            solana: SolanaConfig::default(),
            webauthn: WebAuthnConfig::default(),
            cors: CorsConfig::default(),
            cookie: CookieConfig::default(),
            webhook: WebhookConfig::default(),
            rate_limit: RateLimitConfig::default(),
            database: DatabaseConfig::default(),
            notification: NotificationConfig::default(),
            sso: SsoConfig::default(),
            wallet: WalletConfig::default(),
            privacy: PrivacyConfig::default(),
        }
    }

    #[test]
    fn test_decode_note_encryption_key_valid() {
        let key = base64::engine::general_purpose::STANDARD.encode([0u8; 32]);
        let bytes = decode_note_encryption_key(&key).expect("valid base64 should decode");
        assert_eq!(bytes.len(), 32);
        assert!(bytes.iter().all(|byte| *byte == 0));
    }

    #[test]
    fn test_decode_note_encryption_key_invalid() {
        assert!(decode_note_encryption_key("not-base64").is_err());
    }

    #[test]
    fn test_build_privacy_sidecar_client_requires_api_key() {
        let mut config = base_config();
        config.privacy.enabled = true;
        config.privacy.sidecar_api_key = None;

        match build_privacy_sidecar_client(&config) {
            Ok(_) => panic!("expected error for missing SIDECAR_API_KEY"),
            Err(err) => {
                assert!(err.to_string().contains("SIDECAR_API_KEY is required"));
            }
        }
    }

    #[test]
    fn test_build_privacy_sidecar_client_with_api_key() {
        let mut config = base_config();
        config.privacy.enabled = true;
        config.privacy.sidecar_api_key = Some("test-key".to_string());

        assert!(build_privacy_sidecar_client(&config).is_ok());
    }

    #[test]
    fn test_preload_settings_cache_populates_cached_values() {
        let storage = Storage::in_memory();
        let settings_service = Arc::new(SettingsService::new(storage.system_settings_repo));
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .enable_all()
            .build()
            .expect("runtime");

        runtime.block_on(async {
            preload_settings_cache(&settings_service);
        });

        assert!(settings_service
            .get_cached_u32_sync("rate_limit_auth")
            .is_some());
    }
}