use crate::errors::{AuthError, Result};
use crate::security::timing_protection::constant_time_string_compare;
use crate::storage::AuthStorage;
use serde_json::Value;
pub(crate) const HASH_FIELD: &str = "client_secret_hash";
const LEGACY_FIELD: &str = "client_secret";
fn non_empty<'a>(record: &'a Value, field: &str) -> Option<&'a str> {
record
.get(field)
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
}
pub(crate) fn is_confidential(record: &Value) -> bool {
non_empty(record, HASH_FIELD).is_some() || non_empty(record, LEGACY_FIELD).is_some()
}
pub(crate) async fn hash_secret(secret: &str) -> Result<String> {
let secret = secret.to_string();
tokio::task::spawn_blocking(move || crate::utils::password::hash_password_argon2id(&secret))
.await
.map_err(|e| AuthError::internal(format!("Client secret hashing failed: {e}")))?
}
pub(crate) async fn authenticate(
storage: &dyn AuthStorage,
client_id: &str,
record: &Value,
presented: &str,
) -> bool {
if let Some(hash) = non_empty(record, HASH_FIELD) {
let hash = hash.to_string();
let presented = presented.to_string();
return tokio::task::spawn_blocking(move || {
crate::utils::password::verify_password_argon2id(&presented, &hash)
})
.await
.ok()
.and_then(|checked| checked.ok())
.unwrap_or(false);
}
let Some(stored) = non_empty(record, LEGACY_FIELD) else {
return false;
};
if !constant_time_string_compare(presented, stored) {
return false;
}
if let Err(e) = upgrade(storage, client_id, record, stored).await {
tracing::warn!("Could not hash the stored secret of client {client_id}: {e}");
}
true
}
async fn upgrade(
storage: &dyn AuthStorage,
client_id: &str,
record: &Value,
secret: &str,
) -> Result<()> {
let hash = hash_secret(secret).await?;
let mut upgraded = record.clone();
let Some(fields) = upgraded.as_object_mut() else {
return Ok(());
};
fields.remove(LEGACY_FIELD);
fields.insert(HASH_FIELD.to_string(), Value::String(hash));
let key = format!("oauth2_client:{client_id}");
let ttl = storage.get_kv_ttl(&key).await.ok().flatten();
storage
.store_kv(&key, upgraded.to_string().as_bytes(), ttl)
.await
}