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
use std::future::Future;
use std::time::Duration;
use derivative::Derivative;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use thiserror::Error;
use uuid::Uuid;
use mz_ore::now::NowFn;
pub struct FronteggConfig {
pub admin_api_token_url: String,
pub decoding_key: DecodingKey,
pub tenant_id: Uuid,
pub now: NowFn,
pub refresh_before_secs: i64,
pub password_prefix: String,
}
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct FronteggAuthentication {
admin_api_token_url: String,
#[derivative(Debug = "ignore")]
decoding_key: DecodingKey,
tenant_id: Uuid,
now: NowFn,
validation: Validation,
refresh_before_secs: i64,
password_prefix: String,
}
pub const REFRESH_SUFFIX: &str = "/token/refresh";
impl FronteggAuthentication {
pub fn new(config: FronteggConfig) -> Self {
let mut validation = Validation::new(Algorithm::RS256);
validation.validate_exp = false;
Self {
admin_api_token_url: config.admin_api_token_url,
decoding_key: config.decoding_key,
tenant_id: config.tenant_id,
now: config.now,
validation,
refresh_before_secs: config.refresh_before_secs,
password_prefix: config.password_prefix,
}
}
pub async fn exchange_password_for_token(
&self,
password: &str,
) -> Result<ApiTokenResponse, FronteggError> {
let password = password
.strip_prefix(&self.password_prefix)
.ok_or(FronteggError::InvalidPasswordFormat)?;
let (client_id, secret) = if password.len() == 43 || password.len() == 44 {
let buf = base64::decode_config(password, base64::URL_SAFE)
.map_err(|_| FronteggError::InvalidPasswordFormat)?;
let client_id =
Uuid::from_slice(&buf[..16]).map_err(|_| FronteggError::InvalidPasswordFormat)?;
let secret =
Uuid::from_slice(&buf[16..]).map_err(|_| FronteggError::InvalidPasswordFormat)?;
(client_id, secret)
} else if password.len() >= 64 {
let mut chars = password.chars().filter(|c| c.is_alphanumeric());
let client_id = Uuid::parse_str(&chars.by_ref().take(32).collect::<String>())
.map_err(|_| FronteggError::InvalidPasswordFormat)?;
let secret = Uuid::parse_str(&chars.take(32).collect::<String>())
.map_err(|_| FronteggError::InvalidPasswordFormat)?;
(client_id, secret)
} else {
return Err(FronteggError::InvalidPasswordFormat);
};
self.exchange_client_secret_for_token(client_id, secret)
.await
}
pub async fn exchange_client_secret_for_token(
&self,
client_id: Uuid,
secret: Uuid,
) -> Result<ApiTokenResponse, FronteggError> {
let resp = reqwest::Client::new()
.post(&self.admin_api_token_url)
.json(&ApiTokenArgs { client_id, secret })
.send()
.await?
.error_for_status()?
.json::<ApiTokenResponse>()
.await?;
Ok(resp)
}
pub fn validate_access_token(
&self,
token: &str,
expected_email: Option<&str>,
) -> Result<Claims, FronteggError> {
let msg = decode::<Claims>(&token, &self.decoding_key, &self.validation)?;
if msg.claims.exp < self.now.as_secs() {
return Err(FronteggError::TokenExpired);
}
if msg.claims.tenant_id != self.tenant_id {
return Err(FronteggError::UnauthorizedTenant);
}
if let Some(expected_email) = expected_email {
if msg.claims.email != expected_email {
return Err(FronteggError::WrongEmail);
}
}
Ok(msg.claims)
}
pub fn check_expiry(
&self,
mut token: ApiTokenResponse,
expected_email: String,
) -> Result<impl Future<Output = ()>, FronteggError> {
let mut claims = self.validate_access_token(&token.access_token, Some(&expected_email))?;
let frontegg = self.clone();
Ok(async move {
let refresh_url = format!("{}{}", frontegg.admin_api_token_url, REFRESH_SUFFIX);
loop {
let expire_in = claims.exp - frontegg.now.as_secs();
let check_in = std::cmp::max(0, expire_in - frontegg.refresh_before_secs) as u64;
tokio::time::sleep(Duration::from_secs(check_in)).await;
let refresh_request = async {
let refresh = RefreshToken {
refresh_token: token.refresh_token,
};
loop {
let resp = async {
let token = reqwest::Client::new()
.post(&refresh_url)
.json(&refresh)
.send()
.await?
.error_for_status()?
.json::<ApiTokenResponse>()
.await?;
let claims = frontegg.validate_access_token(
&token.access_token,
Some(&expected_email),
)?;
Ok::<(ApiTokenResponse, Claims), anyhow::Error>((token, claims))
};
match resp.await {
Ok((token, claims)) => {
return (token, claims);
}
Err(_) => {
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
};
let expire_in = std::cmp::max(0, claims.exp - frontegg.now.as_secs()) as u64;
let expire_in = tokio::time::sleep(Duration::from_secs(expire_in));
tokio::select! {
_ = expire_in => return (),
(refresh_token, refresh_claims) = refresh_request => {
token = refresh_token;
claims = refresh_claims;
},
};
}
})
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiTokenArgs {
pub client_id: Uuid,
pub secret: Uuid,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefreshToken {
pub refresh_token: String,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiTokenResponse {
pub expires: String,
pub expires_in: i64,
pub access_token: String,
pub refresh_token: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Claims {
pub exp: i64,
pub email: String,
pub tenant_id: Uuid,
pub roles: Vec<String>,
pub permissions: Vec<String>,
}
#[derive(Error, Debug)]
pub enum FronteggError {
#[error("invalid password format")]
InvalidPasswordFormat,
#[error("invalid token format: {0}")]
InvalidTokenFormat(#[from] jsonwebtoken::errors::Error),
#[error("authentication token exchange failed: {0}")]
TokenExchangeError(#[from] reqwest::Error),
#[error("authentication token expired")]
TokenExpired,
#[error("unauthorized organization")]
UnauthorizedTenant,
#[error("email in access token did not match the expected email")]
WrongEmail,
}