forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB0a2c24cTahinli1 month ago179 commits

git_auth.rs148 lines, 5.1 KiBHistoryRawDownload
1//! Basic-auth parsing and personal-access-token resolution for git over smart HTTP.
2//! Only personal access tokens are accepted as the Basic password; account passwords are never
3//! accepted over git HTTP. Tokens are never logged.
4
5use base64::prelude::{BASE64_STANDARD, Engine};
6use forge_core::{User, token::hash_token};
7use http::{HeaderMap, header::AUTHORIZATION};
8
9use crate::access::AccessError;
10use crate::state::AppState;
11
12/// Usernames that stand in for "no particular user" when a token is the password.
13const TOKEN_ONLY_USERNAMES: [&str; 2] = ["x-access-token", "oauth2"];
14
15/// Parses `Authorization: Basic <base64(user:password)>` into (username, password).
16/// The scheme is matched case-insensitively. Anything else returns `None`.
17pub fn parse_basic_auth(headers: &HeaderMap) -> Option<(String, String)> {
18 let value = headers.get(AUTHORIZATION)?.to_str().ok()?;
19 let (scheme, encoded) = value.split_once(' ')?;
20 if !scheme.eq_ignore_ascii_case("basic") || encoded.is_empty() {
21 return None;
22 }
23 let decoded = BASE64_STANDARD.decode(encoded).ok()?;
24 let text = String::from_utf8(decoded).ok()?;
25 let (username, password) = text.split_once(':')?;
26 Some((username.to_owned(), password.to_owned()))
27}
28
29/// Resolves the actor from a personal access token sent as the Basic password.
30///
31/// - No `Authorization` header: `Ok(None)` (anonymous).
32/// - A header that is not usable Basic auth, an unknown or expired token, a token whose user is
33/// gone, or a username that matches neither the user nor a token-only name: `Err(Unauthorized)`.
34/// - Otherwise the token's `last_used_at` is touched and the user is returned.
35pub async fn user_from_basic(
36 state: &AppState,
37 headers: &HeaderMap,
38) -> Result<Option<User>, AccessError> {
39 if !headers.contains_key(AUTHORIZATION) {
40 return Ok(None);
41 }
42 let Some((username, token)) = parse_basic_auth(headers) else {
43 return Err(AccessError::Unauthorized);
44 };
45
46 let token_hash = hash_token(&token);
47 let access = state
48 .store
49 .token_by_hash(&token_hash)
50 .await
51 .map_err(internal)?
52 .ok_or(AccessError::Unauthorized)?;
53 // An organization never authenticates, so a token that names one is refused.
54 let user = state
55 .store
56 .user_by_id(&access.user_id)
57 .await
58 .map_err(internal)?
59 .filter(|user| !user.is_org())
60 .ok_or(AccessError::Unauthorized)?;
61
62 let username_ok = username.eq_ignore_ascii_case(&user.username)
63 || TOKEN_ONLY_USERNAMES
64 .iter()
65 .any(|name| username.eq_ignore_ascii_case(name));
66 if !username_ok {
67 return Err(AccessError::Unauthorized);
68 }
69
70 state
71 .store
72 .touch_token(&access.id)
73 .await
74 .map_err(internal)?;
75 crate::pages::settings_live::bump_account(state, &user.id);
76 Ok(Some(user))
77}
78
79fn internal(e: forge_core::Error) -> AccessError {
80 AccessError::Internal(e.to_string())
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86 use http::HeaderValue;
87
88 fn headers_with(value: &str) -> HeaderMap {
89 let mut headers = HeaderMap::new();
90 headers.insert(
91 AUTHORIZATION,
92 HeaderValue::from_str(value).expect("valid header"),
93 );
94 headers
95 }
96
97 fn basic(plain: &str) -> String {
98 format!("Basic {}", BASE64_STANDARD.encode(plain))
99 }
100
101 #[test]
102 fn parse_basic_auth_cases() {
103 // One labelled table: each case keeps its own input and expected result.
104 let t = BASE64_STANDARD.encode("tahinli:t");
105 type Case<'a> = (&'a str, String, Option<(&'a str, &'a str)>);
106 let cases: Vec<Case<'_>> = vec![
107 (
108 "user and token",
109 basic("tahinli:forge_abc"),
110 Some(("tahinli", "forge_abc")),
111 ),
112 (
113 "scheme is case insensitive",
114 format!("bAsIc {t}"),
115 Some(("tahinli", "t")),
116 ),
117 (
118 "password may contain colons",
119 basic("tahinli:a:b:c"),
120 Some(("tahinli", "a:b:c")),
121 ),
122 (
123 "empty password is parsed",
124 basic("tahinli:"),
125 Some(("tahinli", "")),
126 ),
127 ("wrong scheme", format!("Bearer {t}"), None),
128 ("missing colon", basic("tahinlitoken"), None),
129 ("bad base64", "Basic !!!not-base64!!!".to_owned(), None),
130 ("extra space", format!("Basic {t}"), None),
131 ("empty value", "Basic ".to_owned(), None),
132 (
133 "non utf8 credentials",
134 format!(
135 "Basic {}",
136 BASE64_STANDARD.encode([0xff_u8, 0xfe, b':', b'x'])
137 ),
138 None,
139 ),
140 ];
141 for (name, value, want) in cases {
142 let got = parse_basic_auth(&headers_with(&value));
143 let want = want.map(|(user, pass)| (user.to_owned(), pass.to_owned()));
144 assert_eq!(got, want, "case {name}");
145 }
146 assert_eq!(parse_basic_auth(&HeaderMap::new()), None, "case no header");
147 }
148}