uptrakit-web-api-types 0.0.4

Shared HTTP request/response types for the Uptrakit web API
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
use serde::{Deserialize, Serialize};
use std::fmt;

use crate::validation::{Validate, ValidationError};

/// Identifies the MFA method used in a challenge verification request.
///
/// Deserialized from HTTP bodies — uses infallible custom `Deserialize` with
/// `Other(String)` so unknown methods never cause a 400 parse error.
/// Loses `Copy` due to `String`.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum MfaMethod {
    Totp,
    Email,
    RecoveryCode,
    /// Unknown method from a future client; verified as false.
    #[cfg_attr(feature = "openapi", schema(value_type = String))]
    Other(String),
}

impl MfaMethod {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Totp => "totp",
            Self::Email => "email",
            Self::RecoveryCode => "recovery_code",
            Self::Other(s) => s.as_str(),
        }
    }
}

impl fmt::Display for MfaMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<String> for MfaMethod {
    fn from(s: String) -> Self {
        match s.as_str() {
            "totp" => Self::Totp,
            "email" => Self::Email,
            "recovery_code" => Self::RecoveryCode,
            _ => Self::Other(s),
        }
    }
}

impl<'de> Deserialize<'de> for MfaMethod {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Ok(Self::from(s))
    }
}

/// Returned by `POST /api/v1/auth/login` when the user has 2FA enrolled.
#[non_exhaustive]
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MfaChallengeResponse {
    pub mfa_token: String,
    pub mfa_methods: Vec<MfaMethod>,
}

impl MfaChallengeResponse {
    pub fn new(mfa_token: String, mfa_methods: Vec<MfaMethod>) -> Self {
        Self {
            mfa_token,
            mfa_methods,
        }
    }
}

/// Body for `POST /api/v1/auth/mfa/verify`.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MfaVerifyRequest {
    pub mfa_token: String,
    pub code: String,
    pub method: MfaMethod,
}

impl Validate for MfaVerifyRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.mfa_token.is_empty() {
            return Err(ValidationError {
                field: "mfa_token",
                message: "mfa_token must not be empty".to_string(),
            });
        }
        if self.code.is_empty() {
            return Err(ValidationError {
                field: "code",
                message: "code must not be empty".to_string(),
            });
        }
        Ok(())
    }
}

/// Body for `POST /api/v1/auth/mfa/email`.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MfaEmailRequest {
    pub mfa_token: String,
}

impl Validate for MfaEmailRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.mfa_token.is_empty() {
            return Err(ValidationError {
                field: "mfa_token",
                message: "mfa_token must not be empty".to_string(),
            });
        }
        Ok(())
    }
}

/// Returned by `GET /api/v1/auth/me/2fa`.
#[non_exhaustive]
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MfaStatusResponse {
    pub totp_enrolled: bool,
    pub recovery_codes_count: u32,
    pub methods_available: Vec<MfaMethod>,
}

impl MfaStatusResponse {
    /// Construct a new [`MfaStatusResponse`].
    #[must_use]
    pub fn new(
        totp_enrolled: bool,
        recovery_codes_count: u32,
        methods_available: Vec<MfaMethod>,
    ) -> Self {
        Self {
            totp_enrolled,
            recovery_codes_count,
            methods_available,
        }
    }
}

/// Returned by `POST /api/v1/auth/me/2fa/totp/enroll`.
#[non_exhaustive]
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TotpEnrollResponse {
    /// `otpauth://totp/` URI for QR generation in the browser.
    pub otpauth_uri: String,
    /// Human-readable base32 secret (for manual entry). Treated as a secret —
    /// never logged.
    pub secret: uptrakit_shared_types::SecretString,
}

impl TotpEnrollResponse {
    /// Construct a new [`TotpEnrollResponse`].
    #[must_use]
    pub fn new(otpauth_uri: String, secret: uptrakit_shared_types::SecretString) -> Self {
        Self {
            otpauth_uri,
            secret,
        }
    }
}

