Skip to content

g1t/apps/api/src/lib.rs

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