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 | use forge_core::Action; |
| 2 | use forge_core::store::commit_status::{CommitStatus, DEFAULT_CONTEXT, StatusState, combine}; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::{Value, json}; |
| 5 | use topcoat::context::{Cx, context}; |
| 6 | use topcoat::router::request::headers; |
| 7 | use topcoat::router::response::Response; |
| 8 | use topcoat::router::{Body, StatusCode, path_param, route}; |
| 9 | |
| 10 | use crate::api; |
| 11 | use crate::client_ip::client_ip; |
| 12 | use crate::state::AppState; |
| 13 | |
| 14 | path_param!(owner); |
| 15 | path_param!(repo); |
| 16 | path_param!(sha); |
| 17 | |
| 18 | const MAX_BODY_BYTES: usize = 16 * 1024; |
| 19 | |
| 20 | #[derive(Deserialize)] |
| 21 | struct ReportBody { |
| 22 | state: String, |
| 23 | context: Option<String>, |
| 24 | description: Option<String>, |
| 25 | target_url: Option<String>, |
| 26 | } |
| 27 | |
| 28 | #[route(POST "/api/v1/repos/{owner}/{repo}/statuses/{sha}")] |
| 29 | async fn report_status(cx: &Cx, body: Body) -> topcoat::Result<Response> { |
| 30 | let state = context::<AppState>(cx); |
| 31 | let (repo, user) = |
| 32 | match api::load_writer(state, client_ip(cx), headers(cx), owner(cx), repo(cx)).await { |
| 33 | Ok(found) => found, |
| 34 | Err(res) => return Ok(*res), |
| 35 | }; |
| 36 | let Some(sha) = api::normalize_sha(sha(cx)) else { |
| 37 | return Ok(not_a_full_sha()); |
| 38 | }; |
| 39 | let report: ReportBody = match api::json_body(body, MAX_BODY_BYTES).await { |
| 40 | Ok(report) => report, |
| 41 | Err(res) => return Ok(*res), |
| 42 | }; |
| 43 | let Ok(status_state) = report.state.parse::<StatusState>() else { |
| 44 | return Ok(api::error( |
| 45 | StatusCode::UNPROCESSABLE_ENTITY, |
| 46 | "state must be one of pending, success, failure, error", |
| 47 | )); |
| 48 | }; |
| 49 | let path = match api::repo_dir(state, &repo) { |
| 50 | Ok(path) => path, |
| 51 | Err(res) => return Ok(*res), |
| 52 | }; |
| 53 | match api::commit_exists(path, sha.clone()).await { |
| 54 | Ok(true) => {} |
| 55 | Ok(false) => return Ok(commit_not_found()), |
| 56 | Err(res) => return Ok(*res), |
| 57 | } |
| 58 | |
| 59 | let context = report.context.unwrap_or_else(|| DEFAULT_CONTEXT.to_owned()); |
| 60 | let saved = match state |
| 61 | .store |
| 62 | .set_status( |
| 63 | &repo.id, |
| 64 | &sha, |
| 65 | &context, |
| 66 | status_state, |
| 67 | report.description.as_deref(), |
| 68 | report.target_url.as_deref(), |
| 69 | &user.id, |
| 70 | ) |
| 71 | .await |
| 72 | { |
| 73 | Ok(saved) => saved, |
| 74 | Err(forge_core::Error::Invalid(message)) => { |
| 75 | return Ok(api::error(StatusCode::UNPROCESSABLE_ENTITY, &message)); |
| 76 | } |
| 77 | Err(e) => return Ok(*api::internal(e)), |
| 78 | }; |
| 79 | state |
| 80 | .live |
| 81 | .bump(&crate::live::Topic::CommitStatuses(repo.id.clone())); |
| 82 | crate::automerge::on_status(state, &repo.id, &sha).await; |
| 83 | crate::merge_queue::on_status(state, &repo, &sha).await; |
| 84 | Ok(api::json(StatusCode::CREATED, &status_json(&saved))) |
| 85 | } |
| 86 | |
| 87 | #[route(GET "/api/v1/repos/{owner}/{repo}/commits/{sha}/statuses")] |
| 88 | async fn list_statuses(cx: &Cx) -> topcoat::Result<Response> { |
| 89 | let state = context::<AppState>(cx); |
| 90 | let actor = match api::authenticate(state, client_ip(cx), headers(cx)).await { |
| 91 | Ok(actor) => actor, |
| 92 | Err(res) => return Ok(*res), |
| 93 | }; |
| 94 | let repo = match api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Read).await |
| 95 | { |
| 96 | Ok(repo) => repo, |
| 97 | Err(res) => return Ok(*res), |
| 98 | }; |
| 99 | let Some(sha) = api::normalize_sha(sha(cx)) else { |
| 100 | return Ok(not_a_full_sha()); |
| 101 | }; |
| 102 | let path = match api::repo_dir(state, &repo) { |
| 103 | Ok(path) => path, |
| 104 | Err(res) => return Ok(*res), |
| 105 | }; |
| 106 | match api::commit_exists(path, sha.clone()).await { |
| 107 | Ok(true) => {} |
| 108 | Ok(false) => return Ok(commit_not_found()), |
| 109 | Err(res) => return Ok(*res), |
| 110 | } |
| 111 | |
| 112 | let statuses = match state.store.statuses_for(&repo.id, &sha).await { |
| 113 | Ok(statuses) => statuses, |
| 114 | Err(e) => return Ok(*api::internal(e)), |
| 115 | }; |
| 116 | let combined = combine(statuses.iter().map(|status| status.state)); |
| 117 | let body = json!({ |
| 118 | "state": combined.map(StatusState::as_str), |
| 119 | "statuses": statuses.iter().map(status_json).collect::<Vec<Value>>(), |
| 120 | }); |
| 121 | Ok(api::json(StatusCode::OK, &body)) |
| 122 | } |
| 123 | |
| 124 | fn status_json(status: &CommitStatus) -> Value { |
| 125 | json!({ |
| 126 | "id": status.id, |
| 127 | "sha": status.sha, |
| 128 | "context": status.context, |
| 129 | "state": status.state.as_str(), |
| 130 | "description": status.description, |
| 131 | "target_url": status.target_url, |
| 132 | "created_at": status.created_at, |
| 133 | "updated_at": status.updated_at, |
| 134 | }) |
| 135 | } |
| 136 | |
| 137 | fn not_a_full_sha() -> Response { |
| 138 | api::error( |
| 139 | StatusCode::UNPROCESSABLE_ENTITY, |
| 140 | "sha must be a full 40 or 64 character hex commit id", |
| 141 | ) |
| 142 | } |
| 143 | |
| 144 | fn commit_not_found() -> Response { |
| 145 | api::error(StatusCode::NOT_FOUND, "commit not found") |
| 146 | } |
| 147 | |
| 148 | #[cfg(test)] |
| 149 | mod tests { |
| 150 | use forge_core::token::generate_token; |
| 151 | use forge_core::{Role, Visibility}; |
| 152 | use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE}; |
| 153 | use topcoat::router::request::Request; |
| 154 | use topcoat::router::{Body, Router, to_bytes}; |
| 155 | |
| 156 | use crate::auth::SESSION_COOKIE; |
| 157 | use crate::test_support::fixture::{Fixture, OWNER, REPO}; |
| 158 | use crate::test_support::http::{bearer, token_for}; |
| 159 | |
| 160 | async fn send( |
| 161 | router: &Router, |
| 162 | method: &str, |
| 163 | uri: &str, |
| 164 | auth: Option<&str>, |
| 165 | cookie: Option<&str>, |
| 166 | body: Option<&str>, |
| 167 | ) -> (u16, serde_json::Value) { |
| 168 | let mut builder = Request::builder().method(method).uri(uri); |
| 169 | if let Some(auth) = auth { |
| 170 | builder = builder.header(AUTHORIZATION, auth); |
| 171 | } |
| 172 | if let Some(cookie) = cookie { |
| 173 | builder = builder.header(COOKIE, cookie); |
| 174 | } |
| 175 | if body.is_some() { |
| 176 | builder = builder.header(CONTENT_TYPE, "application/json"); |
| 177 | } |
| 178 | let req = builder |
| 179 | .body(Body::from(body.unwrap_or("").to_owned())) |
| 180 | .unwrap(); |
| 181 | let res = router.handle(req).await; |
| 182 | let status = res.status().as_u16(); |
| 183 | let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); |
| 184 | let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null); |
| 185 | (status, json) |
| 186 | } |
| 187 | |
| 188 | struct Setup { |
| 189 | fx: Fixture, |
| 190 | reader_token: String, |
| 191 | writer_token: String, |
| 192 | sha: String, |
| 193 | } |
| 194 | |
| 195 | async fn setup(visibility: Visibility) -> Setup { |
| 196 | let fx = Fixture::new(visibility).await; |
| 197 | let owner = fx |
| 198 | .store |
| 199 | .user_by_username(OWNER) |
| 200 | .await |
| 201 | .unwrap() |
| 202 | .expect("owner"); |
| 203 | let repo = fx |
| 204 | .store |
| 205 | .repo_by_owner_and_name(OWNER, REPO) |
| 206 | .await |
| 207 | .unwrap() |
| 208 | .expect("repo"); |
| 209 | let reader = fx |
| 210 | .store |
| 211 | .create_user("bob", None, "not-a-real-hash", false) |
| 212 | .await |
| 213 | .unwrap(); |
| 214 | fx.store |
| 215 | .set_collaborator(&repo.id, &reader.id, Role::Read) |
| 216 | .await |
| 217 | .unwrap(); |
| 218 | let writer_token = token_for(&fx.store, &owner.id, &["repo"]).await; |
| 219 | let reader_token = token_for(&fx.store, &reader.id, &["repo"]).await; |
| 220 | Setup { |
| 221 | sha: fx.modified.clone(), |
| 222 | reader_token, |
| 223 | writer_token, |
| 224 | fx, |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | fn report_uri(sha: &str) -> String { |
| 229 | format!("/api/v1/repos/{OWNER}/{REPO}/statuses/{sha}") |
| 230 | } |
| 231 | |
| 232 | fn list_uri(sha: &str) -> String { |
| 233 | format!("/api/v1/repos/{OWNER}/{REPO}/commits/{sha}/statuses") |
| 234 | } |
| 235 | |
| 236 | const SUCCESS: &str = r#"{"state":"success","context":"ci/build","description":"all good","target_url":"https://ci.example/run/1"}"#; |
| 237 | |
| 238 | #[tokio::test] |
| 239 | async fn write_token_creates_status_with_201() { |
| 240 | let s = setup(Visibility::Public).await; |
| 241 | let (status, body) = send( |
| 242 | &s.fx.router, |
| 243 | "POST", |
| 244 | &report_uri(&s.sha), |
| 245 | Some(&bearer(&s.writer_token)), |
| 246 | None, |
| 247 | Some(SUCCESS), |
| 248 | ) |
| 249 | .await; |
| 250 | assert_eq!(status, 201, "{body}"); |
| 251 | assert_eq!(body["state"], "success"); |
| 252 | assert_eq!(body["context"], "ci/build"); |
| 253 | assert_eq!(body["sha"], s.sha.as_str()); |
| 254 | assert_eq!(body["target_url"], "https://ci.example/run/1"); |
| 255 | } |
| 256 | |
| 257 | #[tokio::test] |
| 258 | async fn context_defaults_and_latest_report_wins() { |
| 259 | let s = setup(Visibility::Public).await; |
| 260 | let auth = bearer(&s.writer_token); |
| 261 | let (status, body) = send( |
| 262 | &s.fx.router, |
| 263 | "POST", |
| 264 | &report_uri(&s.sha), |
| 265 | Some(&auth), |
| 266 | None, |
| 267 | Some(r#"{"state":"pending"}"#), |
| 268 | ) |
| 269 | .await; |
| 270 | assert_eq!(status, 201); |
| 271 | assert_eq!(body["context"], "default"); |
| 272 | |
| 273 | let (status, _) = send( |
| 274 | &s.fx.router, |
| 275 | "POST", |
| 276 | &report_uri(&s.sha), |
| 277 | Some(&auth), |
| 278 | None, |
| 279 | Some(r#"{"state":"failure"}"#), |
| 280 | ) |
| 281 | .await; |
| 282 | assert_eq!(status, 201); |
| 283 | |
| 284 | let (status, body) = send(&s.fx.router, "GET", &list_uri(&s.sha), None, None, None).await; |
| 285 | assert_eq!(status, 200); |
| 286 | assert_eq!(body["state"], "failure"); |
| 287 | assert_eq!(body["statuses"].as_array().map(Vec::len), Some(1)); |
| 288 | } |
| 289 | |
| 290 | #[tokio::test] |
| 291 | async fn refused_writes_return_their_status() { |
| 292 | let s = setup(Visibility::Public).await; |
| 293 | let owner = |
| 294 | s.fx.store |
| 295 | .user_by_username(OWNER) |
| 296 | .await |
| 297 | .unwrap() |
| 298 | .expect("owner"); |
| 299 | let session = generate_token(); |
| 300 | crate::test_support::create_session(&s.fx.store, &owner.id, &session, "csrf-value").await; |
| 301 | let cookie = format!("__Host-{SESSION_COOKIE}={session}"); |
| 302 | let unscoped = bearer(&token_for(&s.fx.store, &owner.id, &[]).await); |
| 303 | let writer = bearer(&s.writer_token); |
| 304 | let reader = bearer(&s.reader_token); |
| 305 | let report = report_uri(&s.sha); |
| 306 | let bad_sha = report_uri("abc123"); |
| 307 | let missing = report_uri(&"0".repeat(40)); |
| 308 | type Case<'a> = ( |
| 309 | &'a str, |
| 310 | &'a str, |
| 311 | Option<&'a str>, |
| 312 | Option<&'a str>, |
| 313 | Option<&'a str>, |
| 314 | u16, |
| 315 | bool, |
| 316 | ); |
| 317 | let cases: [Case<'_>; 10] = [ |
| 318 | ( |
| 319 | "read-only token", |
| 320 | report.as_str(), |
| 321 | Some(reader.as_str()), |
| 322 | None, |
| 323 | Some(SUCCESS), |
| 324 | 403, |
| 325 | true, |
| 326 | ), |
| 327 | ( |
| 328 | "anonymous", |
| 329 | report.as_str(), |
| 330 | None, |
| 331 | None, |
| 332 | Some(SUCCESS), |
| 333 | 401, |
| 334 | true, |
| 335 | ), |
| 336 | ( |
| 337 | "bad token", |
| 338 | report.as_str(), |
| 339 | Some("Bearer forge_not_a_real_token"), |
| 340 | None, |
| 341 | Some(SUCCESS), |
| 342 | 401, |
| 343 | false, |
| 344 | ), |
| 345 | ( |
| 346 | "session cookie alone", |
| 347 | report.as_str(), |
| 348 | None, |
| 349 | Some(cookie.as_str()), |
| 350 | Some(SUCCESS), |
| 351 | 401, |
| 352 | false, |
| 353 | ), |
| 354 | ( |
| 355 | "token without repo scope", |
| 356 | report.as_str(), |
| 357 | Some(unscoped.as_str()), |
| 358 | None, |
| 359 | Some(SUCCESS), |
| 360 | 403, |
| 361 | false, |
| 362 | ), |
| 363 | ( |
| 364 | "sha too short", |
| 365 | bad_sha.as_str(), |
| 366 | Some(writer.as_str()), |
| 367 | None, |
| 368 | Some(SUCCESS), |
| 369 | 422, |
| 370 | false, |
| 371 | ), |
| 372 | ( |
| 373 | "unknown state", |
| 374 | report.as_str(), |
| 375 | Some(writer.as_str()), |
| 376 | None, |
| 377 | Some(r#"{"state":"maybe"}"#), |
| 378 | 422, |
| 379 | false, |
| 380 | ), |
| 381 | ( |
| 382 | "malformed json", |
| 383 | report.as_str(), |
| 384 | Some(writer.as_str()), |
| 385 | None, |
| 386 | Some("{not json"), |
| 387 | 400, |
| 388 | false, |
| 389 | ), |
| 390 | ( |
| 391 | "javascript target url", |
| 392 | report.as_str(), |
| 393 | Some(writer.as_str()), |
| 394 | None, |
| 395 | Some(r#"{"state":"success","target_url":"javascript:alert(1)"}"#), |
| 396 | 422, |
| 397 | false, |
| 398 | ), |
| 399 | ( |
| 400 | "unknown commit", |
| 401 | missing.as_str(), |
| 402 | Some(writer.as_str()), |
| 403 | None, |
| 404 | Some(SUCCESS), |
| 405 | 404, |
| 406 | false, |
| 407 | ), |
| 408 | ]; |
| 409 | for (name, uri, auth, cookie, body, want, error_body) in cases { |
| 410 | let (status, json) = send(&s.fx.router, "POST", uri, auth, cookie, body).await; |
| 411 | assert_eq!(status, want, "case {name}: {json}"); |
| 412 | if error_body { |
| 413 | assert!(json["error"].is_string(), "case {name}"); |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | #[tokio::test] |
| 419 | async fn get_combines_states_and_is_public_without_token() { |
| 420 | let s = setup(Visibility::Public).await; |
| 421 | let auth = bearer(&s.writer_token); |
| 422 | for body in [ |
| 423 | r#"{"state":"success","context":"unit"}"#, |
| 424 | r#"{"state":"pending","context":"lint"}"#, |
| 425 | ] { |
| 426 | let (status, _) = send( |
| 427 | &s.fx.router, |
| 428 | "POST", |
| 429 | &report_uri(&s.sha), |
| 430 | Some(&auth), |
| 431 | None, |
| 432 | Some(body), |
| 433 | ) |
| 434 | .await; |
| 435 | assert_eq!(status, 201); |
| 436 | } |
| 437 | let (status, body) = send(&s.fx.router, "GET", &list_uri(&s.sha), None, None, None).await; |
| 438 | assert_eq!(status, 200); |
| 439 | assert_eq!(body["state"], "pending"); |
| 440 | assert_eq!(body["statuses"].as_array().map(Vec::len), Some(2)); |
| 441 | |
| 442 | let (status, body) = send( |
| 443 | &s.fx.router, |
| 444 | "GET", |
| 445 | &list_uri(&"0".repeat(40)), |
| 446 | None, |
| 447 | None, |
| 448 | None, |
| 449 | ) |
| 450 | .await; |
| 451 | assert_eq!(status, 404, "{body}"); |
| 452 | } |
| 453 | |
| 454 | #[tokio::test] |
| 455 | async fn private_repo_hides_from_strangers() { |
| 456 | let s = setup(Visibility::Private).await; |
| 457 | let (status, _) = send(&s.fx.router, "GET", &list_uri(&s.sha), None, None, None).await; |
| 458 | assert_eq!(status, 401); |
| 459 | |
| 460 | let (status, _) = send( |
| 461 | &s.fx.router, |
| 462 | "GET", |
| 463 | &list_uri(&s.sha), |
| 464 | Some(&bearer(&s.reader_token)), |
| 465 | None, |
| 466 | None, |
| 467 | ) |
| 468 | .await; |
| 469 | assert_eq!(status, 200); |
| 470 | |
| 471 | let stranger = |
| 472 | s.fx.store |
| 473 | .create_user("carol", None, "not-a-real-hash", false) |
| 474 | .await |
| 475 | .unwrap(); |
| 476 | let raw = token_for(&s.fx.store, &stranger.id, &["repo"]).await; |
| 477 | let (status, _) = send( |
| 478 | &s.fx.router, |
| 479 | "GET", |
| 480 | &list_uri(&s.sha), |
| 481 | Some(&bearer(&raw)), |
| 482 | None, |
| 483 | None, |
| 484 | ) |
| 485 | .await; |
| 486 | assert_eq!(status, 404); |
| 487 | } |
| 488 | } |