use super::record::MfaRecord;
use crate::error::{Error, Result, is_err_config_not_found};
use crate::storage_api::object_store::HTTPPreconditions;
use crate::store::object::{decrypt_iam_blob, encrypt_iam_blob};
use crate::{
IAM_CONFIG_ROOT_PREFIX, IamStorageError, IamStore, delete_iam_config, keyring, read_iam_config_with_metadata,
save_iam_config_with_opts,
};
use std::sync::Arc;
use time::OffsetDateTime;
use tracing::warn;
type IamObjectOptions = <IamStore as crate::storage_api::object_store::ObjectOperations>::ObjectOptions;
const MAX_WRITE_ATTEMPTS: usize = 5;
fn record_path(access_key: &str) -> String {
format!("{IAM_CONFIG_ROOT_PREFIX}/mfa/{access_key}/totp.json")
}
pub fn at_rest_protection_available() -> bool {
keyring::encrypt_key().is_some()
}
pub const ENROLLMENT_UNAVAILABLE_REASON: &str =
"two-factor authentication requires RUSTFS_IAM_MASTER_KEY to be configured so the shared secret can be encrypted at rest";
#[derive(Debug)]
pub struct LoadedRecord {
pub record: MfaRecord,
etag: Option<String>,
}
impl LoadedRecord {
pub const fn is_new(&self) -> bool {
self.etag.is_none()
}
}
pub async fn load(api: Arc<IamStore>, access_key: &str, now: OffsetDateTime) -> Result<LoadedRecord> {
let path = record_path(access_key);
match read_iam_config_with_metadata(api, &path, &IamObjectOptions::default()).await {
Ok((data, info)) => {
let plain = decrypt_iam_blob(&data)?;
let record: MfaRecord = serde_json::from_slice(&plain).map_err(|err| {
warn!(
path = %path,
error = %err,
"MFA record is unreadable; refusing to treat it as absent"
);
Error::other(format!("the stored MFA record for this identity is unreadable: {err}"))
})?;
record.validate_version().map_err(|err| Error::other(err.to_string()))?;
Ok(LoadedRecord { record, etag: info.etag })
}
Err(err) if is_err_config_not_found(&err.clone().into()) => Ok(LoadedRecord {
record: MfaRecord::new(access_key, now),
etag: None,
}),
Err(err) => Err(err.into()),
}
}
pub async fn is_enabled(api: Arc<IamStore>, access_key: &str, now: OffsetDateTime) -> Result<bool> {
Ok(load(api, access_key, now).await?.record.is_enabled())
}
pub async fn update<T, E, F>(
api: Arc<IamStore>,
access_key: &str,
now: OffsetDateTime,
mut mutate: F,
) -> std::result::Result<T, E>
where
F: FnMut(&mut MfaRecord) -> std::result::Result<T, E>,
E: From<Error>,
{
let path = record_path(access_key);
for attempt in 1..=MAX_WRITE_ATTEMPTS {
let loaded = load(api.clone(), access_key, now).await.map_err(E::from)?;
let mut record = loaded.record;
let outcome = mutate(&mut record)?;
let plain = serde_json::to_vec(&record).map_err(|err| E::from(Error::other(err.to_string())))?;
let encrypted = encrypt_iam_blob(&plain).map_err(E::from)?;
let mut opts = IamObjectOptions {
max_parity: true,
..Default::default()
};
opts.http_preconditions = Some(match loaded.etag {
Some(etag) => HTTPPreconditions {
if_match: Some(etag),
..Default::default()
},
None => HTTPPreconditions {
if_none_match: Some("*".to_string()),
..Default::default()
},
});
match save_iam_config_with_opts(api.clone(), &path, encrypted, &opts).await {
Ok(()) => return Ok(outcome),
Err(IamStorageError::PreconditionFailed) => {
warn!(
path = %path,
attempt,
"MFA record write lost a race; retrying against current state"
);
}
Err(err) => return Err(E::from(err.into())),
}
}
Err(E::from(Error::other(
"the MFA record for this identity is being modified concurrently; retry the request",
)))
}
pub async fn delete(api: Arc<IamStore>, access_key: &str) -> Result<()> {
let path = record_path(access_key);
match delete_iam_config(api, &path).await {
Ok(()) => Ok(()),
Err(err) if is_err_config_not_found(&err.clone().into()) => Ok(()),
Err(err) => Err(err.into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn record_paths_sit_beside_the_iam_tree_not_inside_it() {
let path = record_path("sinan");
assert_eq!(path, "config/mfa/sinan/totp.json");
assert!(!path.starts_with("config/iam/"));
}
#[test]
fn record_paths_are_scoped_per_identity() {
assert_ne!(record_path("sinan"), record_path("someone-else"));
assert!(record_path("sinan").contains("/sinan/"));
}
#[test]
fn the_unavailable_reason_names_the_variable_an_operator_must_set() {
assert!(ENROLLMENT_UNAVAILABLE_REASON.contains("RUSTFS_IAM_MASTER_KEY"));
}
#[test]
fn a_loaded_record_reports_whether_it_is_new() {
let now = OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid timestamp");
let fresh = LoadedRecord {
record: MfaRecord::new("sinan", now),
etag: None,
};
assert!(fresh.is_new());
let existing = LoadedRecord {
record: MfaRecord::new("sinan", now),
etag: Some("etag".to_string()),
};
assert!(!existing.is_new());
}
}