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.

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