pr_01m47d24b0e6n91zwymwxg0vpx/apps/api/src/lib.rs
| 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 | |
| 7 | mod audit; |
| 8 | mod blobs; |
| 9 | mod mcp; |
| 10 | mod oauth; |
| 11 | mod openapi; |
| 12 | mod operations; |
| 13 | mod renamed; |
| 14 | #[cfg(test)] |
| 15 | mod responses; |
| 16 | mod rest; |
| 17 | |
| 18 | use g1t_contracts::billing::FinishRunArgs; |
| 19 | use g1t_contracts::identity::{ |
| 20 | DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs, |
| 21 | }; |
| 22 | use g1t_contracts::work::{ |
| 23 | CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs, |
| 24 | ReportQueueArgs, ReportReviewArgs, |
| 25 | }; |
| 26 | use g1t_contracts::identity::AgentScope; |
| 27 | use g1t_contracts::{Failure, FailureCode, Outcome, PrincipalKind, Viewer}; |
| 28 | use g1t_kit::wire; |
| 29 | use serde_json::{Value, json}; |
| 30 | use worker::{Context, Env, Method, Request, Response, Result, event}; |
| 31 | |
| 32 | use operations::Services; |
| 33 | |
| 34 | const API: &str = "https://api.g1t.sh"; |
| 35 | |
| 36 | fn method_name(method: Method) -> &'static str { |
| 37 | match method { |
| 38 | Method::Get => "GET", |
| 39 | Method::Post => "POST", |
| 40 | Method::Patch => "PATCH", |
| 41 | Method::Put => "PUT", |
| 42 | Method::Delete => "DELETE", |
| 43 | Method::Options => "OPTIONS", |
| 44 | Method::Head => "HEAD", |
| 45 | _ => "OTHER", |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// A JSON response. Every body the API sends has its keys in `snake_case`; |
| 50 | /// the contracts it passes through are `camelCase`, so they are converted |
| 51 | /// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and |
| 52 | /// the MCP protocol's own envelope keep the spelling their standards use. |
| 53 | pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> { |
| 54 | Response::from_json(&wire::snake_case(serde_json::to_value(value)?)) |
| 55 | } |
| 56 | |
| 57 | /// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the |
| 58 | /// workflow file, GitHub's contexts and event, and where to check out, all |
| 59 | /// passed through as they are. |
| 60 | const JOB_SPEC_AS_GIVEN: &[&str] = &[ |
| 61 | "spec", "workflow", "github", "event", "contexts", "checkout", |
| 62 | ]; |
| 63 | |
| 64 | /// An error in the shape every endpoint uses. |
| 65 | fn failure(failure: &Failure) -> Result<Response> { |
| 66 | Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status())) |
| 67 | } |
| 68 | |
| 69 | fn fail(code: FailureCode, message: &str) -> Result<Response> { |
| 70 | failure(&Failure { |
| 71 | code, |
| 72 | message: message.to_owned(), |
| 73 | }) |
| 74 | } |
| 75 | |
| 76 | /// A request body as JSON. An empty or malformed body is no input. |
| 77 | async fn json_body(request: &mut Request) -> Value { |
| 78 | request.json().await.unwrap_or(Value::Null) |
| 79 | } |
| 80 | |
| 81 | /// Who a request's `Authorization: Bearer g1t_…` names. A missing token is |
| 82 | /// an anonymous viewer; a wrong one is refused, so that a typo does not |
| 83 | /// silently look signed out. |
| 84 | async fn authenticate( |
| 85 | request: &Request, |
| 86 | services: &Services, |
| 87 | ) -> Result<std::result::Result<Viewer, Response>> { |
| 88 | let header = request.headers().get("authorization")?.unwrap_or_default(); |
| 89 | let token = match header.split_once(' ') { |
| 90 | Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => { |
| 91 | token.trim() |
| 92 | } |
| 93 | _ => return Ok(Ok(None)), |
| 94 | }; |
| 95 | let viewer: Viewer = g1t_kit::call( |
| 96 | &services.identity, |
| 97 | "user_for_access_token", |
| 98 | &TokenArgs { |
| 99 | token: token.to_owned(), |
| 100 | }, |
| 101 | ) |
| 102 | .await?; |
| 103 | if viewer.is_some() { |
| 104 | return Ok(Ok(viewer)); |
| 105 | } |
| 106 | let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?; |
| 107 | // Tells an MCP client where to sign in again. |
| 108 | response.headers_mut().set( |
| 109 | "www-authenticate", |
| 110 | &format!("{}, error=\"invalid_token\"", oauth::MCP_CHALLENGE), |
| 111 | )?; |
| 112 | Ok(Err(response)) |
| 113 | } |
| 114 | |
| 115 | /// Where everything is, for someone or something exploring the API. |
| 116 | fn index() -> Value { |
| 117 | let repo = format!("{API}/repos/{{owner}}/{{name}}"); |
| 118 | json!({ |
| 119 | "documentation_url": "https://docs.g1t.sh/reference/api/", |
| 120 | "openapi_url": format!("{API}/openapi.json"), |
| 121 | "mcp_url": "https://mcp.g1t.sh", |
| 122 | "current_user_url": format!("{API}/user"), |
| 123 | "workspaces_url": format!("{API}/workspaces"), |
| 124 | "repositories_url": format!("{API}/repos{{?q}}"), |
| 125 | "search_url": format!("{API}/search{{?q,type,page,per_page}}"), |
| 126 | "repository_url": repo, |
| 127 | "repository_events_url": format!("{repo}/events{{?before}}"), |
| 128 | "labels_url": format!("{repo}/labels"), |
| 129 | "issues_url": format!("{repo}/issues{{?state,label}}"), |
| 130 | "issue_url": format!("{repo}/issues/{{number}}"), |
| 131 | "issue_comments_url": format!("{repo}/issues/{{number}}/comments"), |
| 132 | "pulls_url": format!("{repo}/pulls{{?state}}"), |
| 133 | "pull_url": format!("{repo}/pulls/{{number}}"), |
| 134 | "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"), |
| 135 | "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"), |
| 136 | "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"), |
| 137 | "device_code_url": format!("{API}/device/code"), |
| 138 | "device_token_url": format!("{API}/device/token"), |
| 139 | "oauth_metadata_url": format!("{API}/.well-known/oauth-authorization-server"), |
| 140 | "git_url": "https://g1t.sh/{owner}/{name}.git", |
| 141 | "integrations_url": format!("{API}/workspaces/{{workspace}}/integrations"), |
| 142 | "context_url": format!("{repo}/context{{?reference}}"), |
| 143 | "import_issue_url": format!("{repo}/issues/import"), |
| 144 | "hooks_url": format!("{API}/hooks/{{integration}}"), |
| 145 | }) |
| 146 | } |
| 147 | |
| 148 | // Signing in from a tool. Accounts are created, and passwords typed, only |
| 149 | // in a browser; a tool gets its token by having a person approve a code. |
| 150 | |
| 151 | /// Passes a request from an outside system to its connection, as it came: |
| 152 | /// its signature covers the exact bytes of the body. |
| 153 | async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> { |
| 154 | let headers: std::collections::HashMap<String, String> = request |
| 155 | .headers() |
| 156 | .entries() |
| 157 | .map(|(name, value)| (name.to_lowercase(), value)) |
| 158 | .collect(); |
| 159 | let body = request.text().await.unwrap_or_default(); |
| 160 | if body.len() > 1_000_000 { |
| 161 | return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413)); |
| 162 | } |
| 163 | let received: g1t_contracts::integrations::Received = g1t_kit::call( |
| 164 | &services.integrations, |
| 165 | "receive", |
| 166 | &json!({ "id": id, "headers": headers, "body": body }), |
| 167 | ) |
| 168 | .await?; |
| 169 | Ok(reply(&json!({ "message": received.message }))?.with_status(received.status)) |
| 170 | } |
| 171 | |
| 172 | async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> { |
| 173 | let signature = request.headers().get("stripe-signature")?.unwrap_or_default(); |
| 174 | let payload = request.text().await.unwrap_or_default(); |
| 175 | if payload.len() > 1_000_000 || signature.is_empty() { |
| 176 | return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400)); |
| 177 | } |
| 178 | let handled: g1t_contracts::Outcome<bool> = g1t_kit::call( |
| 179 | &env.service("BILLING")?, |
| 180 | "stripe_webhook", |
| 181 | &g1t_contracts::billing::StripeWebhookArgs { payload, signature }, |
| 182 | ) |
| 183 | .await?; |
| 184 | // A refusal is a 400, so Stripe shows it as failed; anything handled, |
| 185 | // or already handled, is a 200, so Stripe stops sending it. |
| 186 | Ok(match handled { |
| 187 | g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?, |
| 188 | g1t_contracts::Outcome::Fail(failure) => { |
| 189 | reply(&json!({ "message": failure.message }))?.with_status(400) |
| 190 | } |
| 191 | }) |
| 192 | } |
| 193 | |
| 194 | async fn device_code(request: &mut Request, services: &Services) -> Result<Response> { |
| 195 | let body = json_body(request).await; |
| 196 | let started: DeviceStart = g1t_kit::call( |
| 197 | &services.identity, |
| 198 | "device_start", |
| 199 | &DeviceStartArgs { |
| 200 | client_name: body["client_name"].as_str().unwrap_or_default().to_owned(), |
| 201 | }, |
| 202 | ) |
| 203 | .await?; |
| 204 | reply(&json!({ |
| 205 | "device_code": started.device_code, |
| 206 | "user_code": started.user_code, |
| 207 | "verification_uri": "https://g1t.sh/device", |
| 208 | "verification_uri_complete": format!("https://g1t.sh/device?code={}", started.user_code), |
| 209 | "expires_in": started.expires_in, |
| 210 | "interval": started.interval, |
| 211 | })) |
| 212 | } |
| 213 | |
| 214 | async fn device_token(request: &mut Request, services: &Services) -> Result<Response> { |
| 215 | let body = json_body(request).await; |
| 216 | let claim: DeviceClaim = g1t_kit::call( |
| 217 | &services.identity, |
| 218 | "device_claim", |
| 219 | &DeviceClaimArgs { |
| 220 | device_code: body["device_code"].as_str().unwrap_or_default().to_owned(), |
| 221 | }, |
| 222 | ) |
| 223 | .await?; |
| 224 | reply(&match claim { |
| 225 | DeviceClaim::Approved { token, user } => json!({ |
| 226 | "status": "approved", |
| 227 | "token": token, |
| 228 | "username": user.username, |
| 229 | "verified": user.verified, |
| 230 | }), |
| 231 | DeviceClaim::Pending => json!({ "status": "pending" }), |
| 232 | DeviceClaim::Denied => json!({ "status": "denied" }), |
| 233 | DeviceClaim::Expired => json!({ "status": "expired" }), |
| 234 | }) |
| 235 | } |
| 236 | |
| 237 | /// A sandbox reporting on its run of a pull request's acceptance checks. |
| 238 | /// The run's own token, in the body, is the credential: it was given to |
| 239 | /// that sandbox and to nothing else. |
| 240 | async fn report_checks( |
| 241 | request: &mut Request, |
| 242 | services: &Services, |
| 243 | run_id: &str, |
| 244 | ) -> Result<Response> { |
| 245 | let body = json_body(request).await; |
| 246 | let reported: Outcome<CheckRun> = g1t_kit::call( |
| 247 | &services.work, |
| 248 | "report_checks", |
| 249 | &ReportChecksArgs { |
| 250 | run_id: run_id.to_owned(), |
| 251 | token: body["token"].as_str().unwrap_or_default().to_owned(), |
| 252 | results: serde_json::from_value(body["results"].clone()).unwrap_or_default(), |
| 253 | error: body["error"].as_str().map(str::to_owned), |
| 254 | skip: false, |
| 255 | }, |
| 256 | ) |
| 257 | .await?; |
| 258 | match reported { |
| 259 | Outcome::Ok(run) => reply(&json!({ "status": run.status })), |
| 260 | Outcome::Fail(refused) => failure(&refused), |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// A sandbox reporting one tested state of a merge queue. As with checks, |
| 265 | /// the entry's own token is the credential. |
| 266 | async fn report_queue( |
| 267 | request: &mut Request, |
| 268 | services: &Services, |
| 269 | entry_id: &str, |
| 270 | ) -> Result<Response> { |
| 271 | let body = json_body(request).await; |
| 272 | let reported: Outcome<QueueState> = g1t_kit::call( |
| 273 | &services.work, |
| 274 | "report_queue", |
| 275 | &ReportQueueArgs { |
| 276 | entry_id: entry_id.to_owned(), |
| 277 | token: body["token"].as_str().unwrap_or_default().to_owned(), |
| 278 | combined_commit: body["combinedCommit"].as_str().map(str::to_owned), |
| 279 | results: serde_json::from_value(body["results"].clone()).unwrap_or_default(), |
| 280 | error: body["error"].as_str().map(str::to_owned), |
| 281 | conflict_with: body["conflictWith"].as_u64().map(|n| n as u32), |
| 282 | conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(), |
| 283 | }, |
| 284 | ) |
| 285 | .await?; |
| 286 | match reported { |
| 287 | Outcome::Ok(state) => reply(&json!({ "state": state })), |
| 288 | Outcome::Fail(refused) => failure(&refused), |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | /// A sandbox reporting whether a pull request merges cleanly. As with |
| 293 | /// checks, the probe's own token is the credential. |
| 294 | async fn report_mergecheck( |
| 295 | request: &mut Request, |
| 296 | services: &Services, |
| 297 | pull_id: &str, |
| 298 | ) -> Result<Response> { |
| 299 | let body = json_body(request).await; |
| 300 | let reported: Outcome<Mergeable> = g1t_kit::call( |
| 301 | &services.work, |
| 302 | "report_mergecheck", |
| 303 | &ReportMergecheckArgs { |
| 304 | pull_id: pull_id.to_owned(), |
| 305 | token: body["token"].as_str().unwrap_or_default().to_owned(), |
| 306 | conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(), |
| 307 | error: body["error"].as_str().map(str::to_owned), |
| 308 | }, |
| 309 | ) |
| 310 | .await?; |
| 311 | match reported { |
| 312 | Outcome::Ok(state) => reply(&json!({ "mergeable": state })), |
| 313 | Outcome::Fail(refused) => failure(&refused), |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | /// A sandbox reporting the review its agent wrote. As with checks, the |
| 318 | /// run's own token is the credential. |
| 319 | async fn report_review( |
| 320 | request: &mut Request, |
| 321 | services: &Services, |
| 322 | run_id: &str, |
| 323 | ) -> Result<Response> { |
| 324 | let body = json_body(request).await; |
| 325 | let reported: Outcome<bool> = g1t_kit::call( |
| 326 | &services.work, |
| 327 | "report_review", |
| 328 | &ReportReviewArgs { |
| 329 | run_id: run_id.to_owned(), |
| 330 | token: body["token"].as_str().unwrap_or_default().to_owned(), |
| 331 | verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None), |
| 332 | body: body["body"].as_str().unwrap_or_default().to_owned(), |
| 333 | comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(), |
| 334 | model: body["model"].as_str().map(str::to_owned), |
| 335 | error: body["error"].as_str().map(str::to_owned), |
| 336 | }, |
| 337 | ) |
| 338 | .await?; |
| 339 | match reported { |
| 340 | Outcome::Ok(_) => reply(&json!({ "recorded": true })), |
| 341 | Outcome::Fail(refused) => failure(&refused), |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | /// A sandbox reporting the plan its agent wrote. As with checks, the |
| 346 | /// plan's own token is the credential. |
| 347 | async fn report_plan( |
| 348 | request: &mut Request, |
| 349 | services: &Services, |
| 350 | plan_id: &str, |
| 351 | ) -> Result<Response> { |
| 352 | let body = json_body(request).await; |
| 353 | let reported: Outcome<bool> = g1t_kit::call( |
| 354 | &services.work, |
| 355 | "report_plan", |
| 356 | &ReportPlanArgs { |
| 357 | plan_id: plan_id.to_owned(), |
| 358 | token: body["token"].as_str().unwrap_or_default().to_owned(), |
| 359 | summary: body["summary"].as_str().unwrap_or_default().to_owned(), |
| 360 | issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(), |
| 361 | error: body["error"].as_str().map(str::to_owned), |
| 362 | }, |
| 363 | ) |
| 364 | .await?; |
| 365 | match reported { |
| 366 | Outcome::Ok(_) => reply(&json!({ "recorded": true })), |
| 367 | Outcome::Fail(refused) => failure(&refused), |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | /// A sandbox reporting what its agent's run cost, so that the workspace |
| 372 | /// it worked for is charged. As with checks, the run's own token is the |
| 373 | /// credential. |
| 374 | async fn report_usage( |
| 375 | request: &mut Request, |
| 376 | services: &Services, |
| 377 | run_id: &str, |
| 378 | ) -> Result<Response> { |
| 379 | let body = json_body(request).await; |
| 380 | let charged: Outcome<bool> = g1t_kit::call( |
| 381 | &services.billing, |
| 382 | "finish_run", |
| 383 | &FinishRunArgs { |
| 384 | run_id: run_id.to_owned(), |
| 385 | token: body["token"].as_str().unwrap_or_default().to_owned(), |
| 386 | cost_usd: body["cost_usd"].as_f64().unwrap_or_default(), |
| 387 | turns: body["turns"].as_u64().unwrap_or_default() as u32, |
| 388 | }, |
| 389 | ) |
| 390 | .await?; |
| 391 | match charged { |
| 392 | Outcome::Ok(_) => reply(&json!({ "recorded": true })), |
| 393 | Outcome::Fail(refused) => failure(&refused), |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | async fn respond(mut request: Request, env: &Env) -> Result<Response> { |
| 398 | let method = method_name(request.method()); |
| 399 | if method == "OPTIONS" { |
| 400 | return Ok(Response::empty()?.with_status(204)); |
| 401 | } |
| 402 | let url = request.url()?; |
| 403 | // Paths carry no version. An earlier form began with `/v1`, which is |
| 404 | // still accepted so that nothing already written against it breaks. |
| 405 | let path = match url.path().strip_prefix("/v1") { |
| 406 | Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(), |
| 407 | _ => url.path().to_owned(), |
| 408 | }; |
| 409 | let on_mcp = url.host_str().is_some_and(|host| host.starts_with("mcp.")); |
| 410 | let mut services = Services::new(env)?; |
| 411 | |
| 412 | // Stripe reporting to billing. Signed with the secret of the endpoint |
| 413 | // billing registered; the body goes through exactly as received, since |
| 414 | // the signature covers its bytes. |
| 415 | if method == "POST" && !on_mcp && path == "/stripe/webhook" { |
| 416 | return receive_stripe(&mut request, env).await; |
| 417 | } |
| 418 | |
| 419 | // Outside systems reporting to a connection. They sign what they send |
| 420 | // with the connection's own secret, which is not a g1t token, so this |
| 421 | // comes before anything that would read one. |
| 422 | if method == "POST" && !on_mcp |
| 423 | && let Some(id) = path.strip_prefix("/hooks/").filter(|id| !id.is_empty() && !id.contains('/')) { |
| 424 | return receive_hook(&mut request, &services, id).await; |
| 425 | } |
| 426 | |
| 427 | // A sandbox building a deployment, reporting with its build's token, |
| 428 | // which is not a g1t token. The body goes through as it is: it can |
| 429 | // carry a Worker's bundled code. |
| 430 | if method == "POST" && !on_mcp |
| 431 | && let Some(rest) = path.strip_prefix("/deployments/jobs/") |
| 432 | { |
| 433 | let target = format!("https://deployments/jobs/{rest}"); |
| 434 | let body = request.bytes().await?; |
| 435 | let headers = worker::Headers::new(); |
| 436 | headers.set("content-type", "application/json")?; |
| 437 | let mut init = worker::RequestInit::new(); |
| 438 | init.with_method(Method::Post) |
| 439 | .with_headers(headers) |
| 440 | .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into())); |
| 441 | let mut answer = env |
| 442 | .service("DEPLOYMENTS")? |
| 443 | .fetch_request(Request::new_with_init(&target, &init)?) |
| 444 | .await?; |
| 445 | // A fresh response: a fetched one's headers cannot be changed, and |
| 446 | // every response gets the API's own on the way out. |
| 447 | let status = answer.status_code(); |
| 448 | let bytes = answer.bytes().await?; |
| 449 | let bytes = match serde_json::from_slice::<Value>(&bytes) { |
| 450 | Ok(body) => serde_json::to_vec(&wire::snake_case(body))?, |
| 451 | Err(_) => bytes, |
| 452 | }; |
| 453 | return Ok(Response::from_bytes(bytes)? |
| 454 | .with_status(status) |
| 455 | .with_headers({ |
| 456 | let headers = worker::Headers::new(); |
| 457 | headers.set("content-type", "application/json")?; |
| 458 | headers |
| 459 | })); |
| 460 | } |
| 461 | |
| 462 | // A sandbox's artifacts and cache, with its job's token, which is not a |
| 463 | // g1t token either. |
| 464 | if !on_mcp |
| 465 | && let Some(rest) = path.strip_prefix("/actions/jobs/") |
| 466 | && (rest.contains("/artifacts") || rest.ends_with("/cache")) |
| 467 | { |
| 468 | let rest = rest.to_owned(); |
| 469 | return blobs::for_job(request, env, &services, method, &rest).await; |
| 470 | } |
| 471 | |
| 472 | let viewer = match authenticate(&request, &services).await? { |
| 473 | Ok(viewer) => viewer, |
| 474 | Err(refused) => return Ok(refused), |
| 475 | }; |
| 476 | services.audit = audit::AuditContext::of(&request, on_mcp); |
| 477 | // An agent's token: what it may do comes with it, on the composite |
| 478 | // identity identity resolved it to. |
| 479 | if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) { |
| 480 | services.scope = Some(acting.scope.clone()); |
| 481 | } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) { |
| 482 | let header = request.headers().get("authorization")?.unwrap_or_default(); |
| 483 | let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default(); |
| 484 | let scope: Option<AgentScope> = g1t_kit::call( |
| 485 | &services.identity, |
| 486 | "agent_scope", |
| 487 | &TokenArgs { |
| 488 | token: token.to_owned(), |
| 489 | }, |
| 490 | ) |
| 491 | .await?; |
| 492 | // A scope is what lets an agent's token do anything at all. |
| 493 | let Some(scope) = scope else { |
| 494 | return fail(FailureCode::Unauthenticated, "Invalid access token."); |
| 495 | }; |
| 496 | services.scope = Some(scope); |
| 497 | } |
| 498 | if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? { |
| 499 | return Ok(response); |
| 500 | } |
| 501 | if on_mcp { |
| 502 | return mcp::handle(request, &services, &viewer).await; |
| 503 | } |
| 504 | |
| 505 | match (method, path.trim_end_matches('/')) { |
| 506 | ("GET", "") => return reply(&index()), |
| 507 | ("GET", "/openapi.json") => return Response::from_json(&openapi::document()), |
| 508 | // A run's artifacts: listed, or one downloaded. |
| 509 | ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => { |
| 510 | let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect(); |
| 511 | if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() { |
| 512 | return match rest { |
| 513 | [] => { |
| 514 | let seen: Outcome<Value> = g1t_kit::call( |
| 515 | &services.actions, |
| 516 | "run", |
| 517 | &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }), |
| 518 | ) |
| 519 | .await?; |
| 520 | match seen { |
| 521 | Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?), |
| 522 | Outcome::Fail(refused) => failure(&refused), |
| 523 | } |
| 524 | } |
| 525 | [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await, |
| 526 | _ => fail(FailureCode::NotFound, "No such endpoint."), |
| 527 | }; |
| 528 | } |
| 529 | } |
| 530 | ("POST", "/device/code") => return device_code(&mut request, &services).await, |
| 531 | ("POST", "/device/token") => return device_token(&mut request, &services).await, |
| 532 | // Where a pull request lives, for a tool that knows only its fork. |
| 533 | ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => { |
| 534 | let located: Outcome<Value> = g1t_kit::call( |
| 535 | &services.work, |
| 536 | "locate_pull", |
| 537 | &json!({ "id": &path[7..], "viewer": viewer }), |
| 538 | ) |
| 539 | .await?; |
| 540 | return match located { |
| 541 | Outcome::Ok(value) => reply(&value), |
| 542 | Outcome::Fail(refused) => failure(&refused), |
| 543 | }; |
| 544 | } |
| 545 | ("POST", path) if path.starts_with("/mergechecks/") => { |
| 546 | let pull_id = path.trim_start_matches("/mergechecks/").to_owned(); |
| 547 | return report_mergecheck(&mut request, &services, &pull_id).await; |
| 548 | } |
| 549 | ("POST", path) if path.starts_with("/queue/") => { |
| 550 | let entry_id = path.trim_start_matches("/queue/").to_owned(); |
| 551 | return report_queue(&mut request, &services, &entry_id).await; |
| 552 | } |
| 553 | // A sandbox running a GitHub Actions job: fetching the job, and |
| 554 | // reporting how it goes. The job's own token is the credential. |
| 555 | ("POST", path) if path.starts_with("/actions/jobs/") => { |
| 556 | let rest = path.trim_start_matches("/actions/jobs/"); |
| 557 | let (job, method) = match rest.strip_suffix("/spec") { |
| 558 | Some(job) => (job.to_owned(), "job_spec"), |
| 559 | None => (rest.to_owned(), "job_report"), |
| 560 | }; |
| 561 | let body = json_body(&mut request).await; |
| 562 | let answered: Outcome<Value> = g1t_kit::call( |
| 563 | &services.actions, |
| 564 | method, |
| 565 | &json!({ "job": job, "token": body["token"], "report": body["report"] }), |
| 566 | ) |
| 567 | .await?; |
| 568 | return match answered { |
| 569 | // A job's spec is the workflow and its contexts as GitHub |
| 570 | // has them; only g1t's own keys around them are converted. |
| 571 | Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)), |
| 572 | Outcome::Fail(refused) => failure(&refused), |
| 573 | }; |
| 574 | } |
| 575 | // A sandbox reporting its agent run's steps, cost and end. As with |
| 576 | // checks, the run's own token, in the body, is the credential. |
| 577 | ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => { |
| 578 | let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report"); |
| 579 | let mut body = json_body(&mut request).await; |
| 580 | if !body.is_object() { |
| 581 | body = json!({}); |
| 582 | } |
| 583 | body["runId"] = json!(run_id); |
| 584 | let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?; |
| 585 | return match reported { |
| 586 | Outcome::Ok(status) => reply(&json!({ "status": status })), |
| 587 | Outcome::Fail(refused) => failure(&refused), |
| 588 | }; |
| 589 | } |
| 590 | // What a run's agent learned, as memory candidates; the same token. |
| 591 | ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => { |
| 592 | let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned"); |
| 593 | let body = json_body(&mut request).await; |
| 594 | let learned = json!({ |
| 595 | "runId": run_id, |
| 596 | "token": body["token"].as_str().unwrap_or_default(), |
| 597 | "items": body["items"].as_array().cloned().unwrap_or_default(), |
| 598 | }); |
| 599 | let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?; |
| 600 | return match captured { |
| 601 | Outcome::Ok(captured) => reply(&captured), |
| 602 | Outcome::Fail(refused) => failure(&refused), |
| 603 | }; |
| 604 | } |
| 605 | ("POST", path) if path.starts_with("/checks/") => { |
| 606 | let run_id = path.trim_start_matches("/checks/").to_owned(); |
| 607 | return report_checks(&mut request, &services, &run_id).await; |
| 608 | } |
| 609 | ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => { |
| 610 | let run_id = path |
| 611 | .trim_start_matches("/runs/") |
| 612 | .trim_end_matches("/usage") |
| 613 | .to_owned(); |
| 614 | return report_usage(&mut request, &services, &run_id).await; |
| 615 | } |
| 616 | ("POST", path) if path.starts_with("/plans/") => { |
| 617 | let plan_id = path.trim_start_matches("/plans/").to_owned(); |
| 618 | return report_plan(&mut request, &services, &plan_id).await; |
| 619 | } |
| 620 | ("POST", path) if path.starts_with("/reviews/") => { |
| 621 | let run_id = path.trim_start_matches("/reviews/").to_owned(); |
| 622 | return report_review(&mut request, &services, &run_id).await; |
| 623 | } |
| 624 | _ => {} |
| 625 | } |
| 626 | |
| 627 | let query: Vec<(String, String)> = url |
| 628 | .query_pairs() |
| 629 | .map(|(name, value)| (name.into_owned(), value.into_owned())) |
| 630 | .collect(); |
| 631 | let body = if method == "GET" { |
| 632 | Value::Null |
| 633 | } else { |
| 634 | snake_case_keys(json_body(&mut request).await) |
| 635 | }; |
| 636 | let Some((route, input)) = rest::resolve(method, &path, &query, body) else { |
| 637 | return fail(FailureCode::NotFound, "No such endpoint."); |
| 638 | }; |
| 639 | match audit::run(route.op, &services, &viewer, &input).await? { |
| 640 | Outcome::Ok(value) => reply(&value), |
| 641 | Outcome::Fail(refused) => failure(&refused), |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | /// Request bodies take the same keys as the MCP tools, `snake_case`, as |
| 646 | /// responses use; the `camelCase` spelling is accepted too. |
| 647 | fn snake_case_keys(body: Value) -> Value { |
| 648 | let Value::Object(fields) = body else { |
| 649 | return body; |
| 650 | }; |
| 651 | let mut out = serde_json::Map::new(); |
| 652 | for (key, value) in fields { |
| 653 | let mut snake = String::with_capacity(key.len() + 4); |
| 654 | for c in key.chars() { |
| 655 | if c.is_ascii_uppercase() { |
| 656 | snake.push('_'); |
| 657 | snake.push(c.to_ascii_lowercase()); |
| 658 | } else { |
| 659 | snake.push(c); |
| 660 | } |
| 661 | } |
| 662 | // A key given in both spellings keeps the snake_case one. |
| 663 | if snake != key && out.contains_key(&snake) { |
| 664 | continue; |
| 665 | } |
| 666 | out.insert(snake, value); |
| 667 | } |
| 668 | Value::Object(out) |
| 669 | } |
| 670 | |
| 671 | #[cfg(test)] |
| 672 | mod tests { |
| 673 | use super::snake_case_keys; |
| 674 | use serde_json::json; |
| 675 | |
| 676 | #[test] |
| 677 | fn camel_case_keys_are_accepted() { |
| 678 | assert_eq!( |
| 679 | snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })), |
| 680 | json!({ "count_agent_approvals": false, "title": "x" }) |
| 681 | ); |
| 682 | } |
| 683 | |
| 684 | #[test] |
| 685 | fn snake_case_wins_when_both_are_given() { |
| 686 | assert_eq!( |
| 687 | snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })), |
| 688 | json!({ "keep_issue_open": true }) |
| 689 | ); |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | // The API is called from browsers too: the reference's explorer, and apps |
| 694 | // built on g1t. It carries no cookies, so any origin may call it. |
| 695 | #[event(fetch)] |
| 696 | async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> { |
| 697 | let mut response = respond(request, &env).await?; |
| 698 | let headers = response.headers_mut(); |
| 699 | headers.set("access-control-allow-origin", "*")?; |
| 700 | headers.set( |
| 701 | "access-control-allow-headers", |
| 702 | "authorization, content-type", |
| 703 | )?; |
| 704 | headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?; |
| 705 | headers.set("access-control-expose-headers", "www-authenticate")?; |
| 706 | Ok(response) |
| 707 | } |