use std::time::Duration;
use isothrum_runner::tls::{Tls, Trust};
use crate::place::proxmox::chain;
pub const TOKEN_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TokenError {
#[error("the provider rejected the token")]
Rejected,
#[error("the provider's API answered HTTP {0}")]
Status(u16),
#[error("can't reach the provider: {0}")]
Unreachable(String),
}
pub mod digitalocean {
use super::{TokenError, Trust, account};
pub const ACCOUNT_URL: &str = "https://api.digitalocean.com/v2/account";
pub async fn check_token(token: &str) -> Result<(), TokenError> {
account(ACCOUNT_URL, token, Trust::System).await
}
}
pub mod linode {
use super::{TokenError, Trust, account};
pub const ACCOUNT_URL: &str = "https://api.linode.com/v4/account";
pub async fn check_token(token: &str) -> Result<(), TokenError> {
account(ACCOUNT_URL, token, Trust::System).await
}
}
async fn account(url: &str, token: &str, trust: Trust) -> Result<(), TokenError> {
let tls = Tls::new(trust).map_err(|e| TokenError::Unreachable(e.to_string()))?;
let http = reqwest::Client::builder()
.tls_backend_preconfigured(tls.config().clone())
.connect_timeout(TOKEN_TIMEOUT)
.timeout(TOKEN_TIMEOUT)
.build()
.map_err(|e| TokenError::Unreachable(chain(&e)))?;
let answer = http.get(url).bearer_auth(token).send().await.map_err(|e| TokenError::Unreachable(chain(&e)))?;
match answer.status().as_u16() {
200..=299 => Ok(()),
401 => Err(TokenError::Rejected),
other => Err(TokenError::Status(other)),
}
}
#[cfg(test)]
mod tests;