-
Notifications
You must be signed in to change notification settings - Fork 640
/
Copy pathauth.rs
376 lines (309 loc) · 12.8 KB
/
auth.rs
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
use crate::controllers;
use crate::controllers::util::RequestPartsExt;
use crate::middleware::log_request::RequestLogExt;
use crate::models::token::{CrateScope, EndpointScope};
use crate::models::{ApiToken, User};
use crate::util::errors::{
AppResult, InsecurelyGeneratedTokenRevoked, account_locked, forbidden, internal,
};
use crate::util::token::HashedToken;
use chrono::Utc;
use crates_io_session::SessionExtension;
use diesel_async::AsyncPgConnection;
use http::header;
use http::request::Parts;
#[derive(Debug, Clone)]
pub struct AuthCheck {
allow_token: bool,
endpoint_scope: Option<EndpointScope>,
crate_name: Option<String>,
}
impl AuthCheck {
#[must_use]
// #[must_use] can't be applied in the `Default` trait impl
#[allow(clippy::should_implement_trait)]
pub fn default() -> Self {
Self {
allow_token: true,
endpoint_scope: None,
crate_name: None,
}
}
#[must_use]
pub fn only_cookie() -> Self {
Self {
allow_token: false,
endpoint_scope: None,
crate_name: None,
}
}
pub fn with_endpoint_scope(&self, endpoint_scope: EndpointScope) -> Self {
Self {
allow_token: self.allow_token,
endpoint_scope: Some(endpoint_scope),
crate_name: self.crate_name.clone(),
}
}
pub fn for_crate(&self, crate_name: &str) -> Self {
Self {
allow_token: self.allow_token,
endpoint_scope: self.endpoint_scope,
crate_name: Some(crate_name.to_string()),
}
}
#[instrument(name = "auth.check", skip_all)]
pub async fn check(
&self,
parts: &Parts,
conn: &mut AsyncPgConnection,
) -> AppResult<Authentication> {
let auth = authenticate(parts, conn).await?;
if let Some(token) = auth.api_token() {
if !self.allow_token {
let error_message =
"API Token authentication was explicitly disallowed for this API";
parts.request_log().add("cause", error_message);
return Err(forbidden(
"this action can only be performed on the crates.io website",
));
}
if !self.endpoint_scope_matches(token.endpoint_scopes.as_ref()) {
let error_message = "Endpoint scope mismatch";
parts.request_log().add("cause", error_message);
return Err(forbidden(
"this token does not have the required permissions to perform this action",
));
}
if !self.crate_scope_matches(token.crate_scopes.as_ref()) {
let error_message = "Crate scope mismatch";
parts.request_log().add("cause", error_message);
return Err(forbidden(
"this token does not have the required permissions to perform this action",
));
}
}
Ok(auth)
}
fn endpoint_scope_matches(&self, token_scopes: Option<&Vec<EndpointScope>>) -> bool {
match (&token_scopes, &self.endpoint_scope) {
// The token is a legacy token.
(None, _) => true,
// The token is NOT a legacy token, and the endpoint only allows legacy tokens.
(Some(_), None) => false,
// The token is NOT a legacy token, and the endpoint allows a certain endpoint scope or a legacy token.
(Some(token_scopes), Some(endpoint_scope)) => token_scopes.contains(endpoint_scope),
}
}
fn crate_scope_matches(&self, token_scopes: Option<&Vec<CrateScope>>) -> bool {
match (&token_scopes, &self.crate_name) {
// The token is a legacy token.
(None, _) => true,
// The token does not have any crate scopes.
(Some(token_scopes), _) if token_scopes.is_empty() => true,
// The token has crate scopes, but the endpoint does not deal with crates.
(Some(_), None) => false,
// The token is NOT a legacy token, and the endpoint allows a certain endpoint scope or a legacy token.
(Some(token_scopes), Some(crate_name)) => token_scopes
.iter()
.any(|token_scope| token_scope.matches(crate_name)),
}
}
}
#[derive(Debug)]
pub enum Authentication {
Cookie(CookieAuthentication),
Token(TokenAuthentication),
}
#[derive(Debug)]
pub struct CookieAuthentication {
user: User,
}
#[derive(Debug)]
pub struct TokenAuthentication {
token: ApiToken,
user: User,
}
impl Authentication {
pub fn user_id(&self) -> i32 {
self.user().id
}
pub fn api_token_id(&self) -> Option<i32> {
self.api_token().map(|token| token.id)
}
pub fn api_token(&self) -> Option<&ApiToken> {
match self {
Authentication::Token(token) => Some(&token.token),
_ => None,
}
}
pub fn user(&self) -> &User {
match self {
Authentication::Cookie(cookie) => &cookie.user,
Authentication::Token(token) => &token.user,
}
}
}
#[instrument(skip_all)]
async fn authenticate_via_cookie(
parts: &Parts,
conn: &mut AsyncPgConnection,
) -> AppResult<Option<CookieAuthentication>> {
let session = parts
.extensions()
.get::<SessionExtension>()
.expect("missing cookie session");
let user_id_from_session = session.get("user_id").and_then(|s| s.parse::<i32>().ok());
let Some(id) = user_id_from_session else {
return Ok(None);
};
let user = User::find(conn, id).await.map_err(|err| {
parts.request_log().add("cause", err);
internal("user_id from cookie not found in database")
})?;
ensure_not_locked(&user)?;
parts.request_log().add("uid", id);
Ok(Some(CookieAuthentication { user }))
}
#[instrument(skip_all)]
async fn authenticate_via_token(
parts: &Parts,
conn: &mut AsyncPgConnection,
) -> AppResult<Option<TokenAuthentication>> {
let maybe_authorization = parts
.headers()
.get(header::AUTHORIZATION)
.and_then(|h| h.to_str().ok());
let Some(header_value) = maybe_authorization else {
return Ok(None);
};
let token =
HashedToken::parse(header_value).map_err(|_| InsecurelyGeneratedTokenRevoked::boxed())?;
let token = ApiToken::find_by_api_token(conn, &token)
.await
.map_err(|e| {
let cause = format!("invalid token caused by {e}");
parts.request_log().add("cause", cause);
forbidden("authentication failed")
})?;
let user = User::find(conn, token.user_id).await.map_err(|err| {
parts.request_log().add("cause", err);
internal("user_id from token not found in database")
})?;
ensure_not_locked(&user)?;
parts.request_log().add("uid", token.user_id);
parts.request_log().add("tokenid", token.id);
Ok(Some(TokenAuthentication { user, token }))
}
#[instrument(skip_all)]
async fn authenticate(parts: &Parts, conn: &mut AsyncPgConnection) -> AppResult<Authentication> {
controllers::util::verify_origin(parts)?;
match authenticate_via_cookie(parts, conn).await {
Ok(None) => {}
Ok(Some(auth)) => return Ok(Authentication::Cookie(auth)),
Err(err) => return Err(err),
}
match authenticate_via_token(parts, conn).await {
Ok(None) => {}
Ok(Some(auth)) => return Ok(Authentication::Token(auth)),
Err(err) => return Err(err),
}
// Unable to authenticate the user
let cause = "no cookie session or auth header found";
parts.request_log().add("cause", cause);
return Err(forbidden("this action requires authentication"));
}
fn ensure_not_locked(user: &User) -> AppResult<()> {
if let Some(reason) = &user.account_lock_reason {
let still_locked = user
.account_lock_until
.map(|until| until > Utc::now())
.unwrap_or(true);
if still_locked {
return Err(account_locked(reason, user.account_lock_until));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn cs(scope: &str) -> CrateScope {
CrateScope::try_from(scope).unwrap()
}
#[test]
fn regular_endpoint() {
let auth_check = AuthCheck::default();
assert!(auth_check.endpoint_scope_matches(None));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishNew])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishUpdate])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::Yank])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::ChangeOwners])));
assert!(auth_check.crate_scope_matches(None));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("tokio-console")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("tokio-*")])));
}
#[test]
fn publish_new_endpoint() {
let auth_check = AuthCheck::default()
.with_endpoint_scope(EndpointScope::PublishNew)
.for_crate("tokio-console");
assert!(auth_check.endpoint_scope_matches(None));
assert!(auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishNew])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishUpdate])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::Yank])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::ChangeOwners])));
assert!(auth_check.crate_scope_matches(None));
assert!(auth_check.crate_scope_matches(Some(&vec![cs("tokio-console")])));
assert!(auth_check.crate_scope_matches(Some(&vec![cs("tokio-*")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("anyhow")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("actix-*")])));
}
#[test]
fn publish_update_endpoint() {
let auth_check = AuthCheck::default()
.with_endpoint_scope(EndpointScope::PublishUpdate)
.for_crate("tokio-console");
assert!(auth_check.endpoint_scope_matches(None));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishNew])));
assert!(auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishUpdate])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::Yank])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::ChangeOwners])));
assert!(auth_check.crate_scope_matches(None));
assert!(auth_check.crate_scope_matches(Some(&vec![cs("tokio-console")])));
assert!(auth_check.crate_scope_matches(Some(&vec![cs("tokio-*")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("anyhow")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("actix-*")])));
}
#[test]
fn yank_endpoint() {
let auth_check = AuthCheck::default()
.with_endpoint_scope(EndpointScope::Yank)
.for_crate("tokio-console");
assert!(auth_check.endpoint_scope_matches(None));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishNew])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishUpdate])));
assert!(auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::Yank])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::ChangeOwners])));
assert!(auth_check.crate_scope_matches(None));
assert!(auth_check.crate_scope_matches(Some(&vec![cs("tokio-console")])));
assert!(auth_check.crate_scope_matches(Some(&vec![cs("tokio-*")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("anyhow")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("actix-*")])));
}
#[test]
fn owner_change_endpoint() {
let auth_check = AuthCheck::default()
.with_endpoint_scope(EndpointScope::ChangeOwners)
.for_crate("tokio-console");
assert!(auth_check.endpoint_scope_matches(None));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishNew])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::PublishUpdate])));
assert!(!auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::Yank])));
assert!(auth_check.endpoint_scope_matches(Some(&vec![EndpointScope::ChangeOwners])));
assert!(auth_check.crate_scope_matches(None));
assert!(auth_check.crate_scope_matches(Some(&vec![cs("tokio-console")])));
assert!(auth_check.crate_scope_matches(Some(&vec![cs("tokio-*")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("anyhow")])));
assert!(!auth_check.crate_scope_matches(Some(&vec![cs("actix-*")])));
}
}