/// Body for `POST /api/v1/auth/me/2fa/totp/confirm`.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TotpConfirmRequest {
    pub code: String,
}

impl Validate for TotpConfirmRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.code.len() != 6 || !self.code.chars().all(|c| c.is_ascii_digit()) {
            return Err(ValidationError {
                field: "code",
                message: "code must be exactly 6 digits".to_string(),
            });
        }
        Ok(())
    }
}

/// Returned by `POST /api/v1/auth/me/2fa/totp/confirm`.
#[non_exhaustive]
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TotpConfirmResponse {
    /// Plaintext recovery codes shown once.
    pub recovery_codes: Vec<String>,
    /// New full-session tokens (replaces the restricted session, if any).
    pub session: Option<crate::auth::AuthResponse>,
}

impl TotpConfirmResponse {
    /// Construct a new [`TotpConfirmResponse`].
    #[must_use]
    pub fn new(recovery_codes: Vec<String>, session: Option<crate::auth::AuthResponse>) -> Self {
        Self {
            recovery_codes,
            session,
        }
    }
}

/// Body for `POST /api/v1/auth/me/2fa/totp/disable`.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct DisableTotpRequest {
    pub password: Option<uptrakit_shared_types::SecretString>,
    pub totp_code: Option<String>,
}

impl Validate for DisableTotpRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        match (&self.password, &self.totp_code) {
            (Some(_), None) | (None, Some(_)) => Ok(()),
            _ => Err(ValidationError {
                field: "password",
                message: "exactly one of password or totp_code must be provided".to_string(),
            }),
        }
    }
}

/// Body for `POST /api/v1/auth/me/2fa/recovery-codes/regenerate`.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct RegenerateRecoveryCodesRequest {
    pub password: Option<uptrakit_shared_types::SecretString>,
    pub totp_code: Option<String>,
}

impl Validate for RegenerateRecoveryCodesRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        match (&self.password, &self.totp_code) {
            (Some(_), None) | (None, Some(_)) => Ok(()),
            _ => Err(ValidationError {
                field: "password",
                message: "exactly one of password or totp_code must be provided".to_string(),
            }),
        }
    }
}

/// Returned by `POST /api/v1/auth/me/2fa/recovery-codes/regenerate`.
#[non_exhaustive]
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct RegenerateRecoveryCodesResponse {
    pub recovery_codes: Vec<String>,
}

