cedros-login-server 0.0.41

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
//! User withdrawal handlers
//!
//! POST /wallet/withdraw/sol       - Withdraw SOL from embedded wallet to external address
//! POST /wallet/withdraw/spl       - Withdraw SPL tokens from embedded wallet to external address
//! GET  /wallet/withdraw/balances  - Get all token balances for the user's wallet
//! GET  /wallet/withdraw/history   - Get paginated withdrawal history for the authenticated user
//!
//! Gated by `feature_user_withdrawals` system setting (disabled by default).
//! Requires an unlocked SSS wallet (cached encryption key) for transfers.

use axum::{
    extract::{Query, State},
    http::HeaderMap,
    Json,
};
use std::sync::Arc;

use crate::callback::AuthCallback;
use crate::errors::AppError;
use crate::repositories::UserWithdrawalLogEntry;
use crate::services::EmailService;
use crate::utils::authenticate;
use crate::AppState;

/// Request to withdraw SOL to an external address
#[derive(Debug, serde::Deserialize)]
pub struct WithdrawSolRequest {
    /// Destination Solana address (base58)
    pub destination: String,
    /// Amount in lamports
    pub amount_lamports: u64,
}

/// Request to withdraw SPL tokens to an external address
#[derive(Debug, serde::Deserialize)]
pub struct WithdrawSplRequest {
    /// Destination Solana address (base58)
    pub destination: String,
    /// SPL token mint address
    pub token_mint: String,
    /// Amount in smallest token unit (string for precision)
    pub amount: String,
}

/// Response from a user withdrawal
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WithdrawalResponse {
    /// Transaction signature on Solana
    pub tx_signature: String,
    /// Transaction fee in lamports
    pub fee_lamports: i64,
}

/// Token balance information returned to the UI
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletBalancesResponse {
    pub sol_lamports: u64,
    pub tokens: Vec<TokenBalance>,
}

/// A single token balance entry
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenBalance {
    pub mint: String,
    pub amount: String,
    pub decimals: u8,
}

/// Query parameters for withdrawal history pagination
#[derive(Debug, serde::Deserialize)]
pub struct WithdrawalHistoryQuery {
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// A single item in the user withdrawal history response
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserWithdrawalHistoryItem {
    pub id: String,
    pub token_type: String,
    pub token_mint: Option<String>,
    pub amount: String,
    pub destination: String,
    pub tx_signature: String,
    pub fee_lamports: i64,
    pub created_at: String,
}

/// Response for GET /wallet/withdraw/history
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserWithdrawalHistoryResponse {
    pub items: Vec<UserWithdrawalHistoryItem>,
    pub total: u64,
}

/// Validate a base58-encoded Solana address
fn validate_destination(destination: &str) -> Result<(), AppError> {
    if destination.len() < 32 || destination.len() > 50 {
        return Err(AppError::Validation(
            "Invalid destination address length".into(),
        ));
    }
    // L-03: Decode and verify 32-byte public key length
    let bytes = bs58::decode(destination).into_vec().map_err(|_| {
        AppError::Validation("Invalid destination address (not valid base58)".into())
    })?;
    if bytes.len() != 32 {
        return Err(AppError::Validation(format!(
            "Invalid destination address: expected 32 bytes, got {}",
            bytes.len()
        )));
    }
    Ok(())
}

/// Check if user withdrawals feature is enabled
async fn check_feature_enabled<C: AuthCallback, E: EmailService>(
    state: &Arc<AppState<C, E>>,
) -> Result<(), AppError> {
    let enabled = state
        .settings_service
        .get_bool("feature_user_withdrawals")
        .await?
        .unwrap_or(false);

    if !enabled {
        return Err(AppError::NotFound("User withdrawals not enabled".into()));
    }
    Ok(())
}

/// Reconstruct private key from wallet material + cached unlock key.
/// Returns the base58-encoded private key (zeroized on drop) and the user ID.
async fn reconstruct_key<C: AuthCallback, E: EmailService>(
    state: &Arc<AppState<C, E>>,
    headers: &HeaderMap,
) -> Result<(zeroize::Zeroizing<String>, uuid::Uuid), AppError> {
    let auth_user = authenticate(state, headers).await?;

    let wallet_material = state
        .wallet_material_repo
        .find_default_by_user(auth_user.user_id)
        .await?
        .ok_or_else(|| {
            AppError::NotFound("SSS wallet not enrolled. Withdrawals require SSS wallet.".into())
        })?;

    let session_id = auth_user.session_id.ok_or_else(|| {
        AppError::Unauthorized("Session required for embedded wallet operations".into())
    })?;

    let cached_key = state
        .wallet_unlock_cache
        .get(session_id)
        .await
        .ok_or_else(|| {
            AppError::Unauthorized("Wallet is locked. Call POST /wallet/unlock first.".into())
        })?;

    let user_private_key = state
        .wallet_signing_service
        .reconstruct_private_key(&wallet_material, &cached_key)
        .map_err(|e| {
            tracing::error!(error = %e, "Failed to reconstruct private key for withdrawal");
            AppError::Internal(anyhow::anyhow!("Failed to reconstruct wallet key"))
        })?;

    Ok((user_private_key, auth_user.user_id))
}

/// GET /wallet/withdraw/balances
///
/// Get SOL balance + all SPL token balances for the authenticated user's wallet.
/// Only requires authentication (wallet does not need to be unlocked).
pub async fn withdraw_balances<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
) -> Result<Json<WalletBalancesResponse>, AppError> {
    check_feature_enabled(&state).await?;

    let auth_user = authenticate(&state, &headers).await?;

    // Get wallet material to find the pubkey (no unlock required)
    let wallet_material = state
        .wallet_material_repo
        .find_default_by_user(auth_user.user_id)
        .await?
        .ok_or_else(|| AppError::NotFound("SSS wallet not enrolled".into()))?;

    let wallet_address = &wallet_material.solana_pubkey;

    let sidecar = state.privacy_sidecar_client.clone().ok_or_else(|| {
        AppError::Internal(anyhow::anyhow!("Privacy sidecar client not configured"))
    })?;

    let balances = sidecar.get_wallet_balances(wallet_address).await?;

    Ok(Json(WalletBalancesResponse {
        sol_lamports: balances.sol_lamports,
        tokens: balances
            .tokens
            .into_iter()
            .map(|t| TokenBalance {
                mint: t.mint,
                amount: t.amount,
                decimals: t.decimals,
            })
            .collect(),
    }))
}

