Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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