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