forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiBeb7e617Tahinli1 month ago137 commits

git_auth.rs179 lines, 5.5 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 parses_user_and_token() {
103 let headers = headers_with(&basic("tahinli:forge_abc"));
104 assert_eq!(
105 parse_basic_auth(&headers),
106 Some(("tahinli".to_owned(), "forge_abc".to_owned()))
107 );
108 }
109
110 #[test]
111 fn scheme_is_case_insensitive() {
112 let value = format!("bAsIc {}", BASE64_STANDARD.encode("tahinli:t"));
113 let headers = headers_with(&value);
114 assert_eq!(
115 parse_basic_auth(&headers),
116 Some(("tahinli".into(), "t".into()))
117 );
118 }
119
120 #[test]
121 fn password_may_contain_colons() {
122 let headers = headers_with(&basic("tahinli:a:b:c"));
123 assert_eq!(
124 parse_basic_auth(&headers),
125 Some(("tahinli".into(), "a:b:c".into()))
126 );
127 }
128
129 #[test]
130 fn empty_password_is_parsed_but_user_is_not_resolved_here() {
131 let headers = headers_with(&basic("tahinli:"));
132 assert_eq!(
133 parse_basic_auth(&headers),
134 Some(("tahinli".into(), String::new()))
135 );
136 }
137
138 #[test]
139 fn rejects_wrong_scheme() {
140 let value = format!("Bearer {}", BASE64_STANDARD.encode("tahinli:t"));
141 assert_eq!(parse_basic_auth(&headers_with(&value)), None);
142 }
143
144 #[test]
145 fn rejects_missing_colon() {
146 assert_eq!(
147 parse_basic_auth(&headers_with(&basic("tahinlitoken"))),
148 None
149 );
150 }
151
152 #[test]
153 fn rejects_bad_base64() {
154 assert_eq!(
155 parse_basic_auth(&headers_with("Basic !!!not-base64!!!")),
156 None
157 );
158 }
159
160 #[test]
161 fn rejects_extra_spaces_and_empty_value() {
162 let encoded = BASE64_STANDARD.encode("tahinli:t");
163 assert_eq!(
164 parse_basic_auth(&headers_with(&format!("Basic {encoded}"))),
165 None
166 );
167 assert_eq!(parse_basic_auth(&headers_with("Basic ")), None);
168 assert_eq!(parse_basic_auth(&HeaderMap::new()), None);
169 }
170
171 #[test]
172 fn rejects_non_utf8_credentials() {
173 let encoded = BASE64_STANDARD.encode([0xff_u8, 0xfe, b':', b'x']);
174 assert_eq!(
175 parse_basic_auth(&headers_with(&format!("Basic {encoded}"))),
176 None
177 );
178 }
179}