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