forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiB197fa34Tahinli1 month ago68 commits

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