use base64::prelude::{BASE64_STANDARD, Engine}; use forge_core::{User, token::hash_token}; use http::{HeaderMap, header::AUTHORIZATION}; use crate::access::AccessError; use crate::state::AppState; const TOKEN_ONLY_USERNAMES: [&str; 2] = ["x-access-token", "oauth2"]; pub fn parse_basic_auth(headers: &HeaderMap) -> Option<(String, String)> { let value = headers.get(AUTHORIZATION)?.to_str().ok()?; let (scheme, encoded) = value.split_once(' ')?; if !scheme.eq_ignore_ascii_case("basic") || encoded.is_empty() { return None; } let decoded = BASE64_STANDARD.decode(encoded).ok()?; let text = String::from_utf8(decoded).ok()?; let (username, password) = text.split_once(':')?; Some((username.to_owned(), password.to_owned())) } pub async fn user_from_basic( state: &AppState, headers: &HeaderMap, ) -> Result, AccessError> { if !headers.contains_key(AUTHORIZATION) { return Ok(None); } let Some((username, token)) = parse_basic_auth(headers) else { return Err(AccessError::Unauthorized); }; let token_hash = hash_token(&token); let access = state .store .token_by_hash(&token_hash) .await .map_err(internal)? .ok_or(AccessError::Unauthorized)?; let user = state .store .user_by_id(&access.user_id) .await .map_err(internal)? .filter(|user| !user.is_org()) .ok_or(AccessError::Unauthorized)?; let username_ok = username.eq_ignore_ascii_case(&user.username) || TOKEN_ONLY_USERNAMES .iter() .any(|name| username.eq_ignore_ascii_case(name)); if !username_ok { return Err(AccessError::Unauthorized); } if !access .scopes .iter() .any(|scope| scope == crate::api::REPO_SCOPE) { return Err(AccessError::Unauthorized); } state .store .touch_token(&access.id) .await .map_err(internal)?; crate::live::bump_account(state, &user.id); Ok(Some(user)) } fn internal(e: forge_core::Error) -> AccessError { AccessError::Internal(e.to_string()) } #[cfg(test)] mod tests { use super::*; use http::HeaderValue; fn headers_with(value: &str) -> HeaderMap { let mut headers = HeaderMap::new(); headers.insert( AUTHORIZATION, HeaderValue::from_str(value).expect("valid header"), ); headers } fn basic(plain: &str) -> String { format!("Basic {}", BASE64_STANDARD.encode(plain)) } #[test] fn parse_basic_auth_cases() { let t = BASE64_STANDARD.encode("tahinli:t"); type Case<'a> = (&'a str, String, Option<(&'a str, &'a str)>); let cases: Vec> = vec![ ( "user and token", basic("tahinli:forge_abc"), Some(("tahinli", "forge_abc")), ), ( "scheme is case insensitive", format!("bAsIc {t}"), Some(("tahinli", "t")), ), ( "password may contain colons", basic("tahinli:a:b:c"), Some(("tahinli", "a:b:c")), ), ( "empty password is parsed", basic("tahinli:"), Some(("tahinli", "")), ), ("wrong scheme", format!("Bearer {t}"), None), ("missing colon", basic("tahinlitoken"), None), ("bad base64", "Basic !!!not-base64!!!".to_owned(), None), ("extra space", format!("Basic {t}"), None), ("empty value", "Basic ".to_owned(), None), ( "non utf8 credentials", format!( "Basic {}", BASE64_STANDARD.encode([0xff_u8, 0xfe, b':', b'x']) ), None, ), ]; for (name, value, want) in cases { let got = parse_basic_auth(&headers_with(&value)); let want = want.map(|(user, pass)| (user.to_owned(), pass.to_owned())); assert_eq!(got, want, "case {name}"); } assert_eq!(parse_basic_auth(&HeaderMap::new()), None, "case no header"); } }