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