use serde::Deserialize;
use serde::Serialize;
use crate::error::Result;
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Credential {
OAuth {
provider: String,
access_token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
refresh_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
expires_at_unix: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
token_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
account_label: Option<String>,
},
ApiKey {
provider: String,
api_key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
account_label: Option<String>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CredentialKind {
OAuth,
ApiKey,
}
impl Credential {
pub fn oauth(
provider: impl Into<String>,
access_token: String,
refresh_token: Option<String>,
expires_at_unix: Option<i64>,
token_type: Option<String>,
) -> Self {
Self::OAuth {
provider: provider.into(),
access_token,
refresh_token,
expires_at_unix,
token_type,
account_label: None,
}
}
pub fn api_key(provider: impl Into<String>, api_key: String) -> Self {
Self::ApiKey {
provider: provider.into(),
api_key,
account_label: None,
}
}
pub fn kind(&self) -> CredentialKind {
match self {
Self::OAuth { .. } => CredentialKind::OAuth,
Self::ApiKey { .. } => CredentialKind::ApiKey,
}
}
pub fn provider(&self) -> &str {
match self {
Self::OAuth { provider, .. } | Self::ApiKey { provider, .. } => provider.as_str(),
}
}
pub fn access_token(&self) -> Option<&String> {
match self {
Self::OAuth { access_token, .. } => Some(access_token),
Self::ApiKey { .. } => None,
}
}
pub fn refresh_token(&self) -> Option<&String> {
match self {
Self::OAuth { refresh_token, .. } => refresh_token.as_ref(),
Self::ApiKey { .. } => None,
}
}
pub fn api_key_value(&self) -> Option<&String> {
match self {
Self::ApiKey { api_key, .. } => Some(api_key),
Self::OAuth { .. } => None,
}
}
pub fn expires_at_unix(&self) -> Option<i64> {
match self {
Self::OAuth {
expires_at_unix, ..
} => *expires_at_unix,
Self::ApiKey { .. } => None,
}
}
pub fn token_type(&self) -> Option<&String> {
match self {
Self::OAuth { token_type, .. } => token_type.as_ref(),
Self::ApiKey { .. } => None,
}
}
pub fn account_label(&self) -> Option<&str> {
match self {
Self::OAuth { account_label, .. } | Self::ApiKey { account_label, .. } => {
account_label.as_deref()
}
}
}
#[must_use]
pub fn with_account_label(self, label: impl Into<String>) -> Self {
let label = label.into();
let mut this = self;
match &mut this {
Self::OAuth { account_label, .. } | Self::ApiKey { account_label, .. } => {
*account_label = Some(label);
}
}
this
}
pub fn is_expired(&self, now_unix: i64) -> bool {
match self {
Self::OAuth {
expires_at_unix, ..
} => expires_at_unix.is_some_and(|exp| now_unix >= exp),
Self::ApiKey { .. } => false,
}
}
pub fn secret(&self) -> Option<&str> {
match self {
Self::OAuth { access_token, .. } => Some(access_token.as_str()),
Self::ApiKey { api_key, .. } => Some(api_key.as_str()),
}
}
}
impl std::fmt::Debug for Credential {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::OAuth {
provider,
access_token: _,
refresh_token,
expires_at_unix,
token_type,
account_label,
} => f
.debug_struct("Credential")
.field("provider", provider)
.field("kind", &CredentialKind::OAuth)
.field("access_token", &Some::<&str>("<redacted>"))
.field(
"refresh_token",
&refresh_token.as_ref().map(|_| "<redacted>"),
)
.field("api_key", &None::<&str>)
.field("expires_at_unix", expires_at_unix)
.field("token_type", token_type)
.field("account_label", account_label)
.finish(),
Self::ApiKey {
provider,
api_key: _,
account_label,
} => f
.debug_struct("Credential")
.field("provider", provider)
.field("kind", &CredentialKind::ApiKey)
.field("access_token", &None::<&str>)
.field("refresh_token", &None::<&str>)
.field("api_key", &Some::<&str>("<redacted>"))
.field("expires_at_unix", &None::<i64>)
.field("token_type", &None::<&str>)
.field("account_label", account_label)
.finish(),
}
}
}
pub trait CredentialStore: Send + Sync {
fn put(&self, credential: &Credential) -> Result<()>;
fn get(&self, provider: &str) -> Result<Option<Credential>>;
fn delete(&self, provider: &str) -> Result<()>;
fn providers(&self) -> Result<Vec<String>>;
}
#[derive(Default)]
pub struct MemoryStore {
inner: std::sync::RwLock<std::collections::BTreeMap<String, Credential>>,
}
impl Clone for MemoryStore {
fn clone(&self) -> Self {
let map = match self.inner.read() {
Ok(guard) => guard.clone(),
Err(poisoned) => poisoned.into_inner().clone(),
};
Self {
inner: std::sync::RwLock::new(map),
}
}
}
impl MemoryStore {
pub fn new() -> Self {
Self::default()
}
}
impl CredentialStore for MemoryStore {
fn put(&self, credential: &Credential) -> Result<()> {
self.inner
.write()
.map_err(|_| crate::error::Error::Store("memory store lock poisoned".into()))?
.insert(credential.provider().to_string(), credential.clone());
Ok(())
}
fn get(&self, provider: &str) -> Result<Option<Credential>> {
Ok(self
.inner
.read()
.map_err(|_| crate::error::Error::Store("memory store lock poisoned".into()))?
.get(provider)
.cloned())
}
fn delete(&self, provider: &str) -> Result<()> {
self.inner
.write()
.map_err(|_| crate::error::Error::Store("memory store lock poisoned".into()))?
.remove(provider);
Ok(())
}
fn providers(&self) -> Result<Vec<String>> {
Ok(self
.inner
.read()
.map_err(|_| crate::error::Error::Store("memory store lock poisoned".into()))?
.keys()
.cloned()
.collect())
}
}