forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB0a2c24cTahinli1 month ago179 commits

statuses.rs459 lines, 15.3 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 /// Every refused write shares one repo fixture, and each case is labelled in its message.
344 #[tokio::test]
345 async fn refused_writes_return_their_status() {
346 let s = setup(Visibility::Public).await;
347 let owner = s
348 .fx
349 .store
350 .user_by_username(OWNER)
351 .await
352 .unwrap()
353 .expect("owner");
354 let session = generate_token();
355 crate::test_support::create_session(&s.fx.store, &owner.id, &session, "csrf-value").await;
356 let cookie = format!("__Host-{SESSION_COOKIE}={session}");
357 let unscoped = bearer(&token_for(&s.fx.store, &owner.id, &[]).await);
358 let writer = bearer(&s.writer_token);
359 let reader = bearer(&s.reader_token);
360 let report = report_uri(&s.sha);
361 let bad_sha = report_uri("abc123");
362 let missing = report_uri(&"0".repeat(40));
363 // (case, uri, auth, cookie, body, expected status, expects a JSON error body)
364 type Case<'a> = (&'a str, &'a str, Option<&'a str>, Option<&'a str>, Option<&'a str>, u16, bool);
365 let cases: [Case<'_>; 10] = [
366 ("read-only token", report.as_str(), Some(reader.as_str()), None, Some(SUCCESS), 403, true),
367 ("anonymous", report.as_str(), None, None, Some(SUCCESS), 401, true),
368 ("bad token", report.as_str(), Some("Bearer forge_not_a_real_token"), None, Some(SUCCESS), 401, false),
369 ("session cookie alone", report.as_str(), None, Some(cookie.as_str()), Some(SUCCESS), 401, false),
370 ("token without repo scope", report.as_str(), Some(unscoped.as_str()), None, Some(SUCCESS), 403, false),
371 ("sha too short", bad_sha.as_str(), Some(writer.as_str()), None, Some(SUCCESS), 422, false),
372 ("unknown state", report.as_str(), Some(writer.as_str()), None, Some(r#"{"state":"maybe"}"#), 422, false),
373 ("malformed json", report.as_str(), Some(writer.as_str()), None, Some("{not json"), 400, false),
374 ("javascript target url", report.as_str(), Some(writer.as_str()), None, Some(r#"{"state":"success","target_url":"javascript:alert(1)"}"#), 422, false),
375 ("unknown commit", missing.as_str(), Some(writer.as_str()), None, Some(SUCCESS), 404, false),
376 ];
377 for (name, uri, auth, cookie, body, want, error_body) in cases {
378 let (status, json) = send(&s.fx.router, "POST", uri, auth, cookie, body).await;
379 assert_eq!(status, want, "case {name}: {json}");
380 if error_body {
381 assert!(json["error"].is_string(), "case {name}");
382 }
383 }
384 }
385
386 #[tokio::test]
387 async fn get_combines_states_and_is_public_without_token() {
388 let s = setup(Visibility::Public).await;
389 let auth = bearer(&s.writer_token);
390 for body in [
391 r#"{"state":"success","context":"unit"}"#,
392 r#"{"state":"pending","context":"lint"}"#,
393 ] {
394 let (status, _) = send(
395 &s.fx.router,
396 "POST",
397 &report_uri(&s.sha),
398 Some(&auth),
399 None,
400 Some(body),
401 )
402 .await;
403 assert_eq!(status, 201);
404 }
405 let (status, body) = send(&s.fx.router, "GET", &list_uri(&s.sha), None, None, None).await;
406 assert_eq!(status, 200);
407 assert_eq!(body["state"], "pending");
408 assert_eq!(body["statuses"].as_array().map(Vec::len), Some(2));
409
410 // Nothing reported on the root commit yet.
411 let (status, body) = send(
412 &s.fx.router,
413 "GET",
414 &list_uri(&"0".repeat(40)),
415 None,
416 None,
417 None,
418 )
419 .await;
420 assert_eq!(status, 404, "{body}");
421 }
422
423 #[tokio::test]
424 async fn private_repo_hides_from_strangers() {
425 let s = setup(Visibility::Private).await;
426 let (status, _) = send(&s.fx.router, "GET", &list_uri(&s.sha), None, None, None).await;
427 assert_eq!(status, 401);
428
429 // The reader can read the private repo.
430 let (status, _) = send(
431 &s.fx.router,
432 "GET",
433 &list_uri(&s.sha),
434 Some(&bearer(&s.reader_token)),
435 None,
436 None,
437 )
438 .await;
439 assert_eq!(status, 200);
440
441 // A signed-in user with no access sees a 404.
442 let stranger =
443 s.fx.store
444 .create_user("carol", None, "not-a-real-hash", false)
445 .await
446 .unwrap();
447 let raw = token_for(&s.fx.store, &stranger.id, &["repo"]).await;
448 let (status, _) = send(
449 &s.fx.router,
450 "GET",
451 &list_uri(&s.sha),
452 Some(&bearer(&raw)),
453 None,
454 None,
455 )
456 .await;
457 assert_eq!(status, 404);
458 }
459}