forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

git_auth.rs157 lines, 5.4 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 // The same rule as the REST API: git over HTTP needs the `repo` scope, so a token made only
70 // for another purpose (packages) cannot read or push code.
71 if !access
72 .scopes
73 .iter()
74 .any(|scope| scope == crate::api::REPO_SCOPE)
75 {
76 return Err(AccessError::Unauthorized);
77 }
78
79 state
80 .store
81 .touch_token(&access.id)
82 .await
83 .map_err(internal)?;
84 crate::live::bump_account(state, &user.id);
85 Ok(Some(user))
86}
87
88fn internal(e: forge_core::Error) -> AccessError {
89 AccessError::Internal(e.to_string())
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95 use http::HeaderValue;
96
97 fn headers_with(value: &str) -> HeaderMap {
98 let mut headers = HeaderMap::new();
99 headers.insert(
100 AUTHORIZATION,
101 HeaderValue::from_str(value).expect("valid header"),
102 );
103 headers
104 }
105
106 fn basic(plain: &str) -> String {
107 format!("Basic {}", BASE64_STANDARD.encode(plain))
108 }
109
110 #[test]
111 fn parse_basic_auth_cases() {
112 // One labelled table: each case keeps its own input and expected result.
113 let t = BASE64_STANDARD.encode("tahinli:t");
114 type Case<'a> = (&'a str, String, Option<(&'a str, &'a str)>);
115 let cases: Vec<Case<'_>> = vec![
116 (
117 "user and token",
118 basic("tahinli:forge_abc"),
119 Some(("tahinli", "forge_abc")),
120 ),
121 (
122 "scheme is case insensitive",
123 format!("bAsIc {t}"),
124 Some(("tahinli", "t")),
125 ),
126 (
127 "password may contain colons",
128 basic("tahinli:a:b:c"),
129 Some(("tahinli", "a:b:c")),
130 ),
131 (
132 "empty password is parsed",
133 basic("tahinli:"),
134 Some(("tahinli", "")),
135 ),
136 ("wrong scheme", format!("Bearer {t}"), None),
137 ("missing colon", basic("tahinlitoken"), None),
138 ("bad base64", "Basic !!!not-base64!!!".to_owned(), None),
139 ("extra space", format!("Basic {t}"), None),
140 ("empty value", "Basic ".to_owned(), None),
141 (
142 "non utf8 credentials",
143 format!(
144 "Basic {}",
145 BASE64_STANDARD.encode([0xff_u8, 0xfe, b':', b'x'])
146 ),
147 None,
148 ),
149 ];
150 for (name, value, want) in cases {
151 let got = parse_basic_auth(&headers_with(&value));
152 let want = want.map(|(user, pass)| (user.to_owned(), pass.to_owned()));
153 assert_eq!(got, want, "case {name}");
154 }
155 assert_eq!(parse_basic_auth(&HeaderMap::new()), None, "case no header");
156 }
157}