impl RegenerateRecoveryCodesResponse {
    /// Construct a new [`RegenerateRecoveryCodesResponse`].
    #[must_use]
    pub fn new(recovery_codes: Vec<String>) -> Self {
        Self { recovery_codes }
    }
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::assertions_on_result_states,
        reason = "test assertions — is_ok/is_err provides readable failure messages"
    )]
    use super::*;

    // ── MfaMethod enum ───────────────────────────────────────────────────────

    #[test]
    fn mfa_method_totp_as_str() {
        assert_eq!(MfaMethod::Totp.as_str(), "totp");
    }

    #[test]
    fn mfa_method_email_as_str() {
        assert_eq!(MfaMethod::Email.as_str(), "email");
    }

    #[test]
    fn mfa_method_recovery_code_as_str() {
        assert_eq!(MfaMethod::RecoveryCode.as_str(), "recovery_code");
    }

    #[test]
    fn mfa_method_other_as_str() {
        let other = MfaMethod::Other("future_method".to_string());
        assert_eq!(other.as_str(), "future_method");
    }

    #[test]
    fn mfa_method_display_matches_as_str() {
        assert_eq!(format!("{}", MfaMethod::Totp), "totp");
        assert_eq!(format!("{}", MfaMethod::Email), "email");
        assert_eq!(format!("{}", MfaMethod::RecoveryCode), "recovery_code");
    }

    #[test]
    fn mfa_method_from_string_totp() {
        assert_eq!(MfaMethod::from("totp".to_string()), MfaMethod::Totp);
    }

    #[test]
    fn mfa_method_from_string_email() {
        assert_eq!(MfaMethod::from("email".to_string()), MfaMethod::Email);
    }

    #[test]
    fn mfa_method_from_string_recovery_code() {
        assert_eq!(
            MfaMethod::from("recovery_code".to_string()),
            MfaMethod::RecoveryCode
        );
    }

    #[test]
    fn mfa_method_from_string_unknown() {
        let unknown = MfaMethod::from("future_method".to_string());
        assert!(matches!(
            unknown,
            MfaMethod::Other(ref s) if s == "future_method"
        ));
    }

    #[test]
    fn mfa_method_serde_round_trip_totp() {
        let method = MfaMethod::Totp;
        let json = serde_json::to_string(&method).unwrap();
        let deserialized: MfaMethod = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, method);
    }

    #[test]
    fn mfa_method_serde_round_trip_recovery_code() {
        let method = MfaMethod::RecoveryCode;
        let json = serde_json::to_string(&method).unwrap();
        let deserialized: MfaMethod = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, method);
    }

    #[test]
    fn mfa_method_deserialize_unknown() {
        let json = r#""future_method""#;
        let method: MfaMethod = serde_json::from_str(json).unwrap();
        assert!(matches!(
            method,
            MfaMethod::Other(ref s) if s == "future_method"
        ));
    }

    // ── MfaVerifyRequest ─────────────────────────────────────────────────────

    fn valid_mfa_verify() -> MfaVerifyRequest {
        MfaVerifyRequest {
            mfa_token: "token_123".to_string(),
            code: "123456".to_string(),
            method: MfaMethod::Totp,
        }
    }

    #[test]
    fn mfa_verify_request_valid() {
        assert!(valid_mfa_verify().validate().is_ok());
    }

    #[test]
    fn mfa_verify_request_empty_token() {
        let mut req = valid_mfa_verify();
        req.mfa_token = String::new();
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "mfa_token");
    }

    #[test]
    fn mfa_verify_request_empty_code() {
        let mut req = valid_mfa_verify();
        req.code = String::new();
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "code");
    }

    // ── MfaEmailRequest ──────────────────────────────────────────────────────

    fn valid_mfa_email() -> MfaEmailRequest {
        MfaEmailRequest {
            mfa_token: "token_123".to_string(),
        }
    }

    #[test]
    fn mfa_email_request_valid() {
        assert!(valid_mfa_email().validate().is_ok());
    }

    #[test]
    fn mfa_email_request_empty_token() {
        let mut req = valid_mfa_email();
        req.mfa_token = String::new();
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "mfa_token");
    }

    // ── TotpConfirmRequest ───────────────────────────────────────────────────

    #[test]
    fn totp_confirm_request_valid() {
        let req = TotpConfirmRequest {
            code: "123456".to_string(),
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn totp_confirm_request_not_digits() {
        let req = TotpConfirmRequest {
            code: "12345a".to_string(),
        };
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "code");
    }

    #[test]
    fn totp_confirm_request_too_short() {
        let req = TotpConfirmRequest {
            code: "12345".to_string(),
        };
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "code");
    }

    #[test]
    fn totp_confirm_request_too_long() {
        let req = TotpConfirmRequest {
            code: "1234567".to_string(),
        };
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "code");
    }

    // ── DisableTotpRequest ───────────────────────────────────────────────────

    #[test]
    fn disable_totp_request_with_password() {
        let req = DisableTotpRequest {
            password: Some(uptrakit_shared_types::SecretString::new("pass123")),
            totp_code: None,
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn disable_totp_request_with_totp_code() {
        let req = DisableTotpRequest {
            password: None,
            totp_code: Some("123456".to_string()),
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn disable_totp_request_with_both() {
        let req = DisableTotpRequest {
            password: Some(uptrakit_shared_types::SecretString::new("pass123")),
            totp_code: Some("123456".to_string()),
        };
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "password");
    }

    #[test]
    fn disable_totp_request_with_neither() {
        let req = DisableTotpRequest {
            password: None,
            totp_code: None,
        };
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "password");
    }

    // ── RegenerateRecoveryCodesRequest ───────────────────────────────────────

    #[test]
    fn regenerate_recovery_codes_request_with_password() {
        let req = RegenerateRecoveryCodesRequest {
            password: Some(uptrakit_shared_types::SecretString::new("pass123")),
            totp_code: None,
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn regenerate_recovery_codes_request_with_totp_code() {
        let req = RegenerateRecoveryCodesRequest {
            password: None,
            totp_code: Some("123456".to_string()),
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn regenerate_recovery_codes_request_with_both() {
        let req = RegenerateRecoveryCodesRequest {
            password: Some(uptrakit_shared_types::SecretString::new("pass123")),
            totp_code: Some("123456".to_string()),
        };
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "password");
    }

    #[test]
    fn regenerate_recovery_codes_request_with_neither() {
        let req = RegenerateRecoveryCodesRequest {
            password: None,
            totp_code: None,
        };
        let err = req.validate().unwrap_err();
        assert_eq!(err.field, "password");
    }

    // ── Struct serialization round-trips ─────────────────────────────────────

    #[test]
    fn mfa_challenge_response_round_trip() {
        let resp = MfaChallengeResponse {
            mfa_token: "token_abc".to_string(),
            mfa_methods: vec![MfaMethod::Totp, MfaMethod::Email],
        };
        let json = serde_json::to_string(&resp).unwrap();
        let deserialized: MfaChallengeResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.mfa_token, "token_abc");
        assert_eq!(deserialized.mfa_methods.len(), 2);
        assert_eq!(deserialized.mfa_methods[0], MfaMethod::Totp);
        assert_eq!(deserialized.mfa_methods[1], MfaMethod::Email);
    }

    #[test]
    fn mfa_status_response_round_trip() {
        let resp = MfaStatusResponse {
            totp_enrolled: true,
            recovery_codes_count: 5,
            methods_available: vec![MfaMethod::Totp, MfaMethod::Email, MfaMethod::RecoveryCode],
        };
        let json = serde_json::to_string(&resp).unwrap();
        let deserialized: MfaStatusResponse = serde_json::from_str(&json).unwrap();
        assert!(deserialized.totp_enrolled);
        assert_eq!(deserialized.recovery_codes_count, 5);
        assert_eq!(deserialized.methods_available.len(), 3);
    }

    #[test]
    fn totp_enroll_response_round_trip() {
        let resp = TotpEnrollResponse {
            otpauth_uri: "otpauth://totp/test".to_string(),
            secret: uptrakit_shared_types::SecretString::new("JBSWY3DPEBLW64TMMQ======"),
        };
        let json = serde_json::to_string(&resp).unwrap();
        let deserialized: TotpEnrollResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.otpauth_uri, "otpauth://totp/test");
        assert_eq!(
            deserialized.secret.expose_secret(),
            "JBSWY3DPEBLW64TMMQ======"
        );
    }

    #[test]
    fn totp_confirm_response_round_trip() {
        let resp = TotpConfirmResponse {
            recovery_codes: vec!["code1".to_string(), "code2".to_string()],
            session: None,
        };
        let json = serde_json::to_string(&resp).unwrap();
        let deserialized: TotpConfirmResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.recovery_codes.len(), 2);
        assert!(deserialized.session.is_none());
    }

    #[test]
    fn regenerate_recovery_codes_response_round_trip() {
        let resp = RegenerateRecoveryCodesResponse {
            recovery_codes: vec![
                "code1".to_string(),
                "code2".to_string(),
                "code3".to_string(),
            ],
        };
        let json = serde_json::to_string(&resp).unwrap();
        let deserialized: RegenerateRecoveryCodesResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.recovery_codes.len(), 3);
    }
}