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