Skip to main content

rustfs_iam/mfa/
service.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The MFA operations the admin API exposes.
16//!
17//! This is the whole feature's surface: the console and the `rc` CLI reach it
18//! through the same admin endpoints, and neither carries any of the logic. The
19//! functions return `rustfs-madmin` wire types directly rather than a private
20//! shape plus a mapping layer, so there is one definition of what a client sees.
21//!
22//! Errors are deliberately coarse at this boundary. [`MfaServiceError`] tells a
23//! handler which HTTP status and which audit class to use, and nothing more: a
24//! caller must not be able to tell a wrong code from a replayed one, or an
25//! identity with no enrollment from one that is locked out.
26
27use super::record::{MfaVerification, MfaVerifyError};
28use super::totp::{TOTP_ALGORITHM, TOTP_DIGITS, TOTP_PERIOD_SECONDS, TotpSecret, provisioning_uri};
29use super::{challenge, qr, recovery, store};
30use crate::IamStore;
31use crate::error::Error;
32use rustfs_madmin::account::{MfaEnrollResponse, MfaStatus, RecoveryCodesResponse, UserMfaStatus};
33use std::sync::Arc;
34use time::OffsetDateTime;
35
36/// Issuer shown by the authenticator app.
37///
38/// Constant rather than derived from the deployment: apps key their entries on
39/// issuer plus account, so a value that changed with the hostname would make an
40/// existing enrollment look like a different account after a rename.
41pub const MFA_ISSUER: &str = "RustFS";
42
43/// What went wrong, at the granularity a handler needs.
44#[derive(Debug, thiserror::Error)]
45pub enum MfaServiceError {
46    #[error("two-factor authentication is not available: {0}")]
47    EnrollmentUnavailable(&'static str),
48    #[error("two-factor authentication is not enabled for this identity")]
49    NotEnabled,
50    #[error("two-factor authentication is already enabled for this identity")]
51    AlreadyEnabled,
52    #[error("no pending enrollment to confirm")]
53    NoPendingEnrollment,
54    #[error("the verification code is invalid")]
55    InvalidCode,
56    #[error("too many failed attempts; retry in {retry_after_seconds}s")]
57    Locked { retry_after_seconds: u64 },
58    #[error("the login challenge is invalid or has expired")]
59    InvalidChallenge,
60    #[error("{0}")]
61    Internal(String),
62}
63
64impl From<Error> for MfaServiceError {
65    fn from(value: Error) -> Self {
66        Self::Internal(value.to_string())
67    }
68}
69
70/// The audit class for a failure, so every handler classifies identically.
71impl MfaServiceError {
72    pub const fn audit_class(&self) -> &'static str {
73        match self {
74            Self::EnrollmentUnavailable(_) => "enrollment_unavailable",
75            Self::NotEnabled | Self::NoPendingEnrollment => "not_enrolled",
76            Self::AlreadyEnabled => "already_enabled",
77            Self::InvalidCode => "invalid_code",
78            Self::Locked { .. } => "rate_limited",
79            Self::InvalidChallenge => "challenge_invalid",
80            Self::Internal(_) => "internal_error",
81        }
82    }
83}
84
85fn map_verify_error(error: MfaVerifyError) -> MfaServiceError {
86    match error {
87        MfaVerifyError::NotEnabled => MfaServiceError::NotEnabled,
88        MfaVerifyError::Locked { retry_after_seconds } => MfaServiceError::Locked { retry_after_seconds },
89        // Wrong, replayed and malformed all collapse to one answer on the wire.
90        // The distinction survives only in the audit trail, which the caller
91        // reads from `MfaVerification`/the record, not from this error.
92        MfaVerifyError::InvalidCode | MfaVerifyError::ReplayedTotpCode | MfaVerifyError::ReplayedRecoveryCode => {
93            MfaServiceError::InvalidCode
94        }
95    }
96}
97
98/// Report the caller's own MFA state.
99pub async fn status(api: Arc<IamStore>, access_key: &str, now: OffsetDateTime) -> Result<MfaStatus, MfaServiceError> {
100    let loaded = store::load(api, access_key, now).await?;
101    let record = loaded.record;
102    let available = store::at_rest_protection_available();
103
104    Ok(MfaStatus {
105        enabled: record.is_enabled(),
106        pending: record.has_pending_enrollment(now),
107        algorithm: record.algorithm.clone(),
108        digits: record.digits,
109        period_seconds: record.period_seconds,
110        activated_at: record.activated_at,
111        pending_expires_at: record
112            .has_pending_enrollment(now)
113            .then_some(record.pending_expires_at)
114            .flatten(),
115        recovery_codes_remaining: record.recovery_codes_remaining(),
116        last_verified_at: record.last_verified_at,
117        enrollment_available: available,
118        enrollment_blocked_reason: (!available).then(|| store::ENROLLMENT_UNAVAILABLE_REASON.to_string()),
119    })
120}
121
122/// Report another identity's MFA state, for an administrator.
123///
124/// Narrower than [`status`] on purpose: an administrator inspecting someone
125/// else's account has no need for their enrollment internals.
126pub async fn admin_status(api: Arc<IamStore>, access_key: &str, now: OffsetDateTime) -> Result<UserMfaStatus, MfaServiceError> {
127    let record = store::load(api, access_key, now).await?.record;
128
129    Ok(UserMfaStatus {
130        access_key: access_key.to_string(),
131        enabled: record.is_enabled(),
132        activated_at: record.activated_at,
133        recovery_codes_remaining: record.recovery_codes_remaining(),
134    })
135}
136
137/// Whether `access_key` must present a second factor.
138///
139/// The login path's gate. Propagates a store failure rather than answering
140/// `false`, so an outage cannot silently disable the second factor.
141pub async fn is_enabled(api: Arc<IamStore>, access_key: &str, now: OffsetDateTime) -> Result<bool, MfaServiceError> {
142    Ok(store::is_enabled(api, access_key, now).await?)
143}
144
145/// Begin an enrollment and return everything needed to complete it.
146///
147/// Calling this on an already-enrolled identity is a re-configuration, not an
148/// error: the active factor keeps working until the new one is confirmed.
149pub async fn enroll(api: Arc<IamStore>, access_key: &str, now: OffsetDateTime) -> Result<MfaEnrollResponse, MfaServiceError> {
150    if !store::at_rest_protection_available() {
151        return Err(MfaServiceError::EnrollmentUnavailable(store::ENROLLMENT_UNAVAILABLE_REASON));
152    }
153
154    let secret = TotpSecret::generate();
155    let uri = provisioning_uri(MFA_ISSUER, access_key, &secret);
156    let rendered = qr::render(&uri).map_err(|err| MfaServiceError::Internal(err.to_string()))?;
157
158    let secret_for_store = secret.clone();
159    let expires_at = store::update(api, access_key, now, move |record| {
160        record.begin_enrollment(&secret_for_store, now);
161        Ok::<_, MfaServiceError>(record.pending_expires_at)
162    })
163    .await?;
164
165    let expires_at = expires_at.ok_or_else(|| MfaServiceError::Internal("enrollment expiry was not recorded".to_string()))?;
166
167    Ok(MfaEnrollResponse {
168        secret_base32: secret.to_base32(),
169        otpauth_uri: uri,
170        qr_svg: rendered.svg,
171        qr_utf8: rendered.utf8,
172        algorithm: TOTP_ALGORITHM.to_string(),
173        digits: TOTP_DIGITS,
174        period_seconds: TOTP_PERIOD_SECONDS,
175        expires_at,
176    })
177}
178
179/// Confirm a pending enrollment and issue the first set of recovery codes.
180///
181/// The codes are returned once and never again: only their hashes are stored.
182pub async fn activate(
183    api: Arc<IamStore>,
184    access_key: &str,
185    code: &str,
186    now: OffsetDateTime,
187) -> Result<RecoveryCodesResponse, MfaServiceError> {
188    let code = code.to_string();
189
190    let plaintext = store::update(api, access_key, now, move |record| {
191        if !record.has_pending_enrollment(now) {
192            return Err(MfaServiceError::NoPendingEnrollment);
193        }
194
195        record.activate_enrollment(&code, now).map_err(map_verify_error)?;
196
197        // Activation always replaces the recovery codes. Reusing a previous set
198        // would leave codes valid for a secret they were never issued against.
199        let generated = recovery::generate();
200        record.set_recovery_codes(generated.stored, now);
201        Ok(generated.plaintext)
202    })
203    .await?;
204
205    Ok(RecoveryCodesResponse {
206        recovery_codes: plaintext,
207        generated_at: now,
208    })
209}
210
211/// Replace the recovery codes, after proving possession of the second factor.
212pub async fn regenerate_recovery_codes(
213    api: Arc<IamStore>,
214    access_key: &str,
215    code: &str,
216    now: OffsetDateTime,
217) -> Result<RecoveryCodesResponse, MfaServiceError> {
218    let code = code.to_string();
219
220    let plaintext = store::update(api, access_key, now, move |record| {
221        if !record.is_enabled() {
222            return Err(MfaServiceError::NotEnabled);
223        }
224
225        record.verify(&code, now).map_err(map_verify_error)?;
226
227        let generated = recovery::generate();
228        record.set_recovery_codes(generated.stored, now);
229        Ok(generated.plaintext)
230    })
231    .await?;
232
233    Ok(RecoveryCodesResponse {
234        recovery_codes: plaintext,
235        generated_at: now,
236    })
237}
238
239/// Turn the second factor off, after proving possession of it.
240///
241/// The caller is expected to have already re-verified the account password:
242/// this function checks the factor, not the identity.
243pub async fn disable(api: Arc<IamStore>, access_key: &str, code: &str, now: OffsetDateTime) -> Result<(), MfaServiceError> {
244    let code = code.to_string();
245
246    store::update(api, access_key, now, move |record| {
247        if !record.is_enabled() {
248            return Err(MfaServiceError::NotEnabled);
249        }
250
251        record.verify(&code, now).map_err(map_verify_error)?;
252
253        record.disable();
254        Ok(())
255    })
256    .await
257}
258
259/// Clear an identity's second factor administratively.
260///
261/// The break-glass path for a user who lost both their authenticator and their
262/// recovery codes. Deletes the record outright rather than disabling it, so no
263/// stale lockout counter survives to block the user's next enrollment.
264pub async fn admin_reset(api: Arc<IamStore>, access_key: &str) -> Result<(), MfaServiceError> {
265    Ok(store::delete(api, access_key).await?)
266}
267
268/// Verify a second factor during session minting.
269///
270/// Returns which factor satisfied it, so the caller can audit a recovery-code
271/// login differently from a routine one and warn when the codes run low.
272pub async fn verify(
273    api: Arc<IamStore>,
274    access_key: &str,
275    code: &str,
276    now: OffsetDateTime,
277) -> Result<MfaVerification, MfaServiceError> {
278    let code = code.to_string();
279
280    store::update(api, access_key, now, move |record| record.verify(&code, now).map_err(map_verify_error)).await
281}
282
283/// Issue a login challenge for `access_key`.
284pub fn issue_challenge(access_key: &str, now: OffsetDateTime, signing_key: &[u8]) -> String {
285    challenge::issue(access_key, now.unix_timestamp().max(0) as u64, signing_key)
286}
287
288/// Validate a login challenge presented alongside a second factor.
289pub fn validate_challenge(
290    challenge_token: &str,
291    access_key: &str,
292    now: OffsetDateTime,
293    signing_key: &[u8],
294) -> Result<(), MfaServiceError> {
295    challenge::validate(challenge_token, access_key, now.unix_timestamp().max(0) as u64, signing_key)
296        .map_err(|_| MfaServiceError::InvalidChallenge)
297}
298
299/// How long an issued challenge remains valid.
300pub const fn challenge_ttl_seconds() -> u64 {
301    challenge::CHALLENGE_TTL_SECONDS
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    #[test]
309    fn wrong_replayed_and_malformed_codes_are_indistinguishable_on_the_wire() {
310        // The security property: a caller probing the endpoint must not be able
311        // to tell that a code was *correct but replayed*, which would confirm
312        // they had captured a real code.
313        for error in [
314            MfaVerifyError::InvalidCode,
315            MfaVerifyError::ReplayedTotpCode,
316            MfaVerifyError::ReplayedRecoveryCode,
317        ] {
318            let mapped = map_verify_error(error);
319            assert!(matches!(mapped, MfaServiceError::InvalidCode), "{error:?} leaked as {mapped}");
320            assert_eq!(mapped.to_string(), "the verification code is invalid");
321        }
322    }
323
324    #[test]
325    fn a_lockout_reports_its_retry_hint() {
326        let mapped = map_verify_error(MfaVerifyError::Locked {
327            retry_after_seconds: 900,
328        });
329        assert!(matches!(
330            mapped,
331            MfaServiceError::Locked {
332                retry_after_seconds: 900
333            }
334        ));
335        assert_eq!(mapped.audit_class(), "rate_limited");
336    }
337
338    #[test]
339    fn verification_failures_map_to_their_audit_classes() {
340        for (error, expected) in [
341            (MfaVerifyError::InvalidCode, "invalid_code"),
342            (MfaVerifyError::ReplayedTotpCode, "invalid_code"),
343            (MfaVerifyError::ReplayedRecoveryCode, "invalid_code"),
344            (MfaVerifyError::NotEnabled, "not_enrolled"),
345            (MfaVerifyError::Locked { retry_after_seconds: 60 }, "rate_limited"),
346        ] {
347            assert_eq!(map_verify_error(error).audit_class(), expected, "for {error:?}");
348        }
349    }
350
351    #[test]
352    fn a_storage_error_stays_internal() {
353        // A disk or quorum failure must not be reported to the user as a bad
354        // code, or they will keep retrying a request that cannot succeed.
355        let mapped = MfaServiceError::from(Error::other("erasure set is offline"));
356
357        assert!(matches!(mapped, MfaServiceError::Internal(_)));
358        assert_eq!(mapped.audit_class(), "internal_error");
359    }
360
361    #[test]
362    fn the_issuer_is_stable() {
363        // Authenticator apps key entries on issuer plus account; a value that
364        // moved with the hostname would orphan existing enrollments.
365        assert_eq!(MFA_ISSUER, "RustFS");
366    }
367
368    #[test]
369    fn challenges_issued_here_validate_here() {
370        let now = OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid timestamp");
371        let key = b"signing-key";
372        let token = issue_challenge("sinan", now, key);
373
374        assert!(validate_challenge(&token, "sinan", now, key).is_ok());
375        assert!(matches!(
376            validate_challenge(&token, "someone-else", now, key),
377            Err(MfaServiceError::InvalidChallenge)
378        ));
379    }
380
381    #[test]
382    fn every_error_has_a_distinct_audit_class_where_it_matters() {
383        // Enrollment-unavailable and locked must not be reported as a bad code:
384        // both are actionable by the operator or the user, and conflating them
385        // with a wrong code hides the remedy.
386        assert_eq!(MfaServiceError::EnrollmentUnavailable("x").audit_class(), "enrollment_unavailable");
387        assert_eq!(MfaServiceError::Locked { retry_after_seconds: 1 }.audit_class(), "rate_limited");
388        assert_eq!(MfaServiceError::InvalidCode.audit_class(), "invalid_code");
389        assert_eq!(MfaServiceError::InvalidChallenge.audit_class(), "challenge_invalid");
390    }
391}