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