flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/api/src/lib.rs

706 lines28,604 bytesCodeBlame
1//! The public API: REST at api.g1t.sh and the MCP server at mcp.g1t.sh.
2//!
3//! One Worker, two hostnames. Both are thin adapters over the same
4//! operations (see [`operations::Op`]), which call the services that own
5//! the data. This Worker holds none.
6
7mod audit;
8mod blobs;
9mod mcp;
10mod oauth;
11mod openapi;
12mod operations;
13mod renamed;
14#[cfg(test)]
15mod responses;
16mod rest;
17
18use g1t_contracts::billing::FinishRunArgs;
19use g1t_contracts::identity::{
20 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
21};
22use g1t_contracts::work::{
23 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
24 ReportQueueArgs, ReportReviewArgs,
25};
26use g1t_contracts::identity::AgentScope;
27use g1t_contracts::{Failure, FailureCode, Outcome, PrincipalKind, Viewer};
28use g1t_kit::wire;
29use serde_json::{Value, json};
30use worker::{Context, Env, Method, Request, Response, Result, event};
31
32use operations::Services;
33
34const API: &str = "https://api.g1t.sh";
35
36fn method_name(method: Method) -> &'static str {
37 match method {
38 Method::Get => "GET",
39 Method::Post => "POST",
40 Method::Patch => "PATCH",
41 Method::Put => "PUT",
42 Method::Delete => "DELETE",
43 Method::Options => "OPTIONS",
44 Method::Head => "HEAD",
45 _ => "OTHER",
46 }
47}
48
49/// A JSON response. Every body the API sends has its keys in `snake_case`;
50/// the contracts it passes through are `camelCase`, so they are converted
51/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
52/// the MCP protocol's own envelope keep the spelling their standards use.
53pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
54 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
55}
56
57/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
58/// workflow file, GitHub's contexts and event, and where to check out, all
59/// passed through as they are.
60const JOB_SPEC_AS_GIVEN: &[&str] = &[
61 "spec", "workflow", "github", "event", "contexts", "checkout",
62];
63
64/// An error in the shape every endpoint uses.
65fn failure(failure: &Failure) -> Result<Response> {
66 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
67}
68
69fn fail(code: FailureCode, message: &str) -> Result<Response> {
70 failure(&Failure {
71 code,
72 message: message.to_owned(),
73 })
74}
75
76/// A request body as JSON. An empty or malformed body is no input.
77async fn json_body(request: &mut Request) -> Value {
78 request.json().await.unwrap_or(Value::Null)
79}
80
81/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
82/// an anonymous viewer; a wrong one is refused, so that a typo does not
83/// silently look signed out.
84async fn authenticate(
85 request: &Request,
86 services: &Services,
87) -> Result<std::result::Result<Viewer, Response>> {
88 let header = request.headers().get("authorization")?.unwrap_or_default();
89 let token = match header.split_once(' ') {
90 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
91 token.trim()
92 }
93 _ => return Ok(Ok(None)),
94 };
95 let viewer: Viewer = g1t_kit::call(
96 &services.identity,
97 "user_for_access_token",
98 &TokenArgs {
99 token: token.to_owned(),
100 },
101 )
102 .await?;
103 if viewer.is_some() {
104 return Ok(Ok(viewer));
105 }
106 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
107 // Tells an MCP client where to sign in again.
108 response.headers_mut().set(
109 "www-authenticate",
110 &format!("{}, error=\"invalid_token\"", oauth::MCP_CHALLENGE),
111 )?;
112 Ok(Err(response))
113}
114
115/// Where everything is, for someone or something exploring the API.
116fn index() -> Value {
117 let repo = format!("{API}/repos/{{owner}}/{{name}}");
118 json!({
119 "documentation_url": "https://docs.g1t.sh/reference/api/",
120 "openapi_url": format!("{API}/openapi.json"),
121 "mcp_url": "https://mcp.g1t.sh",
122 "current_user_url": format!("{API}/user"),
123 "workspaces_url": format!("{API}/workspaces"),
124 "repositories_url": format!("{API}/repos{{?q}}"),
125 "repository_url": repo,
126 "repository_events_url": format!("{repo}/events{{?before}}"),
127 "labels_url": format!("{repo}/labels"),
128 "issues_url": format!("{repo}/issues{{?state,label}}"),
129 "issue_url": format!("{repo}/issues/{{number}}"),
130 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
131 "pulls_url": format!("{repo}/pulls{{?state}}"),
132 "pull_url": format!("{repo}/pulls/{{number}}"),
133 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
134 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
135 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
136 "device_code_url": format!("{API}/device/code"),
137 "device_token_url": format!("{API}/device/token"),
138 "oauth_metadata_url": format!("{API}/.well-known/oauth-authorization-server"),
139 "git_url": "https://g1t.sh/{owner}/{name}.git",
140 "integrations_url": format!("{API}/workspaces/{{workspace}}/integrations"),
141 "context_url": format!("{repo}/context{{?reference}}"),
142 "import_issue_url": format!("{repo}/issues/import"),
143 "hooks_url": format!("{API}/hooks/{{integration}}"),
144 })
145}
146
147// Signing in from a tool. Accounts are created, and passwords typed, only
148// in a browser; a tool gets its token by having a person approve a code.
149
150/// Passes a request from an outside system to its connection, as it came:
151/// its signature covers the exact bytes of the body.
152async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
153 let headers: std::collections::HashMap<String, String> = request
154 .headers()
155 .entries()
156 .map(|(name, value)| (name.to_lowercase(), value))
157 .collect();
158 let body = request.text().await.unwrap_or_default();
159 if body.len() > 1_000_000 {
160 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
161 }
162 let received: g1t_contracts::integrations::Received = g1t_kit::call(
163 &services.integrations,
164 "receive",
165 &json!({ "id": id, "headers": headers, "body": body }),
166 )
167 .await?;
168 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
169}
170
171async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
172 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
173 let payload = request.text().await.unwrap_or_default();
174 if payload.len() > 1_000_000 || signature.is_empty() {
175 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
176 }
177 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
178 &env.service("BILLING")?,
179 "stripe_webhook",
180 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
181 )
182 .await?;
183 // A refusal is a 400, so Stripe shows it as failed; anything handled,
184 // or already handled, is a 200, so Stripe stops sending it.
185 Ok(match handled {
186 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
187 g1t_contracts::Outcome::Fail(failure) => {
188 reply(&json!({ "message": failure.message }))?.with_status(400)
189 }
190 })
191}
192
193async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
194 let body = json_body(request).await;
195 let started: DeviceStart = g1t_kit::call(
196 &services.identity,
197 "device_start",
198 &DeviceStartArgs {
199 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
200 },
201 )
202 .await?;
203 reply(&json!({
204 "device_code": started.device_code,
205 "user_code": started.user_code,
206 "verification_uri": "https://g1t.sh/device",
207 "verification_uri_complete": format!("https://g1t.sh/device?code={}", started.user_code),
208 "expires_in": started.expires_in,
209 "interval": started.interval,
210 }))
211}
212
213async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
214 let body = json_body(request).await;
215 let claim: DeviceClaim = g1t_kit::call(
216 &services.identity,
217 "device_claim",
218 &DeviceClaimArgs {
219 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
220 },
221 )
222 .await?;
223 reply(&match claim {
224 DeviceClaim::Approved { token, user } => json!({
225 "status": "approved",
226 "token": token,
227 "username": user.username,
228 "verified": user.verified,
229 }),
230 DeviceClaim::Pending => json!({ "status": "pending" }),
231 DeviceClaim::Denied => json!({ "status": "denied" }),
232 DeviceClaim::Expired => json!({ "status": "expired" }),
233 })
234}
235
236/// A sandbox reporting on its run of a pull request's acceptance checks.
237/// The run's own token, in the body, is the credential: it was given to
238/// that sandbox and to nothing else.
239async fn report_checks(
240 request: &mut Request,
241 services: &Services,
242 run_id: &str,
243) -> Result<Response> {
244 let body = json_body(request).await;
245 let reported: Outcome<CheckRun> = g1t_kit::call(
246 &services.work,
247 "report_checks",
248 &ReportChecksArgs {
249 run_id: run_id.to_owned(),
250 token: body["token"].as_str().unwrap_or_default().to_owned(),
251 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
252 error: body["error"].as_str().map(str::to_owned),
253 skip: false,
254 },
255 )
256 .await?;
257 match reported {
258 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
259 Outcome::Fail(refused) => failure(&refused),
260 }
261}
262
263/// A sandbox reporting one tested state of a merge queue. As with checks,
264/// the entry's own token is the credential.
265async fn report_queue(
266 request: &mut Request,
267 services: &Services,
268 entry_id: &str,
269) -> Result<Response> {
270 let body = json_body(request).await;
271 let reported: Outcome<QueueState> = g1t_kit::call(
272 &services.work,
273 "report_queue",
274 &ReportQueueArgs {
275 entry_id: entry_id.to_owned(),
276 token: body["token"].as_str().unwrap_or_default().to_owned(),
277 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
278 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
279 error: body["error"].as_str().map(str::to_owned),
280 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
281 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
282 },
283 )
284 .await?;
285 match reported {
286 Outcome::Ok(state) => reply(&json!({ "state": state })),
287 Outcome::Fail(refused) => failure(&refused),
288 }
289}
290
291/// A sandbox reporting whether a pull request merges cleanly. As with
292/// checks, the probe's own token is the credential.
293async fn report_mergecheck(
294 request: &mut Request,
295 services: &Services,
296 pull_id: &str,
297) -> Result<Response> {
298 let body = json_body(request).await;
299 let reported: Outcome<Mergeable> = g1t_kit::call(
300 &services.work,
301 "report_mergecheck",
302 &ReportMergecheckArgs {
303 pull_id: pull_id.to_owned(),
304 token: body["token"].as_str().unwrap_or_default().to_owned(),
305 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
306 error: body["error"].as_str().map(str::to_owned),
307 },
308 )
309 .await?;
310 match reported {
311 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
312 Outcome::Fail(refused) => failure(&refused),
313 }
314}
315
316/// A sandbox reporting the review its agent wrote. As with checks, the
317/// run's own token is the credential.
318async fn report_review(
319 request: &mut Request,
320 services: &Services,
321 run_id: &str,
322) -> Result<Response> {
323 let body = json_body(request).await;
324 let reported: Outcome<bool> = g1t_kit::call(
325 &services.work,
326 "report_review",
327 &ReportReviewArgs {
328 run_id: run_id.to_owned(),
329 token: body["token"].as_str().unwrap_or_default().to_owned(),
330 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
331 body: body["body"].as_str().unwrap_or_default().to_owned(),
332 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
333 model: body["model"].as_str().map(str::to_owned),
334 error: body["error"].as_str().map(str::to_owned),
335 },
336 )
337 .await?;
338 match reported {
339 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
340 Outcome::Fail(refused) => failure(&refused),
341 }
342}
343
344/// A sandbox reporting the plan its agent wrote. As with checks, the
345/// plan's own token is the credential.
346async fn report_plan(
347 request: &mut Request,
348 services: &Services,
349 plan_id: &str,
350) -> Result<Response> {
351 let body = json_body(request).await;
352 let reported: Outcome<bool> = g1t_kit::call(
353 &services.work,
354 "report_plan",
355 &ReportPlanArgs {
356 plan_id: plan_id.to_owned(),
357 token: body["token"].as_str().unwrap_or_default().to_owned(),
358 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
359 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
360 error: body["error"].as_str().map(str::to_owned),
361 },
362 )
363 .await?;
364 match reported {
365 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
366 Outcome::Fail(refused) => failure(&refused),
367 }
368}
369
370/// A sandbox reporting what its agent's run cost, so that the workspace
371/// it worked for is charged. As with checks, the run's own token is the
372/// credential.
373async fn report_usage(
374 request: &mut Request,
375 services: &Services,
376 run_id: &str,
377) -> Result<Response> {
378 let body = json_body(request).await;
379 let charged: Outcome<bool> = g1t_kit::call(
380 &services.billing,
381 "finish_run",
382 &FinishRunArgs {
383 run_id: run_id.to_owned(),
384 token: body["token"].as_str().unwrap_or_default().to_owned(),
385 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
386 turns: body["turns"].as_u64().unwrap_or_default() as u32,
387 },
388 )
389 .await?;
390 match charged {
391 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
392 Outcome::Fail(refused) => failure(&refused),
393 }
394}
395
396async fn respond(mut request: Request, env: &Env) -> Result<Response> {
397 let method = method_name(request.method());
398 if method == "OPTIONS" {
399 return Ok(Response::empty()?.with_status(204));
400 }
401 let url = request.url()?;
402 // Paths carry no version. An earlier form began with `/v1`, which is
403 // still accepted so that nothing already written against it breaks.
404 let path = match url.path().strip_prefix("/v1") {
405 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
406 _ => url.path().to_owned(),
407 };
408 let on_mcp = url.host_str().is_some_and(|host| host.starts_with("mcp."));
409 let mut services = Services::new(env)?;
410
411 // Stripe reporting to billing. Signed with the secret of the endpoint
412 // billing registered; the body goes through exactly as received, since
413 // the signature covers its bytes.
414 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
415 return receive_stripe(&mut request, env).await;
416 }
417
418 // Outside systems reporting to a connection. They sign what they send
419 // with the connection's own secret, which is not a g1t token, so this
420 // comes before anything that would read one.
421 if method == "POST" && !on_mcp
422 && let Some(id) = path.strip_prefix("/hooks/").filter(|id| !id.is_empty() && !id.contains('/')) {
423 return receive_hook(&mut request, &services, id).await;
424 }
425
426 // A sandbox building a deployment, reporting with its build's token,
427 // which is not a g1t token. The body goes through as it is: it can
428 // carry a Worker's bundled code.
429 if method == "POST" && !on_mcp
430 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
431 {
432 let target = format!("https://deployments/jobs/{rest}");
433 let body = request.bytes().await?;
434 let headers = worker::Headers::new();
435 headers.set("content-type", "application/json")?;
436 let mut init = worker::RequestInit::new();
437 init.with_method(Method::Post)
438 .with_headers(headers)
439 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
440 let mut answer = env
441 .service("DEPLOYMENTS")?
442 .fetch_request(Request::new_with_init(&target, &init)?)
443 .await?;
444 // A fresh response: a fetched one's headers cannot be changed, and
445 // every response gets the API's own on the way out.
446 let status = answer.status_code();
447 let bytes = answer.bytes().await?;
448 let bytes = match serde_json::from_slice::<Value>(&bytes) {
449 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
450 Err(_) => bytes,
451 };
452 return Ok(Response::from_bytes(bytes)?
453 .with_status(status)
454 .with_headers({
455 let headers = worker::Headers::new();
456 headers.set("content-type", "application/json")?;
457 headers
458 }));
459 }
460
461 // A sandbox's artifacts and cache, with its job's token, which is not a
462 // g1t token either.
463 if !on_mcp
464 && let Some(rest) = path.strip_prefix("/actions/jobs/")
465 && (rest.contains("/artifacts") || rest.ends_with("/cache"))
466 {
467 let rest = rest.to_owned();
468 return blobs::for_job(request, env, &services, method, &rest).await;
469 }
470
471 let viewer = match authenticate(&request, &services).await? {
472 Ok(viewer) => viewer,
473 Err(refused) => return Ok(refused),
474 };
475 services.audit = audit::AuditContext::of(&request, on_mcp);
476 // An agent's token: what it may do comes with it, on the composite
477 // identity identity resolved it to.
478 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
479 services.scope = Some(acting.scope.clone());
480 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
481 let header = request.headers().get("authorization")?.unwrap_or_default();
482 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
483 let scope: Option<AgentScope> = g1t_kit::call(
484 &services.identity,
485 "agent_scope",
486 &TokenArgs {
487 token: token.to_owned(),
488 },
489 )
490 .await?;
491 // A scope is what lets an agent's token do anything at all.
492 let Some(scope) = scope else {
493 return fail(FailureCode::Unauthenticated, "Invalid access token.");
494 };
495 services.scope = Some(scope);
496 }
497 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
498 return Ok(response);
499 }
500 if on_mcp {
501 return mcp::handle(request, &services, &viewer).await;
502 }
503
504 match (method, path.trim_end_matches('/')) {
505 ("GET", "") => return reply(&index()),
506 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
507 // A run's artifacts: listed, or one downloaded.
508 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
509 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
510 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
511 return match rest {
512 [] => {
513 let seen: Outcome<Value> = g1t_kit::call(
514 &services.actions,
515 "run",
516 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
517 )
518 .await?;
519 match seen {
520 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
521 Outcome::Fail(refused) => failure(&refused),
522 }
523 }
524 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
525 _ => fail(FailureCode::NotFound, "No such endpoint."),
526 };
527 }
528 }
529 ("POST", "/device/code") => return device_code(&mut request, &services).await,
530 ("POST", "/device/token") => return device_token(&mut request, &services).await,
531 // Where a pull request lives, for a tool that knows only its fork.
532 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
533 let located: Outcome<Value> = g1t_kit::call(
534 &services.work,
535 "locate_pull",
536 &json!({ "id": &path[7..], "viewer": viewer }),
537 )
538 .await?;
539 return match located {
540 Outcome::Ok(value) => reply(&value),
541 Outcome::Fail(refused) => failure(&refused),
542 };
543 }
544 ("POST", path) if path.starts_with("/mergechecks/") => {
545 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
546 return report_mergecheck(&mut request, &services, &pull_id).await;
547 }
548 ("POST", path) if path.starts_with("/queue/") => {
549 let entry_id = path.trim_start_matches("/queue/").to_owned();
550 return report_queue(&mut request, &services, &entry_id).await;
551 }
552 // A sandbox running a GitHub Actions job: fetching the job, and
553 // reporting how it goes. The job's own token is the credential.
554 ("POST", path) if path.starts_with("/actions/jobs/") => {
555 let rest = path.trim_start_matches("/actions/jobs/");
556 let (job, method) = match rest.strip_suffix("/spec") {
557 Some(job) => (job.to_owned(), "job_spec"),
558 None => (rest.to_owned(), "job_report"),
559 };
560 let body = json_body(&mut request).await;
561 let answered: Outcome<Value> = g1t_kit::call(
562 &services.actions,
563 method,
564 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
565 )
566 .await?;
567 return match answered {
568 // A job's spec is the workflow and its contexts as GitHub
569 // has them; only g1t's own keys around them are converted.
570 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
571 Outcome::Fail(refused) => failure(&refused),
572 };
573 }
574 // A sandbox reporting its agent run's steps, cost and end. As with
575 // checks, the run's own token, in the body, is the credential.
576 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
577 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
578 let mut body = json_body(&mut request).await;
579 if !body.is_object() {
580 body = json!({});
581 }
582 body["runId"] = json!(run_id);
583 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
584 return match reported {
585 Outcome::Ok(status) => reply(&json!({ "status": status })),
586 Outcome::Fail(refused) => failure(&refused),
587 };
588 }
589 // What a run's agent learned, as memory candidates; the same token.
590 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
591 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
592 let body = json_body(&mut request).await;
593 let learned = json!({
594 "runId": run_id,
595 "token": body["token"].as_str().unwrap_or_default(),
596 "items": body["items"].as_array().cloned().unwrap_or_default(),
597 });
598 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
599 return match captured {
600 Outcome::Ok(captured) => reply(&captured),
601 Outcome::Fail(refused) => failure(&refused),
602 };
603 }
604 ("POST", path) if path.starts_with("/checks/") => {
605 let run_id = path.trim_start_matches("/checks/").to_owned();
606 return report_checks(&mut request, &services, &run_id).await;
607 }
608 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
609 let run_id = path
610 .trim_start_matches("/runs/")
611 .trim_end_matches("/usage")
612 .to_owned();
613 return report_usage(&mut request, &services, &run_id).await;
614 }
615 ("POST", path) if path.starts_with("/plans/") => {
616 let plan_id = path.trim_start_matches("/plans/").to_owned();
617 return report_plan(&mut request, &services, &plan_id).await;
618 }
619 ("POST", path) if path.starts_with("/reviews/") => {
620 let run_id = path.trim_start_matches("/reviews/").to_owned();
621 return report_review(&mut request, &services, &run_id).await;
622 }
623 _ => {}
624 }
625
626 let query: Vec<(String, String)> = url
627 .query_pairs()
628 .map(|(name, value)| (name.into_owned(), value.into_owned()))
629 .collect();
630 let body = if method == "GET" {
631 Value::Null
632 } else {
633 snake_case_keys(json_body(&mut request).await)
634 };
635 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
636 return fail(FailureCode::NotFound, "No such endpoint.");
637 };
638 match audit::run(route.op, &services, &viewer, &input).await? {
639 Outcome::Ok(value) => reply(&value),
640 Outcome::Fail(refused) => failure(&refused),
641 }
642}
643
644/// Request bodies take the same keys as the MCP tools, `snake_case`, as
645/// responses use; the `camelCase` spelling is accepted too.
646fn snake_case_keys(body: Value) -> Value {
647 let Value::Object(fields) = body else {
648 return body;
649 };
650 let mut out = serde_json::Map::new();
651 for (key, value) in fields {
652 let mut snake = String::with_capacity(key.len() + 4);
653 for c in key.chars() {
654 if c.is_ascii_uppercase() {
655 snake.push('_');
656 snake.push(c.to_ascii_lowercase());
657 } else {
658 snake.push(c);
659 }
660 }
661 // A key given in both spellings keeps the snake_case one.
662 if snake != key && out.contains_key(&snake) {
663 continue;
664 }
665 out.insert(snake, value);
666 }
667 Value::Object(out)
668}
669
670#[cfg(test)]
671mod tests {
672 use super::snake_case_keys;
673 use serde_json::json;
674
675 #[test]
676 fn camel_case_keys_are_accepted() {
677 assert_eq!(
678 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
679 json!({ "count_agent_approvals": false, "title": "x" })
680 );
681 }
682
683 #[test]
684 fn snake_case_wins_when_both_are_given() {
685 assert_eq!(
686 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
687 json!({ "keep_issue_open": true })
688 );
689 }
690}
691
692// The API is called from browsers too: the reference's explorer, and apps
693// built on g1t. It carries no cookies, so any origin may call it.
694#[event(fetch)]
695async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
696 let mut response = respond(request, &env).await?;
697 let headers = response.headers_mut();
698 headers.set("access-control-allow-origin", "*")?;
699 headers.set(
700 "access-control-allow-headers",
701 "authorization, content-type",
702 )?;
703 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
704 headers.set("access-control-expose-headers", "www-authenticate")?;
705 Ok(response)
706}