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