Skip to content

g1t/apps/api/src/lib.rs

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