1use crate::{Error, Result, error::invalid};
2use std::{
3 fmt,
4 future::Future,
5 pin::Pin,
6 sync::Arc,
7 time::{Duration, Instant},
8};
9use tokio::sync::Mutex;
10
11pub type TokenFuture<'a> = Pin<Box<dyn Future<Output = Result<String>> + Send + 'a>>;
12
13pub trait TokenProvider: Send + Sync {
15 fn token(&self) -> TokenFuture<'_>;
16 fn invalidate<'a>(
17 &'a self,
18 _rejected: &'a str,
19 ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
20 Box::pin(async {})
21 }
22}
23
24#[derive(Clone)]
25pub enum Credentials {
26 Missing,
28 Anonymous,
30 #[doc(hidden)]
31 Bearer(String),
32 #[doc(hidden)]
33 AccessKey {
34 id: String,
35 secret: String,
36 },
37 Provider(Arc<dyn TokenProvider>),
38}
39impl fmt::Debug for Credentials {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.write_str(match self {
42 Self::Missing => "Missing",
43 Self::Anonymous => "Anonymous",
44 _ => "Credentials([REDACTED])",
45 })
46 }
47}
48impl Credentials {
49 pub fn bearer(token: impl Into<String>) -> Result<Self> {
50 let token = token.into();
51 validate_token(&token)?;
52 Ok(Self::Bearer(token))
53 }
54 pub fn access_key(id: impl Into<String>, secret: impl Into<String>) -> Result<Self> {
55 let (id, secret) = (id.into(), secret.into());
56 if id.is_empty() || id.contains(':') || secret.is_empty() {
57 return Err(invalid("A valid access key ID and secret are required"));
58 }
59 Ok(Self::AccessKey { id, secret })
60 }
61}
62pub(crate) fn validate_token(value: &str) -> Result<()> {
63 if value.is_empty() || !value.bytes().all(|b| b.is_ascii_graphic()) {
64 return Err(invalid(
65 "Bearer tokens must be nonempty ASCII without whitespace",
66 ));
67 }
68 Ok(())
69}
70
71pub(crate) struct Auth {
72 credentials: Credentials,
73 cache: Mutex<Option<(String, Instant)>>,
74}
75impl Auth {
76 pub fn new(credentials: Credentials) -> Result<Self> {
77 match &credentials {
78 Credentials::Bearer(t) => validate_token(t)?,
79 Credentials::AccessKey { id, secret }
80 if id.is_empty() || id.contains(':') || secret.is_empty() =>
81 {
82 return Err(invalid("A valid access key pair is required"));
83 }
84 _ => (),
85 }
86 Ok(Self {
87 credentials,
88 cache: Mutex::new(None),
89 })
90 }
91 pub async fn token(
92 &self,
93 client: &reqwest::Client,
94 url: &str,
95 timeout: Duration,
96 ) -> Result<String> {
97 match &self.credentials {
98 Credentials::Missing | Credentials::Anonymous => Err(invalid(
99 "Anonymous access cannot call an authenticated operation",
100 )),
101 Credentials::Bearer(t) => Ok(t.clone()),
102 Credentials::Provider(provider) => {
103 let token = provider.token().await?;
104 validate_token(&token)?;
105 Ok(token)
106 }
107 Credentials::AccessKey { id, secret } => {
108 let mut cache = self.cache.lock().await;
111 if let Some((token, until)) = &*cache
112 && Instant::now() < *until
113 {
114 return Ok(token.clone());
115 }
116 let started = Instant::now();
117 let mut response = client
118 .post(url)
119 .basic_auth(id, Some(secret))
120 .header("accept", "application/json")
121 .form(&[("grant_type", "client_credentials")])
122 .timeout(timeout)
123 .send()
124 .await
125 .map_err(|_| Error::Authentication { status: None })?;
126 let status = response.status().as_u16();
127 let fail = || Error::Authentication {
128 status: Some(status),
129 };
130 if status != 200 {
131 return Err(fail());
132 }
133 let mut raw = Vec::new();
134 while let Some(chunk) = response.chunk().await.map_err(|_| fail())? {
135 if raw.len() + chunk.len() > 1_048_576 {
136 return Err(fail());
137 }
138 raw.extend_from_slice(&chunk);
139 }
140 let data: serde_json::Value = serde_json::from_slice(&raw).map_err(|_| fail())?;
141 let token = data
142 .get("access_token")
143 .and_then(|v| v.as_str())
144 .ok_or_else(fail)?;
145 validate_token(token).map_err(|_| fail())?;
146 if !data
147 .get("token_type")
148 .and_then(|v| v.as_str())
149 .unwrap_or("Bearer")
150 .eq_ignore_ascii_case("bearer")
151 {
152 return Err(fail());
153 }
154 let seconds = data
155 .get("expires_in")
156 .map(|v| v.as_f64())
157 .unwrap_or(Some(900.0))
158 .ok_or_else(fail)?;
159 if !seconds.is_finite() || seconds <= 0.0 {
160 return Err(fail());
161 }
162 let ttl = Duration::try_from_secs_f64(seconds - (seconds * 0.1).min(300.0))
163 .map_err(|_| fail())?;
164 let until = started.checked_add(ttl).ok_or_else(fail)?;
165 *cache = Some((token.to_owned(), until));
166 Ok(token.to_owned())
167 }
168 }
169 }
170 pub fn refreshable(&self) -> bool {
171 matches!(
172 self.credentials,
173 Credentials::AccessKey { .. } | Credentials::Provider(_)
174 )
175 }
176 pub async fn invalidate(&self, rejected: &str) {
177 match &self.credentials {
178 Credentials::Provider(p) => p.invalidate(rejected).await,
179 Credentials::AccessKey { .. } => {
180 let mut cache = self.cache.lock().await;
181 if cache.as_ref().is_some_and(|(token, _)| token == rejected) {
182 *cache = None;
183 }
184 }
185 _ => (),
186 }
187 }
188}