/// POST /wallet/withdraw/sol
///
/// Withdraw SOL from the user's embedded wallet to an external Solana address.
/// Requires `feature_user_withdrawals` enabled and unlocked wallet.
pub async fn withdraw_sol<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Json(request): Json<WithdrawSolRequest>,
) -> Result<Json<WithdrawalResponse>, AppError> {
    check_feature_enabled(&state).await?;

    // KYC enforcement gate
    if let Some(kyc_service) = &state.kyc_service {
        let auth_user = crate::utils::authenticate(&state, &headers).await?;
        kyc_service.check_enforcement(auth_user.user_id, "withdrawals").await?;
    }

    validate_destination(&request.destination)?;
    state.sanctions_service.check_address(&request.destination).await?;

    // Token gate enforcement
    {
        let auth_user = crate::utils::authenticate(&state, &headers).await?;
        state
            .token_gating_service
            .check_enforcement(auth_user.user_id, "withdrawals")
            .await?;
    }

    if request.amount_lamports == 0 {
        return Err(AppError::Validation(
            "amount_lamports must be positive".into(),
        ));
    }

    // R2-H01: Validate amount fits in i64 before any cast
    let amount_i64 = i64::try_from(request.amount_lamports).map_err(|_| {
        AppError::Validation("amount_lamports exceeds maximum allowed value".into())
    })?;

    let (user_private_key, user_id) = reconstruct_key(&state, &headers).await?;

    let sidecar = state.privacy_sidecar_client.clone().ok_or_else(|| {
        AppError::Internal(anyhow::anyhow!("Privacy sidecar client not configured"))
    })?;

    tracing::info!(
        user_id = %user_id,
        destination = %request.destination,
        amount_lamports = request.amount_lamports,
        "User SOL withdrawal initiated"
    );

    let result = sidecar
        .transfer_sol(
            &user_private_key,
            &request.destination,
            request.amount_lamports,
        )
        .await?;

    tracing::info!(
        user_id = %user_id,
        tx_signature = %result.tx_signature,
        "User SOL withdrawal completed"
    );

    // Log the withdrawal (failure must not fail the response — tx already sent)
    if let Err(e) = state
        .user_withdrawal_log_repo
        .create(UserWithdrawalLogEntry::new(
            user_id,
            "sol",
            None,
            amount_i64,
            &request.destination,
            &result.tx_signature,
            result.fee_lamports,
        ))
        .await
    {
        // M-11: Include full context for manual reconciliation
        tracing::error!(
            error = %e,
            user_id = %user_id,
            tx_signature = %result.tx_signature,
            amount_lamports = request.amount_lamports,
            destination = %request.destination,
            fee_lamports = result.fee_lamports,
            "WITHDRAWAL_LOG_FAILURE: SOL withdrawal succeeded but log write failed"
        );
    }

    Ok(Json(WithdrawalResponse {
        tx_signature: result.tx_signature,
        fee_lamports: result.fee_lamports,
    }))
}

