forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.08.8 MiBb00f3f4Tahinli1 month ago147 commits

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