forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·9.7 MiB·37e985d·Tahinli·3 hours ago·363 commits
| 1 | pub mod ci; |
| 2 | pub mod releases; |
| 3 | pub mod statuses; |
| 4 | pub mod tags; |
| 5 | |
| 6 | use std::net::IpAddr; |
| 7 | use std::path::PathBuf; |
| 8 | use std::time::Instant; |
| 9 | |
| 10 | use forge_core::{Action, Denied, Repo, User, authorize, token::hash_token}; |
| 11 | use forge_git::browse; |
| 12 | use http::HeaderMap; |
| 13 | use http::header::{ |
| 14 | AUTHORIZATION, CONTENT_TYPE, HeaderName, HeaderValue, RETRY_AFTER, WWW_AUTHENTICATE, |
| 15 | }; |
| 16 | use serde_json::{Value, json}; |
| 17 | use topcoat::context::{Cx, context}; |
| 18 | use topcoat::router::StatusCode; |
| 19 | use topcoat::router::request::uri; |
| 20 | use topcoat::router::response::Response; |
| 21 | |
| 22 | use crate::state::AppState; |
| 23 | use crate::throttle::{self, GIT_IP_LIMIT}; |
| 24 | use crate::views::query_value; |
| 25 | |
| 26 | pub const REPO_SCOPE: &str = "repo"; |
| 27 | |
| 28 | pub type Refusal = Box<Response>; |
| 29 | |
| 30 | pub const MAX_PAGE: usize = 50; |
| 31 | |
| 32 | pub fn numeric_id(id: &str) -> i64 { |
| 33 | let digest = hash_token(id); |
| 34 | i64::from_str_radix(&digest[..12], 16).unwrap_or(0) + 1 |
| 35 | } |
| 36 | |
| 37 | pub fn is_numeric(raw: &str) -> bool { |
| 38 | !raw.is_empty() && raw.len() <= 15 && raw.bytes().all(|b| b.is_ascii_digit()) |
| 39 | } |
| 40 | |
| 41 | pub fn user_json(base: &str, id: &str, name: &str) -> Value { |
| 42 | json!({ |
| 43 | "id": numeric_id(id), |
| 44 | "login": name, |
| 45 | "username": name, |
| 46 | "login_name": "", |
| 47 | "full_name": "", |
| 48 | "email": "", |
| 49 | "avatar_url": "", |
| 50 | "html_url": format!("{}/{}", base.trim_end_matches('/'), name), |
| 51 | "is_admin": false, |
| 52 | }) |
| 53 | } |
| 54 | |
| 55 | pub struct Paging { |
| 56 | pub page: usize, |
| 57 | pub limit: usize, |
| 58 | } |
| 59 | |
| 60 | pub fn paging(cx: &Cx, default_limit: usize) -> Paging { |
| 61 | let number = |key: &str| query_value(cx, key).and_then(|v| v.parse::<usize>().ok()); |
| 62 | Paging { |
| 63 | page: number("page").filter(|p| *p > 0).unwrap_or(1), |
| 64 | limit: number("limit") |
| 65 | .filter(|l| *l > 0) |
| 66 | .map_or(default_limit, |l| l.min(MAX_PAGE)), |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | pub fn slice<T>(items: Vec<T>, pg: &Paging) -> (Vec<T>, usize) { |
| 71 | let total = items.len(); |
| 72 | let start = pg.page.saturating_sub(1).saturating_mul(pg.limit); |
| 73 | ( |
| 74 | items.into_iter().skip(start).take(pg.limit).collect(), |
| 75 | total, |
| 76 | ) |
| 77 | } |
| 78 | |
| 79 | pub fn page_response(cx: &Cx, items: Vec<Value>, total: usize, pg: &Paging) -> Response { |
| 80 | let mut res = json(StatusCode::OK, &Value::Array(items)); |
| 81 | let last = total.div_ceil(pg.limit.max(1)).max(1); |
| 82 | let state = context::<AppState>(cx); |
| 83 | let base = state.config.base_url.trim_end_matches('/'); |
| 84 | let mut rest = String::new(); |
| 85 | if let Some(query) = uri(cx).query() { |
| 86 | for (k, v) in form_urlencoded::parse(query.as_bytes()) { |
| 87 | if k != "page" && k != "limit" { |
| 88 | rest.push_str(&format!( |
| 89 | "{}={}&", |
| 90 | form_urlencoded::byte_serialize(k.as_bytes()).collect::<String>(), |
| 91 | form_urlencoded::byte_serialize(v.as_bytes()).collect::<String>() |
| 92 | )); |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | let link = |page: usize, rel: &str| { |
| 97 | format!( |
| 98 | "<{base}{}?{rest}page={page}&limit={}>; rel=\"{rel}\"", |
| 99 | uri(cx).path(), |
| 100 | pg.limit |
| 101 | ) |
| 102 | }; |
| 103 | let mut links = Vec::new(); |
| 104 | if pg.page < last { |
| 105 | links.push(link(pg.page + 1, "next")); |
| 106 | links.push(link(last, "last")); |
| 107 | } |
| 108 | if pg.page > 1 { |
| 109 | links.push(link(pg.page - 1, "prev")); |
| 110 | links.push(link(1, "first")); |
| 111 | } |
| 112 | let map = res.headers_mut(); |
| 113 | map.insert( |
| 114 | HeaderName::from_static("x-total-count"), |
| 115 | HeaderValue::from(total), |
| 116 | ); |
| 117 | if !links.is_empty() |
| 118 | && let Ok(value) = HeaderValue::from_str(&links.join(", ")) |
| 119 | { |
| 120 | map.insert(HeaderName::from_static("link"), value); |
| 121 | } |
| 122 | map.insert( |
| 123 | HeaderName::from_static("access-control-expose-headers"), |
| 124 | HeaderValue::from_static("Link, X-Total-Count"), |
| 125 | ); |
| 126 | res |
| 127 | } |
| 128 | |
| 129 | pub fn json<T: serde::Serialize + ?Sized>(status: StatusCode, value: &T) -> Response { |
| 130 | let mut res = Response::new(topcoat::router::Body::from( |
| 131 | serde_json::to_string(value).unwrap_or_default(), |
| 132 | )); |
| 133 | *res.status_mut() = status; |
| 134 | res.headers_mut().insert( |
| 135 | CONTENT_TYPE, |
| 136 | HeaderValue::from_static("application/json; charset=utf-8"), |
| 137 | ); |
| 138 | res |
| 139 | } |
| 140 | |
| 141 | pub fn error(status: StatusCode, message: &str) -> Response { |
| 142 | json(status, &json!({ "error": message })) |
| 143 | } |
| 144 | |
| 145 | pub fn unauthorized() -> Response { |
| 146 | let mut res = error(StatusCode::UNAUTHORIZED, "authentication required"); |
| 147 | res.headers_mut().insert( |
| 148 | WWW_AUTHENTICATE, |
| 149 | HeaderValue::from_static("Bearer realm=\"forge\""), |
| 150 | ); |
| 151 | res |
| 152 | } |
| 153 | |
| 154 | pub fn internal(message: impl std::fmt::Display) -> Refusal { |
| 155 | tracing::error!(error = %message, "api request failed"); |
| 156 | Box::new(error( |
| 157 | StatusCode::INTERNAL_SERVER_ERROR, |
| 158 | "internal server error", |
| 159 | )) |
| 160 | } |
| 161 | |
| 162 | pub fn presented_token(headers: &HeaderMap) -> Option<Option<String>> { |
| 163 | let value = headers.get(AUTHORIZATION)?.to_str().ok()?; |
| 164 | let Some((scheme, rest)) = value.split_once(' ') else { |
| 165 | return Some(None); |
| 166 | }; |
| 167 | let token = if scheme.eq_ignore_ascii_case("basic") { |
| 168 | crate::git_auth::parse_basic_auth(headers).map(|(_, password)| password) |
| 169 | } else if scheme.eq_ignore_ascii_case("bearer") || scheme.eq_ignore_ascii_case("token") { |
| 170 | Some(rest.trim().to_owned()) |
| 171 | } else { |
| 172 | None |
| 173 | }; |
| 174 | match token { |
| 175 | Some(token) if token.starts_with("forge_") => Some(Some(token)), |
| 176 | _ => Some(None), |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | pub async fn authenticate( |
| 181 | state: &AppState, |
| 182 | ip: IpAddr, |
| 183 | headers: &HeaderMap, |
| 184 | ) -> Result<Option<User>, Refusal> { |
| 185 | let Some((user, token_id, scopes)) = authenticate_token(state, ip, headers).await? else { |
| 186 | return Ok(None); |
| 187 | }; |
| 188 | if !scopes.iter().any(|scope| scope == REPO_SCOPE) { |
| 189 | return Err(Box::new(error( |
| 190 | StatusCode::FORBIDDEN, |
| 191 | "the token lacks the repo scope", |
| 192 | ))); |
| 193 | } |
| 194 | if let Err(e) = state.store.touch_token(&token_id).await { |
| 195 | return Err(internal(e)); |
| 196 | } |
| 197 | crate::live::bump_account(state, &user.id); |
| 198 | Ok(Some(user)) |
| 199 | } |
| 200 | |
| 201 | pub async fn authenticate_token( |
| 202 | state: &AppState, |
| 203 | ip: IpAddr, |
| 204 | headers: &HeaderMap, |
| 205 | ) -> Result<Option<(User, String, Vec<String>)>, Refusal> { |
| 206 | if !headers.contains_key(AUTHORIZATION) { |
| 207 | return Ok(None); |
| 208 | } |
| 209 | let key = throttle::ip_key("git-ip", ip); |
| 210 | let now = Instant::now(); |
| 211 | if let Some(retry) = state.throttle.check(&key, GIT_IP_LIMIT, now) { |
| 212 | tracing::warn!(ip = %ip, retry_after_secs = retry.as_secs(), "api authentication throttled"); |
| 213 | let mut res = error( |
| 214 | StatusCode::TOO_MANY_REQUESTS, |
| 215 | "too many failed attempts, try again later", |
| 216 | ); |
| 217 | res.headers_mut() |
| 218 | .insert(RETRY_AFTER, HeaderValue::from(retry.as_secs().max(1))); |
| 219 | return Err(Box::new(res)); |
| 220 | } |
| 221 | |
| 222 | let Some(Some(token)) = presented_token(headers) else { |
| 223 | state.throttle.record_failure(&key, now); |
| 224 | return Err(Box::new(unauthorized())); |
| 225 | }; |
| 226 | let access = match state.store.token_by_hash(&hash_token(&token)).await { |
| 227 | Ok(Some(access)) => access, |
| 228 | Ok(None) => { |
| 229 | state.throttle.record_failure(&key, now); |
| 230 | return Err(Box::new(unauthorized())); |
| 231 | } |
| 232 | Err(e) => return Err(internal(e)), |
| 233 | }; |
| 234 | let user = match state.store.user_by_id(&access.user_id).await { |
| 235 | Ok(Some(user)) if !user.is_org() => user, |
| 236 | Ok(_) => { |
| 237 | state.throttle.record_failure(&key, now); |
| 238 | return Err(Box::new(unauthorized())); |
| 239 | } |
| 240 | Err(e) => return Err(internal(e)), |
| 241 | }; |
| 242 | Ok(Some((user, access.id, access.scopes))) |
| 243 | } |
| 244 | |
| 245 | fn refused(actor: Option<&User>, denied: Denied) -> Refusal { |
| 246 | Box::new(match (actor, denied) { |
| 247 | (None, _) => unauthorized(), |
| 248 | (Some(_), Denied::NotFound) => error(StatusCode::NOT_FOUND, "repository not found"), |
| 249 | (Some(_), Denied::Forbidden) => error(StatusCode::FORBIDDEN, "forbidden"), |
| 250 | }) |
| 251 | } |
| 252 | |
| 253 | pub async fn load_repo( |
| 254 | state: &AppState, |
| 255 | actor: Option<&User>, |
| 256 | owner: &str, |
| 257 | name: &str, |
| 258 | action: Action, |
| 259 | ) -> Result<Repo, Refusal> { |
| 260 | let repo = match state.store.repo_by_owner_and_name(owner, name).await { |
| 261 | Ok(Some(repo)) => repo, |
| 262 | Ok(None) => return Err(refused(actor, Denied::NotFound)), |
| 263 | Err(e) => return Err(internal(e)), |
| 264 | }; |
| 265 | let (role, org_role) = state |
| 266 | .store |
| 267 | .user_roles(&repo, actor) |
| 268 | .await |
| 269 | .map_err(internal)?; |
| 270 | authorize(actor, &repo, role, org_role, action).map_err(|denied| refused(actor, denied))?; |
| 271 | Ok(repo) |
| 272 | } |
| 273 | |
| 274 | pub async fn load_writer( |
| 275 | state: &AppState, |
| 276 | ip: IpAddr, |
| 277 | headers: &HeaderMap, |
| 278 | owner: &str, |
| 279 | name: &str, |
| 280 | ) -> Result<(Repo, User), Refusal> { |
| 281 | let Some(user) = authenticate(state, ip, headers).await? else { |
| 282 | return Err(Box::new(unauthorized())); |
| 283 | }; |
| 284 | let repo = load_repo(state, Some(&user), owner, name, Action::Write).await?; |
| 285 | Ok((repo, user)) |
| 286 | } |
| 287 | |
| 288 | pub fn repo_dir(state: &AppState, repo: &Repo) -> Result<PathBuf, Refusal> { |
| 289 | forge_git::repo::repo_path(&state.config.data_dir, &repo.id).map_err(internal) |
| 290 | } |
| 291 | |
| 292 | pub async fn commit_exists(path: PathBuf, sha: String) -> Result<bool, Refusal> { |
| 293 | tokio::task::spawn_blocking(move || browse::commit_reachable(&path, &sha)) |
| 294 | .await |
| 295 | .map_err(internal)? |
| 296 | .map_err(internal) |
| 297 | } |
| 298 | |
| 299 | pub fn normalize_sha(raw: &str) -> Option<String> { |
| 300 | let lower = raw.to_ascii_lowercase(); |
| 301 | forge_core::store::commit_status::is_full_sha(&lower).then_some(lower) |
| 302 | } |
| 303 | |
| 304 | pub async fn read_body(body: topcoat::router::Body, limit: usize) -> Result<Vec<u8>, Refusal> { |
| 305 | topcoat::router::to_bytes(body, limit) |
| 306 | .await |
| 307 | .map(|bytes| bytes.to_vec()) |
| 308 | .map_err(|_| { |
| 309 | Box::new(error( |
| 310 | StatusCode::PAYLOAD_TOO_LARGE, |
| 311 | "request body is too large", |
| 312 | )) |
| 313 | }) |
| 314 | } |
| 315 | |
| 316 | pub async fn json_body<T: serde::de::DeserializeOwned>( |
| 317 | body: topcoat::router::Body, |
| 318 | limit: usize, |
| 319 | ) -> Result<T, Refusal> { |
| 320 | let bytes = read_body(body, limit).await?; |
| 321 | serde_json::from_slice(&bytes).map_err(|e| { |
| 322 | Box::new(error( |
| 323 | StatusCode::BAD_REQUEST, |
| 324 | &format!("invalid JSON body: {e}"), |
| 325 | )) |
| 326 | }) |
| 327 | } |
| 328 | |
| 329 | #[cfg(test)] |
| 330 | mod tests { |
| 331 | use super::*; |
| 332 | use http::HeaderValue; |
| 333 | |
| 334 | fn headers_with(value: &str) -> HeaderMap { |
| 335 | let mut headers = HeaderMap::new(); |
| 336 | headers.insert( |
| 337 | AUTHORIZATION, |
| 338 | HeaderValue::from_str(value).expect("valid header"), |
| 339 | ); |
| 340 | headers |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn accepts_bearer_and_token_schemes() { |
| 345 | assert_eq!( |
| 346 | presented_token(&headers_with("Bearer forge_abc")), |
| 347 | Some(Some("forge_abc".into())) |
| 348 | ); |
| 349 | assert_eq!( |
| 350 | presented_token(&headers_with("token forge_abc")), |
| 351 | Some(Some("forge_abc".into())) |
| 352 | ); |
| 353 | assert_eq!( |
| 354 | presented_token(&headers_with("BEARER forge_abc")), |
| 355 | Some(Some("forge_abc".into())) |
| 356 | ); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn rejects_other_shapes() { |
| 361 | assert_eq!( |
| 362 | presented_token(&headers_with("Basic Zm9vOmJhcg==")), |
| 363 | Some(None) |
| 364 | ); |
| 365 | assert_eq!( |
| 366 | presented_token(&headers_with("Bearer notforge")), |
| 367 | Some(None) |
| 368 | ); |
| 369 | assert_eq!(presented_token(&headers_with("Bearer ")), Some(None)); |
| 370 | assert_eq!(presented_token(&HeaderMap::new()), None); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn sha_is_lowercased_and_must_be_full() { |
| 375 | assert_eq!(normalize_sha(&"AB".repeat(20)), Some("ab".repeat(20))); |
| 376 | assert_eq!(normalize_sha("abc123"), None); |
| 377 | assert_eq!(normalize_sha(&"z".repeat(40)), None); |
| 378 | } |
| 379 | } |