/// POST /wallet/withdraw/spl
///
/// Withdraw any SPL token from the user's embedded wallet to an external address.
/// Requires `feature_user_withdrawals` enabled and unlocked wallet.
pub async fn withdraw_spl<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Json(request): Json<WithdrawSplRequest>,
) -> Result<Json<WithdrawalResponse>, AppError> {
    check_feature_enabled(&state).await?;

    // KYC enforcement gate
    if let Some(kyc_service) = &state.kyc_service {
        let auth_user = crate::utils::authenticate(&state, &headers).await?;
        kyc_service.check_enforcement(auth_user.user_id, "withdrawals").await?;
    }

    validate_destination(&request.destination)?;
    state.sanctions_service.check_address(&request.destination).await?;

    // Token gate enforcement
    {
        let auth_user = crate::utils::authenticate(&state, &headers).await?;
        state
            .token_gating_service
            .check_enforcement(auth_user.user_id, "withdrawals")
            .await?;
    }

    // Validate token_mint is a valid base58 address
    if request.token_mint.len() < 32
        || request.token_mint.len() > 50
        || bs58::decode(&request.token_mint).into_vec().is_err()
    {
        return Err(AppError::Validation(
            "token_mint must be a valid Solana address".into(),
        ));
    }

    // Validate amount
    let amount_val: u64 = request
        .amount
        .parse()
        .map_err(|_| AppError::Validation("amount must be a valid integer string".into()))?;
    if amount_val == 0 {
        return Err(AppError::Validation("amount must be positive".into()));
    }

    let (user_private_key, user_id) = reconstruct_key(&state, &headers).await?;

    let sidecar = state.privacy_sidecar_client.clone().ok_or_else(|| {
        AppError::Internal(anyhow::anyhow!("Privacy sidecar client not configured"))
    })?;

    tracing::info!(
        user_id = %user_id,
        destination = %request.destination,
        token_mint = %request.token_mint,
        amount = %request.amount,
        "User SPL withdrawal initiated"
    );

    let result = sidecar
        .transfer_spl(
            &user_private_key,
            &request.destination,
            &request.token_mint,
            &request.amount,
        )
        .await?;

    tracing::info!(
        user_id = %user_id,
        tx_signature = %result.tx_signature,
        "User SPL withdrawal completed"
    );

    // Log the withdrawal (failure must not fail the response — tx already sent)
    if let Err(e) = state
        .user_withdrawal_log_repo
        .create(UserWithdrawalLogEntry::new(
            user_id,
            "spl",
            Some(&request.token_mint),
            amount_val as i64,
            &request.destination,
            &result.tx_signature,
            result.fee_lamports,
        ))
        .await
    {
        // M-11: Include full context for manual reconciliation
        tracing::error!(
            error = %e,
            user_id = %user_id,
            tx_signature = %result.tx_signature,
            token_mint = %request.token_mint,
            amount = %request.amount,
            destination = %request.destination,
            fee_lamports = result.fee_lamports,
            "WITHDRAWAL_LOG_FAILURE: SPL withdrawal succeeded but log write failed"
        );
    }

    Ok(Json(WithdrawalResponse {
        tx_signature: result.tx_signature,
        fee_lamports: result.fee_lamports,
    }))
}

/// GET /wallet/withdraw/history
///
/// Get paginated withdrawal history for the authenticated user.
/// Requires `feature_user_withdrawals` enabled and authentication.
pub async fn withdraw_history<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Query(params): Query<WithdrawalHistoryQuery>,
) -> Result<Json<UserWithdrawalHistoryResponse>, AppError> {
    check_feature_enabled(&state).await?;

    let auth_user = authenticate(&state, &headers).await?;
    let limit = params.limit.unwrap_or(10).min(100);
    let offset = params.offset.unwrap_or(0);

    let entries = state
        .user_withdrawal_log_repo
        .find_by_user(auth_user.user_id, limit, offset)
        .await?;
    let total = state
        .user_withdrawal_log_repo
        .count_by_user(auth_user.user_id)
        .await?;

    let items = entries
        .into_iter()
        .map(|e| UserWithdrawalHistoryItem {
            id: e.id.to_string(),
            token_type: e.token_type,
            token_mint: e.token_mint,
            amount: e.amount.to_string(),
            destination: e.destination,
            tx_signature: e.tx_signature,
            fee_lamports: e.fee_lamports,
            created_at: e.created_at.to_rfc3339(),
        })
        .collect();

    Ok(Json(UserWithdrawalHistoryResponse { items, total }))
}