isothrum_machine/cloud/
token.rs1use std::time::Duration;
6
7use isothrum_runner::tls::{Tls, Trust};
8
9use crate::place::proxmox::chain;
10
11pub const TOKEN_TIMEOUT: Duration = Duration::from_secs(15);
13
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
16#[non_exhaustive]
17pub enum TokenError {
18 #[error("the provider rejected the token")]
20 Rejected,
21 #[error("the provider's API answered HTTP {0}")]
23 Status(u16),
24 #[error("can't reach the provider: {0}")]
26 Unreachable(String),
27}
28
29pub mod digitalocean {
31 use super::{TokenError, Trust, account};
32
33 pub const ACCOUNT_URL: &str = "https://api.digitalocean.com/v2/account";
35
36 pub async fn check_token(token: &str) -> Result<(), TokenError> {
42 account(ACCOUNT_URL, token, Trust::System).await
43 }
44}
45
46pub mod linode {
48 use super::{TokenError, Trust, account};
49
50 pub const ACCOUNT_URL: &str = "https://api.linode.com/v4/account";
52
53 pub async fn check_token(token: &str) -> Result<(), TokenError> {
59 account(ACCOUNT_URL, token, Trust::System).await
60 }
61}
62
63async fn account(url: &str, token: &str, trust: Trust) -> Result<(), TokenError> {
66 let tls = Tls::new(trust).map_err(|e| TokenError::Unreachable(e.to_string()))?;
67 let http = reqwest::Client::builder()
68 .tls_backend_preconfigured(tls.config().clone())
69 .connect_timeout(TOKEN_TIMEOUT)
70 .timeout(TOKEN_TIMEOUT)
71 .build()
72 .map_err(|e| TokenError::Unreachable(chain(&e)))?;
73 let answer = http.get(url).bearer_auth(token).send().await.map_err(|e| TokenError::Unreachable(chain(&e)))?;
74 match answer.status().as_u16() {
75 200..=299 => Ok(()),
76 401 => Err(TokenError::Rejected),
77 other => Err(TokenError::Status(other)),
78 }
79}
80
81#[cfg(test)]
82mod tests;