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