1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use crate::dto::utils::MaybeStringU64;
use async_trait::async_trait;
use futures_locks::RwLock;
use reqwest::{
header::{HeaderMap, HeaderValue},
StatusCode,
};
use reqwest_middleware::ClientWithMiddleware;
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
use std::{fmt::Display, sync::Arc};
use thiserror::Error;
/// Type of closure for a synchronous auth callback.
type CustomAuthCallback =
dyn Fn(&mut HeaderMap, &ClientWithMiddleware) -> Result<(), AuthenticatorError> + Send + Sync;
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
/// Trait for a custom authenticator. This should set the necessary headers in `headers` before each
/// request. Note that this may be called from multiple places in parallel.
pub trait CustomAuthenticator {
/// Set the required headers for authentication. This may use the provided
/// `client` to perform a request, if necessary. This will be called frequently, so
/// make sure it only makes external requests when needed.
///
/// # Arguments
///
/// * `headers` - Header map to modify.
/// * `client` - Client used to perform any external authentication requests.
async fn set_headers(
&self,
headers: &mut HeaderMap,
client: &ClientWithMiddleware,
) -> Result<(), AuthenticatorError>;
}
/// Enumeration of the possible authentication methods available.
#[derive(Clone)]
pub enum AuthHeaderManager {
/// Authenticator that makes OIDC requests to obtain tokens.
OIDCToken(Arc<Authenticator>),
/// A fixed OIDC token
FixedToken(String),
/// An internal auth ticket.
AuthTicket(String),
/// A synchronous authentication method.
Custom(Arc<CustomAuthCallback>),
/// An async authentication method.
CustomAsync(Arc<dyn CustomAuthenticator + Send + Sync>),
}
impl AuthHeaderManager {
/// Set necessary headers in `headers`. This will sometimes request tokens from
/// the identity provider.
///
/// # Arguments
///
/// * `headers` - Request header collection.
/// * `client` - Reqwest client used to send authentication requests, if necessary.
pub async fn set_headers(
&self,
headers: &mut HeaderMap,
client: &ClientWithMiddleware,
) -> Result<(), AuthenticatorError> {
match self {
AuthHeaderManager::OIDCToken(a) => {
let token = a.get_token(client).await?;
let auth_header_value =
HeaderValue::from_str(&format!("Bearer {token}")).map_err(|e| {
AuthenticatorError::internal_error(
"Failed to set authorization bearer token".to_string(),
Some(e.to_string()),
)
})?;
headers.insert("Authorization", auth_header_value);
}
AuthHeaderManager::FixedToken(token) => {
let auth_header_value =
HeaderValue::from_str(&format!("Bearer {token}")).map_err(|e| {
AuthenticatorError::internal_error(
"Failed to set authorization bearer token".to_string(),
Some(e.to_string()),
)
})?;
headers.insert("Authorization", auth_header_value);
}
AuthHeaderManager::AuthTicket(t) => {
let auth_ticket_header_value = HeaderValue::from_str(t).map_err(|e| {
AuthenticatorError::internal_error(
"Failed to set auth ticket".to_string(),
Some(e.to_string()),
)
})?;
headers.insert("auth-ticket", auth_ticket_header_value);
}
AuthHeaderManager::Custom(c) => c(headers, client)?,
AuthHeaderManager::CustomAsync(c) => c.set_headers(headers, client).await?,
}
Ok(())
}
}
/// Configuration for authentication using the OIDC authenticator
pub struct AuthenticatorConfig {
/// Service principal client ID.
pub client_id: String,
/// IdP token URL.
pub token_url: String,
/// Service principal client secret.
pub secret: String,
/// Optional resource.
pub resource: Option<String>,
/// Optional audience.
pub audience: Option<String>,
/// Optional space separate list of scopes.
pub scopes: Option<String>,
/// Optional default token expiry time, in seconds.
/// If this is set, the authenticator will fall back on this if
/// the identity provider returns a token response without `expires_in`.
/// If this is not set, and `expires_in` is missing, the authenticator will return an error.
pub default_expires_in: Option<u64>,
}
#[derive(Serialize, Deserialize, Debug)]
struct AuthenticatorRequest {
client_id: String,
client_secret: String,
resource: Option<String>,
audience: Option<String>,
scope: Option<String>,
grant_type: String,
}
impl AuthenticatorRequest {
fn new(config: AuthenticatorConfig) -> AuthenticatorRequest {
AuthenticatorRequest {
client_id: config.client_id,
client_secret: config.secret,
grant_type: "client_credentials".to_string(),
resource: config.resource,
audience: config.audience,
scope: config.scopes,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
struct AuthenticatorResponse {
access_token: String,
expires_in: Option<MaybeStringU64>,
}
#[derive(Serialize, Deserialize, Debug, Error)]
/// Error from an authenticator request.
pub struct AuthenticatorError {
/// Error message
pub error: String,
/// Detailed error description.
pub error_description: Option<String>,
/// Error URI.
pub error_uri: Option<String>,
}
impl AuthenticatorError {
/// Create an authenticator error from message and description.
///
/// # Arguments
///
/// * `error` - Short error message
/// * `error_description` - Detailed error description.
pub fn internal_error(error: String, error_description: Option<String>) -> Self {
Self {
error,
error_description,
error_uri: None,
}
}
}
impl Display for AuthenticatorError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.error,)?;
if let Some(error_description) = &self.error_description {
write!(f, ": {error_description}")?;
}
if let Some(error_uri) = &self.error_uri {
write!(f, " ({error_uri})")?;
}
Ok(())
}
}
struct AuthenticatorState {
last_token: Option<String>,
current_token_expiry: Instant,
}
/// Result from getting a token, including expiry time.
pub struct AuthenticatorResult {
/// The token string.
token: String,
/// The time when the token will expire.
expiry: Instant,
}
/// Simple OIDC authenticator.
pub struct Authenticator {
req: AuthenticatorRequest,
state: RwLock<AuthenticatorState>,
token_url: String,
default_expires_in: Option<Duration>,
}
impl AuthenticatorResult {
/// Get the token string.
pub fn token(&self) -> &str {
&self.token
}
/// Consume self and get the token string.
pub fn into_token(self) -> String {
self.token
}
/// Get the expiry time.
pub fn expiry(&self) -> Instant {
self.expiry
}
}
impl Authenticator {
/// Create a new authenticator with given config.
///
/// # Arguments
///
/// * `config` - Authenticator configuration.
pub fn new(config: AuthenticatorConfig) -> Authenticator {
Authenticator {
token_url: config.token_url.clone(),
default_expires_in: config.default_expires_in.map(Duration::from_secs),
req: AuthenticatorRequest::new(config),
state: RwLock::new(AuthenticatorState {
last_token: None,
current_token_expiry: Instant::now(),
}),
}
}
async fn request_token(
&self,
client: &ClientWithMiddleware,
) -> Result<AuthenticatorResult, AuthenticatorError> {
let response = client
.post(&self.token_url)
.form(&self.req)
.send()
.await
.map_err(|e| {
AuthenticatorError::internal_error(
"Something went wrong when sending the request".to_string(),
Some(e.to_string()),
)
})?;
let status = response.status();
let start = Instant::now();
let response = response.text().await.map_err(|e| {
AuthenticatorError::internal_error(
"Failed to receive response contents".to_owned(),
Some(e.to_string()),
)
})?;
if status != StatusCode::OK {
return match serde_json::from_str(&response) {
Ok(e) => Err(e),
Err(e) => Err(AuthenticatorError::internal_error(
format!("Something went wrong (status: {status}), but the response error couldn't be deserialized. Raw response: {response}")
, Some(e.to_string())))
};
}
let response: AuthenticatorResponse = serde_json::from_str(&response).map_err(|e| {
AuthenticatorError::internal_error(
"Failed to deserialize response from OAuth endpoint".to_string(),
Some(e.to_string()),
)
})?;
let token = response.access_token;
let Some(expires_in) = response
.expires_in
// Subtract 60 as a buffer. We do retry on 401s, but it's best to renew the
// token before it expires. If for whatever reason expires_in is less than 60,
// we will just always renew before sending a request. We won't (hopefully)
// get an infinite loop.
.map(|m| Duration::from_secs(m.0.saturating_sub(60)))
.or(self.default_expires_in)
else {
return Err(AuthenticatorError::internal_error(
"Missing expires_in in response, and no default expiration configured".to_owned(),
None,
));
};
Ok(AuthenticatorResult {
token,
expiry: start + expires_in,
})
}
/// Get a token. This will only fetch a new token if it is about
/// to expire (will expire in the next 60 seconds). This also
/// returns when the next token will be requested. This is the time
/// when the authenticator will refresh the token, so the actual
/// expiry time minus 60 seconds.
///
/// # Arguments
///
/// * `client` - Reqwest client to use for requests to the IdP.
pub async fn get_token_with_expiry(
&self,
client: &ClientWithMiddleware,
) -> Result<AuthenticatorResult, AuthenticatorError> {
let now = Instant::now();
{
let state = &*self.state.read().await;
if let Some(last) = &state.last_token {
if state.current_token_expiry > now {
return Ok(AuthenticatorResult {
token: last.clone(),
expiry: state.current_token_expiry,
});
}
}
}
// If the token is expired, release the read lock and try to acquire a write lock.
let mut write = self.state.write().await;
// Need to check here too, in case we were blocked in this write lock by another thread
// fetching the token.
if let Some(last) = &write.last_token {
if write.current_token_expiry > now {
return Ok(AuthenticatorResult {
token: last.clone(),
expiry: write.current_token_expiry,
});
}
}
match self.request_token(client).await {
Ok(response) => {
write.current_token_expiry = response.expiry;
write.last_token = Some(response.token.clone());
Ok(response)
}
Err(e) => Err(e),
}
}
/// Get a token. This will only fetch a new token if it is about
/// to expire (will expire in the next 60 seconds).
///
/// # Arguments
///
/// * `client` - Reqwest client to use for requests to the IdP.
pub async fn get_token(
&self,
client: &ClientWithMiddleware,
) -> Result<String, AuthenticatorError> {
Ok(self.get_token_with_expiry(client).await?.token)
}
}