Skip to content

g1t/apps/api/src/lib.rs

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