Skip to main content

rustfs_iam/mfa/
store.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//! Persistence for MFA records.
16//!
17//! Records live in the same object store and under the same at-rest encryption
18//! as IAM identities, one object per identity:
19//!
20//! ```text
21//! .rustfs.sys/config/mfa/<access-key>/totp.json
22//! ```
23//!
24//! # Why `config/mfa/` and not `config/iam/mfa/`
25//!
26//! The IAM cache loader walks the whole of `config/iam/` on startup and buckets
27//! every key it finds by its first path segment. A new prefix under there would
28//! be swept into that walk for no benefit, so MFA records sit in a sibling
29//! prefix. They still go through the IAM at-rest crypto, which is the part worth
30//! sharing.
31//!
32//! # Concurrency
33//!
34//! Every mutation is a read-modify-write, and two of them racing would lose an
35//! update — including, in the worst case, a replay high-water mark or a spent
36//! recovery code. Rather than holding a distributed lock across the round trip,
37//! writes carry the ETag they read as an `If-Match` precondition and retry when
38//! the store reports a conflict. That is the same optimistic scheme the IAM
39//! lazy-rewrite path already uses, and it degrades to a retry rather than to a
40//! held lock that a crashed node would have to time out.
41//!
42//! # No caching
43//!
44//! Records are read from the store on every verification. A cache would need
45//! cluster-wide invalidation to keep the replay mark and the lockout counter
46//! honest, and getting that wrong reopens exactly the holes this module exists
47//! to close. Verifications are rare enough that the read is not worth
48//! optimising.
49
50use super::record::MfaRecord;
51use crate::error::{Error, Result, is_err_config_not_found};
52use crate::storage_api::object_store::HTTPPreconditions;
53use crate::store::object::{decrypt_iam_blob, encrypt_iam_blob};
54use crate::{
55    IAM_CONFIG_ROOT_PREFIX, IamStorageError, IamStore, delete_iam_config, keyring, read_iam_config_with_metadata,
56    save_iam_config_with_opts,
57};
58use std::sync::Arc;
59use time::OffsetDateTime;
60use tracing::warn;
61
62type IamObjectOptions = <IamStore as crate::storage_api::object_store::ObjectOperations>::ObjectOptions;
63
64/// Attempts before a contended write gives up.
65///
66/// A conflict means another request for the *same identity* wrote first, which
67/// is rare; more than a few in a row means something is wrong rather than busy.
68const MAX_WRITE_ATTEMPTS: usize = 5;
69
70/// Path of the record for `access_key`.
71fn record_path(access_key: &str) -> String {
72    format!("{IAM_CONFIG_ROOT_PREFIX}/mfa/{access_key}/totp.json")
73}
74
75/// Whether the server can protect a TOTP secret at rest.
76///
77/// Enrollment is refused when this is false. A TOTP secret is credential-
78/// equivalent — anyone holding it can mint valid codes forever — so writing one
79/// in plaintext would let the second factor be lifted straight off a disk,
80/// leaving the user with a false sense of protection. IAM identities tolerate a
81/// missing master key for backward compatibility with existing deployments;
82/// a new feature has no such history to honour.
83pub fn at_rest_protection_available() -> bool {
84    keyring::encrypt_key().is_some()
85}
86
87/// Operator-facing explanation for a refused enrollment.
88pub const ENROLLMENT_UNAVAILABLE_REASON: &str =
89    "two-factor authentication requires RUSTFS_IAM_MASTER_KEY to be configured so the shared secret can be encrypted at rest";
90
91/// A record plus the ETag it was read at, for a subsequent conditional write.
92#[derive(Debug)]
93pub struct LoadedRecord {
94    pub record: MfaRecord,
95    /// `None` when the record does not exist yet.
96    etag: Option<String>,
97}
98
99impl LoadedRecord {
100    /// Whether this identity has ever had a record written.
101    pub const fn is_new(&self) -> bool {
102        self.etag.is_none()
103    }
104}
105
106/// Load the record for `access_key`, or a fresh one if none exists.
107///
108/// An absent record is not an error: it is the state every identity starts in.
109pub async fn load(api: Arc<IamStore>, access_key: &str, now: OffsetDateTime) -> Result<LoadedRecord> {
110    let path = record_path(access_key);
111
112    match read_iam_config_with_metadata(api, &path, &IamObjectOptions::default()).await {
113        Ok((data, info)) => {
114            let plain = decrypt_iam_blob(&data)?;
115            let record: MfaRecord = serde_json::from_slice(&plain).map_err(|err| {
116                // A record that cannot be parsed must not silently become "no
117                // second factor": that would turn corruption into a bypass.
118                warn!(
119                    path = %path,
120                    error = %err,
121                    "MFA record is unreadable; refusing to treat it as absent"
122                );
123                Error::other(format!("the stored MFA record for this identity is unreadable: {err}"))
124            })?;
125            record.validate_version().map_err(|err| Error::other(err.to_string()))?;
126
127            Ok(LoadedRecord { record, etag: info.etag })
128        }
129        Err(err) if is_err_config_not_found(&err.clone().into()) => Ok(LoadedRecord {
130            record: MfaRecord::new(access_key, now),
131            etag: None,
132        }),
133        Err(err) => Err(err.into()),
134    }
135}
136
137/// Read-only view of whether `access_key` has an active second factor.
138///
139/// Returns `false` for an identity with no record, and propagates a read
140/// failure rather than defaulting: the login path calls this to decide whether
141/// to demand a second factor, and a store outage must not be an automatic
142/// bypass.
143pub async fn is_enabled(api: Arc<IamStore>, access_key: &str, now: OffsetDateTime) -> Result<bool> {
144    Ok(load(api, access_key, now).await?.record.is_enabled())
145}
146
147/// Apply `mutate` to the identity's record and persist the result.
148///
149/// Retries on a lost race, re-reading so the mutation always applies to current
150/// state. `mutate` may therefore run more than once and must not have side
151/// effects of its own.
152///
153/// Generic over the closure's error so a caller can return its own typed
154/// failure — a rejected code, say — without encoding it into a string and
155/// decoding it on the way out. Storage failures arrive through `From<Error>`.
156pub async fn update<T, E, F>(
157    api: Arc<IamStore>,
158    access_key: &str,
159    now: OffsetDateTime,
160    mut mutate: F,
161) -> std::result::Result<T, E>
162where
163    F: FnMut(&mut MfaRecord) -> std::result::Result<T, E>,
164    E: From<Error>,
165{
166    let path = record_path(access_key);
167
168    for attempt in 1..=MAX_WRITE_ATTEMPTS {
169        let loaded = load(api.clone(), access_key, now).await.map_err(E::from)?;
170        let mut record = loaded.record;
171        let outcome = mutate(&mut record)?;
172
173        let plain = serde_json::to_vec(&record).map_err(|err| E::from(Error::other(err.to_string())))?;
174        let encrypted = encrypt_iam_blob(&plain).map_err(E::from)?;
175
176        let mut opts = IamObjectOptions {
177            max_parity: true,
178            ..Default::default()
179        };
180        // A new record must not overwrite one another request created between
181        // our read and our write, so an absent ETag becomes `If-None-Match: *`
182        // rather than an unconditional put.
183        opts.http_preconditions = Some(match loaded.etag {
184            Some(etag) => HTTPPreconditions {
185                if_match: Some(etag),
186                ..Default::default()
187            },
188            None => HTTPPreconditions {
189                if_none_match: Some("*".to_string()),
190                ..Default::default()
191            },
192        });
193
194        match save_iam_config_with_opts(api.clone(), &path, encrypted, &opts).await {
195            Ok(()) => return Ok(outcome),
196            Err(IamStorageError::PreconditionFailed) => {
197                warn!(
198                    path = %path,
199                    attempt,
200                    "MFA record write lost a race; retrying against current state"
201                );
202            }
203            Err(err) => return Err(E::from(err.into())),
204        }
205    }
206
207    Err(E::from(Error::other(
208        "the MFA record for this identity is being modified concurrently; retry the request",
209    )))
210}
211
212/// Remove the record entirely.
213///
214/// Used by the administrative reset, where leaving a disabled-but-present
215/// record would only preserve a stale lockout counter.
216pub async fn delete(api: Arc<IamStore>, access_key: &str) -> Result<()> {
217    let path = record_path(access_key);
218    match delete_iam_config(api, &path).await {
219        Ok(()) => Ok(()),
220        // Already absent is the desired end state.
221        Err(err) if is_err_config_not_found(&err.clone().into()) => Ok(()),
222        Err(err) => Err(err.into()),
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn record_paths_sit_beside_the_iam_tree_not_inside_it() {
232        // Inside `config/iam/` the IAM cache loader would sweep these into its
233        // startup walk; this pins them out of it.
234        let path = record_path("sinan");
235
236        assert_eq!(path, "config/mfa/sinan/totp.json");
237        assert!(!path.starts_with("config/iam/"));
238    }
239
240    #[test]
241    fn record_paths_are_scoped_per_identity() {
242        assert_ne!(record_path("sinan"), record_path("someone-else"));
243        assert!(record_path("sinan").contains("/sinan/"));
244    }
245
246    #[test]
247    fn the_unavailable_reason_names_the_variable_an_operator_must_set() {
248        // The message is the whole remediation path for a blocked enrollment.
249        assert!(ENROLLMENT_UNAVAILABLE_REASON.contains("RUSTFS_IAM_MASTER_KEY"));
250    }
251
252    #[test]
253    fn a_loaded_record_reports_whether_it_is_new() {
254        let now = OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid timestamp");
255
256        let fresh = LoadedRecord {
257            record: MfaRecord::new("sinan", now),
258            etag: None,
259        };
260        assert!(fresh.is_new());
261
262        let existing = LoadedRecord {
263            record: MfaRecord::new("sinan", now),
264            etag: Some("etag".to_string()),
265        };
266        assert!(!existing.is_new());
267    }
268}