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