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.

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