use std::str::FromStr;
use serde::{Deserialize, Serialize};
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub enum Authentication {
BearerToken(String),
BasicHTTP {
username: String,
password: String,
},
CondaToken(String),
S3Credentials {
access_key_id: String,
secret_access_key: String,
session_token: Option<String>,
},
OAuth {
#[serde(default, skip_serializing_if = "Option::is_none")]
audience: Option<String>,
access_token: String,
refresh_token: Option<String>,
expires_at: Option<i64>,
token_endpoint: String,
revocation_endpoint: Option<String>,
client_id: String,
},
}
#[derive(Debug)]
pub enum AuthenticationParseError {
InvalidScheme,
InvalidToken,
}
impl FromStr for Authentication {
type Err = AuthenticationParseError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
serde_json::from_str(s).map_err(|_err| AuthenticationParseError::InvalidToken)
}
}
impl Authentication {
pub fn method(&self) -> &str {
match self {
Authentication::BearerToken(_) => "BearerToken",
Authentication::BasicHTTP { .. } => "BasicHTTP",
Authentication::CondaToken(_) => "CondaToken",
Authentication::S3Credentials { .. } => "S3",
Authentication::OAuth { .. } => "OAuth",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_oauth_json_round_trips_without_audience() {
let old = serde_json::json!({"OAuth": {
"access_token": "fixture", "refresh_token": null, "expires_at": null,
"token_endpoint": "https://issuer.example/token", "revocation_endpoint": null,
"client_id": "rattler"
}});
let auth: Authentication = serde_json::from_value(old.clone()).unwrap();
assert!(matches!(
&auth,
Authentication::OAuth { audience: None, .. }
));
assert_eq!(serde_json::to_value(auth).unwrap(), old);
}
}