|
| 1 | +//! Shared HTTP client + auth for the `gitlab_*` family. GitLab uses `PRIVATE-TOKEN` (Personal |
| 2 | +//! Access Token) rather than bearer auth as its canonical PAT header; we honour that so users |
| 3 | +//! can paste a token from the GitLab UI directly into `secrets.toml`. |
| 4 | +//! |
| 5 | +//! Every request flows through [`rest_get`], which composes `https://{host}/api/v4{path}` — |
| 6 | +//! `host` is the caller-supplied (and pre-validated) GitLab instance, defaulting to |
| 7 | +//! `gitlab.com`. The fetcher resolves and validates the host before reaching this module, so we |
| 8 | +//! treat it as already-safe here. |
| 9 | +
|
| 10 | +use std::sync::{Mutex, OnceLock}; |
| 11 | +use std::time::Duration; |
| 12 | + |
| 13 | +use reqwest::{Client, StatusCode}; |
| 14 | +use serde::Deserialize; |
| 15 | +use serde::de::DeserializeOwned; |
| 16 | + |
| 17 | +use crate::fetcher::FetchError; |
| 18 | + |
| 19 | +const USER_AGENT: &str = concat!("splashboard/", env!("CARGO_PKG_VERSION")); |
| 20 | +const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); |
| 21 | +const DEFAULT_HOST: &str = "gitlab.com"; |
| 22 | + |
| 23 | +static AUTHENTICATED_USERNAME_CACHE: OnceLock<Mutex<Option<(String, String)>>> = OnceLock::new(); |
| 24 | + |
| 25 | +pub fn default_host() -> &'static str { |
| 26 | + DEFAULT_HOST |
| 27 | +} |
| 28 | + |
| 29 | +pub fn http() -> &'static Client { |
| 30 | + static CLIENT: OnceLock<Client> = OnceLock::new(); |
| 31 | + CLIENT.get_or_init(|| { |
| 32 | + Client::builder() |
| 33 | + .user_agent(USER_AGENT) |
| 34 | + .timeout(REQUEST_TIMEOUT) |
| 35 | + .gzip(true) |
| 36 | + .build() |
| 37 | + .expect("reqwest client should build with default config") |
| 38 | + }) |
| 39 | +} |
| 40 | + |
| 41 | +pub fn resolve_token() -> Result<String, FetchError> { |
| 42 | + std::env::var("GITLAB_TOKEN").map_err(|_| FetchError::Failed("GITLAB_TOKEN not set".into())) |
| 43 | +} |
| 44 | + |
| 45 | +/// Username of the token-authenticated user. Resolved lazily via `/api/v4/user` and memoised |
| 46 | +/// per-host so the `gitlab_review_requests` widget doesn't pay a roundtrip on every refresh. |
| 47 | +/// Keyed on `host` because two configs pointing at different GitLab instances must not bleed |
| 48 | +/// usernames into each other. |
| 49 | +pub async fn resolve_authenticated_username(host: &str) -> Result<String, FetchError> { |
| 50 | + let slot = AUTHENTICATED_USERNAME_CACHE.get_or_init(|| Mutex::new(None)); |
| 51 | + if let Some(cached) = slot |
| 52 | + .lock() |
| 53 | + .ok() |
| 54 | + .and_then(|g| g.clone()) |
| 55 | + .filter(|(h, _)| h == host) |
| 56 | + { |
| 57 | + return Ok(cached.1); |
| 58 | + } |
| 59 | + #[derive(Deserialize)] |
| 60 | + struct Me { |
| 61 | + username: String, |
| 62 | + } |
| 63 | + let me: Me = rest_get(host, "/user").await?; |
| 64 | + if let Ok(mut g) = slot.lock() { |
| 65 | + *g = Some((host.into(), me.username.clone())); |
| 66 | + } |
| 67 | + Ok(me.username) |
| 68 | +} |
| 69 | + |
| 70 | +#[cfg(test)] |
| 71 | +pub(crate) fn clear_authenticated_username_cache() { |
| 72 | + if let Ok(mut g) = AUTHENTICATED_USERNAME_CACHE |
| 73 | + .get_or_init(|| Mutex::new(None)) |
| 74 | + .lock() |
| 75 | + { |
| 76 | + *g = None; |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +/// REST GET → deserialize JSON. `path` is the part after `/api/v4` (e.g. `"/user"`, |
| 81 | +/// `"/projects/group%2Fproj"`). Non-2xx responses surface the GitLab `message` field when |
| 82 | +/// present so the error placeholder and the log line are both actionable. |
| 83 | +pub async fn rest_get<T: DeserializeOwned>(host: &str, path: &str) -> Result<T, FetchError> { |
| 84 | + let token = resolve_token()?; |
| 85 | + let url = format!("https://{host}/api/v4{path}"); |
| 86 | + let res = http() |
| 87 | + .get(&url) |
| 88 | + .header("PRIVATE-TOKEN", &token) |
| 89 | + .header("Accept", "application/json") |
| 90 | + .send() |
| 91 | + .await |
| 92 | + .map_err(|e| FetchError::Failed(format!("gitlab request failed: {e}")))?; |
| 93 | + parse_json(res).await |
| 94 | +} |
| 95 | + |
| 96 | +async fn parse_json<T: DeserializeOwned>(res: reqwest::Response) -> Result<T, FetchError> { |
| 97 | + let status = res.status(); |
| 98 | + let bytes = res |
| 99 | + .bytes() |
| 100 | + .await |
| 101 | + .map_err(|e| FetchError::Failed(format!("gitlab response body: {e}")))?; |
| 102 | + if !status.is_success() { |
| 103 | + return Err(FetchError::Failed(error_message(status, &bytes))); |
| 104 | + } |
| 105 | + serde_json::from_slice(&bytes) |
| 106 | + .map_err(|e| FetchError::Failed(format!("gitlab json parse: {e}"))) |
| 107 | +} |
| 108 | + |
| 109 | +fn error_message(status: StatusCode, body: &[u8]) -> String { |
| 110 | + #[derive(Deserialize)] |
| 111 | + struct ApiError { |
| 112 | + message: Option<serde_json::Value>, |
| 113 | + error: Option<String>, |
| 114 | + } |
| 115 | + let reported = serde_json::from_slice::<ApiError>(body).ok().and_then(|e| { |
| 116 | + e.message |
| 117 | + .as_ref() |
| 118 | + .map(|m| match m { |
| 119 | + serde_json::Value::String(s) => s.clone(), |
| 120 | + other => other.to_string(), |
| 121 | + }) |
| 122 | + .or(e.error) |
| 123 | + }); |
| 124 | + match reported { |
| 125 | + Some(m) => format!("gitlab {status}: {m}"), |
| 126 | + None => format!("gitlab {status}"), |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +#[cfg(test)] |
| 131 | +mod tests { |
| 132 | + use std::future::Future; |
| 133 | + use std::io::{Read, Write}; |
| 134 | + use std::net::TcpListener; |
| 135 | + use std::thread; |
| 136 | + |
| 137 | + use serde::Deserialize; |
| 138 | + |
| 139 | + use super::*; |
| 140 | + |
| 141 | + #[derive(Debug, Deserialize)] |
| 142 | + struct TestPayload { |
| 143 | + username: String, |
| 144 | + } |
| 145 | + |
| 146 | + struct EnvGuard { |
| 147 | + _lock: std::sync::MutexGuard<'static, ()>, |
| 148 | + restore: Vec<(&'static str, Option<String>)>, |
| 149 | + } |
| 150 | + |
| 151 | + impl EnvGuard { |
| 152 | + fn set(pairs: &[(&'static str, Option<&str>)]) -> Self { |
| 153 | + let lock = crate::paths::TEST_ENV_LOCK |
| 154 | + .lock() |
| 155 | + .unwrap_or_else(|e| e.into_inner()); |
| 156 | + let restore = pairs |
| 157 | + .iter() |
| 158 | + .map(|(k, v)| { |
| 159 | + let prev = std::env::var(k).ok(); |
| 160 | + match v { |
| 161 | + Some(value) => unsafe { std::env::set_var(k, value) }, |
| 162 | + None => unsafe { std::env::remove_var(k) }, |
| 163 | + } |
| 164 | + (*k, prev) |
| 165 | + }) |
| 166 | + .collect(); |
| 167 | + Self { |
| 168 | + _lock: lock, |
| 169 | + restore, |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + impl Drop for EnvGuard { |
| 175 | + fn drop(&mut self) { |
| 176 | + for (k, v) in &self.restore { |
| 177 | + match v { |
| 178 | + Some(value) => unsafe { std::env::set_var(k, value) }, |
| 179 | + None => unsafe { std::env::remove_var(k) }, |
| 180 | + } |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + fn run_async<T>(future: impl Future<Output = T>) -> T { |
| 186 | + tokio::runtime::Builder::new_current_thread() |
| 187 | + .enable_all() |
| 188 | + .build() |
| 189 | + .unwrap() |
| 190 | + .block_on(future) |
| 191 | + } |
| 192 | + |
| 193 | + #[test] |
| 194 | + fn default_host_is_gitlab_dot_com() { |
| 195 | + assert_eq!(default_host(), "gitlab.com"); |
| 196 | + } |
| 197 | + |
| 198 | + #[test] |
| 199 | + fn resolve_token_reads_gitlab_token() { |
| 200 | + let _g = EnvGuard::set(&[("GITLAB_TOKEN", Some("glpat-xxx"))]); |
| 201 | + assert_eq!(resolve_token().unwrap(), "glpat-xxx"); |
| 202 | + } |
| 203 | + |
| 204 | + #[test] |
| 205 | + fn resolve_token_fails_when_unset() { |
| 206 | + let _g = EnvGuard::set(&[("GITLAB_TOKEN", None)]); |
| 207 | + let err = resolve_token().unwrap_err(); |
| 208 | + assert!(matches!(err, FetchError::Failed(m) if m == "GITLAB_TOKEN not set")); |
| 209 | + } |
| 210 | + |
| 211 | + #[test] |
| 212 | + fn http_reuses_the_same_client() { |
| 213 | + assert!(std::ptr::eq(http(), http())); |
| 214 | + } |
| 215 | + |
| 216 | + #[test] |
| 217 | + fn resolve_authenticated_username_returns_cached_value() { |
| 218 | + let _g = EnvGuard::set(&[("GITLAB_TOKEN", None)]); |
| 219 | + clear_authenticated_username_cache(); |
| 220 | + *AUTHENTICATED_USERNAME_CACHE |
| 221 | + .get_or_init(|| Mutex::new(None)) |
| 222 | + .lock() |
| 223 | + .unwrap() = Some(("gitlab.com".into(), "root".into())); |
| 224 | + |
| 225 | + let user = run_async(resolve_authenticated_username("gitlab.com")).unwrap(); |
| 226 | + assert_eq!(user, "root"); |
| 227 | + clear_authenticated_username_cache(); |
| 228 | + } |
| 229 | + |
| 230 | + #[test] |
| 231 | + fn resolve_authenticated_username_busts_cache_per_host() { |
| 232 | + // A cache hit must match the requested host; otherwise switching configs between two |
| 233 | + // GitLab instances would bleed identities. Requesting a different host than the cached |
| 234 | + // one falls through to `rest_get`, which (without a token) returns the auth error. |
| 235 | + let _g = EnvGuard::set(&[("GITLAB_TOKEN", None)]); |
| 236 | + clear_authenticated_username_cache(); |
| 237 | + *AUTHENTICATED_USERNAME_CACHE |
| 238 | + .get_or_init(|| Mutex::new(None)) |
| 239 | + .lock() |
| 240 | + .unwrap() = Some(("gitlab.com".into(), "root".into())); |
| 241 | + |
| 242 | + let err = run_async(resolve_authenticated_username("gitlab.example.org")).unwrap_err(); |
| 243 | + assert!(matches!(err, FetchError::Failed(m) if m == "GITLAB_TOKEN not set")); |
| 244 | + clear_authenticated_username_cache(); |
| 245 | + } |
| 246 | + |
| 247 | + #[test] |
| 248 | + fn rest_get_send_error_surfaces_request_failed() { |
| 249 | + // `\n` in a PRIVATE-TOKEN header forces reqwest to fail at builder time, so the send- |
| 250 | + // error arm is reachable without hitting the live API. |
| 251 | + let _g = EnvGuard::set(&[("GITLAB_TOKEN", Some("tok\nbreak"))]); |
| 252 | + let err = run_async(rest_get::<TestPayload>("gitlab.com", "/user")).unwrap_err(); |
| 253 | + assert!(matches!( |
| 254 | + err, |
| 255 | + FetchError::Failed(m) if m.starts_with("gitlab request failed:") |
| 256 | + )); |
| 257 | + } |
| 258 | + |
| 259 | + #[test] |
| 260 | + fn parse_json_deserializes_success_bodies() { |
| 261 | + let payload = parse_test_payload("200 OK", r#"{"username":"alice"}"#).unwrap(); |
| 262 | + assert_eq!(payload.username, "alice"); |
| 263 | + } |
| 264 | + |
| 265 | + #[test] |
| 266 | + fn parse_json_surfaces_string_message_field() { |
| 267 | + let err = |
| 268 | + parse_test_payload("404 Not Found", r#"{"message":"404 Not Found"}"#).unwrap_err(); |
| 269 | + assert!(matches!( |
| 270 | + err, |
| 271 | + FetchError::Failed(m) if m == "gitlab 404 Not Found: 404 Not Found" |
| 272 | + )); |
| 273 | + } |
| 274 | + |
| 275 | + #[test] |
| 276 | + fn parse_json_handles_structured_message_objects() { |
| 277 | + // GitLab sometimes returns `{"message": {"error": "...", "details": [...]}}` rather |
| 278 | + // than a flat string; the error wrapper should stringify gracefully instead of dropping |
| 279 | + // it. |
| 280 | + let err = parse_test_payload( |
| 281 | + "400 Bad Request", |
| 282 | + r#"{"message":{"error":"invalid","scope":["user"]}}"#, |
| 283 | + ) |
| 284 | + .unwrap_err(); |
| 285 | + let FetchError::Failed(m) = err else { |
| 286 | + panic!("expected Failed"); |
| 287 | + }; |
| 288 | + assert!(m.starts_with("gitlab 400 Bad Request:")); |
| 289 | + } |
| 290 | + |
| 291 | + #[test] |
| 292 | + fn parse_json_falls_back_to_error_field() { |
| 293 | + let err = |
| 294 | + parse_test_payload("401 Unauthorized", r#"{"error":"invalid_token"}"#).unwrap_err(); |
| 295 | + assert!(matches!( |
| 296 | + err, |
| 297 | + FetchError::Failed(m) if m == "gitlab 401 Unauthorized: invalid_token" |
| 298 | + )); |
| 299 | + } |
| 300 | + |
| 301 | + #[test] |
| 302 | + fn parse_json_falls_back_to_status_without_a_message() { |
| 303 | + let err = parse_test_payload("500 Internal Server Error", "{}").unwrap_err(); |
| 304 | + assert!(matches!( |
| 305 | + err, |
| 306 | + FetchError::Failed(m) if m == "gitlab 500 Internal Server Error" |
| 307 | + )); |
| 308 | + } |
| 309 | + |
| 310 | + #[test] |
| 311 | + fn parse_json_surfaces_json_parse_errors() { |
| 312 | + let err = parse_test_payload("200 OK", "not-json").unwrap_err(); |
| 313 | + assert!(matches!( |
| 314 | + err, |
| 315 | + FetchError::Failed(m) if m.contains("gitlab json parse") |
| 316 | + )); |
| 317 | + } |
| 318 | + |
| 319 | + fn parse_test_payload(status: &str, body: &str) -> Result<TestPayload, FetchError> { |
| 320 | + let (url, server) = serve_once(status, body); |
| 321 | + let response = run_async(async { |
| 322 | + let response = http().get(&url).send().await.unwrap(); |
| 323 | + parse_json::<TestPayload>(response).await |
| 324 | + }); |
| 325 | + server.join().unwrap(); |
| 326 | + response |
| 327 | + } |
| 328 | + |
| 329 | + fn serve_once(status: &str, body: &str) -> (String, thread::JoinHandle<()>) { |
| 330 | + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); |
| 331 | + let addr = listener.local_addr().unwrap(); |
| 332 | + let status = status.to_owned(); |
| 333 | + let body = body.to_owned(); |
| 334 | + let handle = thread::spawn(move || { |
| 335 | + let (mut stream, _) = listener.accept().unwrap(); |
| 336 | + let mut request = [0; 1024]; |
| 337 | + let _ = stream.read(&mut request); |
| 338 | + let response = format!( |
| 339 | + "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", |
| 340 | + body.len() |
| 341 | + ); |
| 342 | + stream.write_all(response.as_bytes()).unwrap(); |
| 343 | + stream.flush().unwrap(); |
| 344 | + }); |
| 345 | + (format!("http://{addr}"), handle) |
| 346 | + } |
| 347 | +} |
0 commit comments