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