pr_01m47d24b0e6n91zwymwxg0vpx/apps/api/src/lib.rs

457 lines17,019 bytesCodeBlame
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 mcp;
8mod oauth;
9mod openapi;
10mod operations;
11mod rest;
12
13use g1t_contracts::billing::FinishRunArgs;
14use g1t_contracts::identity::{
15 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
16};
17use g1t_contracts::work::{
18 CheckRun, QueueState, ReportChecksArgs, ReportPlanArgs, ReportQueueArgs, ReportReviewArgs,
19};
20use g1t_contracts::identity::AgentScope;
21use g1t_contracts::{Failure, FailureCode, Outcome, PrincipalKind, Viewer};
22use serde_json::{Value, json};
23use worker::{Context, Env, Method, Request, Response, Result, event};
24
25use operations::Services;
26
27const API: &str = "https://api.g1t.sh";
28
29fn method_name(method: Method) -> &'static str {
30 match method {
31 Method::Get => "GET",
32 Method::Post => "POST",
33 Method::Patch => "PATCH",
34 Method::Put => "PUT",
35 Method::Delete => "DELETE",
36 Method::Options => "OPTIONS",
37 Method::Head => "HEAD",
38 _ => "OTHER",
39 }
40}
41
42/// An error in the shape every endpoint uses.
43fn failure(failure: &Failure) -> Result<Response> {
44 Ok(Response::from_json(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
45}
46
47fn fail(code: FailureCode, message: &str) -> Result<Response> {
48 failure(&Failure {
49 code,
50 message: message.to_owned(),
51 })
52}
53
54/// A request body as JSON. An empty or malformed body is no input.
55async fn json_body(request: &mut Request) -> Value {
56 request.json().await.unwrap_or(Value::Null)
57}
58
59/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
60/// an anonymous viewer; a wrong one is refused, so that a typo does not
61/// silently look signed out.
62async fn authenticate(
63 request: &Request,
64 services: &Services,
65) -> Result<std::result::Result<Viewer, Response>> {
66 let header = request.headers().get("authorization")?.unwrap_or_default();
67 let token = match header.split_once(' ') {
68 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
69 token.trim()
70 }
71 _ => return Ok(Ok(None)),
72 };
73 let viewer: Viewer = g1t_kit::call(
74 &services.identity,
75 "user_for_access_token",
76 &TokenArgs {
77 token: token.to_owned(),
78 },
79 )
80 .await?;
81 if viewer.is_some() {
82 return Ok(Ok(viewer));
83 }
84 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
85 // Tells an MCP client where to sign in again.
86 response.headers_mut().set(
87 "www-authenticate",
88 &format!("{}, error=\"invalid_token\"", oauth::MCP_CHALLENGE),
89 )?;
90 Ok(Err(response))
91}
92
93/// Where everything is, for someone or something exploring the API.
94fn index() -> Value {
95 let repo = format!("{API}/repos/{{owner}}/{{name}}");
96 json!({
97 "documentation_url": "https://docs.g1t.sh/api/reference/",
98 "openapi_url": format!("{API}/openapi.json"),
99 "mcp_url": "https://mcp.g1t.sh",
100 "current_user_url": format!("{API}/user"),
101 "workspaces_url": format!("{API}/workspaces"),
102 "repositories_url": format!("{API}/repos{{?q}}"),
103 "repository_url": repo,
104 "repository_events_url": format!("{repo}/events{{?before}}"),
105 "labels_url": format!("{repo}/labels"),
106 "issues_url": format!("{repo}/issues{{?state,label}}"),
107 "issue_url": format!("{repo}/issues/{{number}}"),
108 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
109 "pulls_url": format!("{repo}/pulls{{?state}}"),
110 "pull_url": format!("{repo}/pulls/{{number}}"),
111 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
112 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
113 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
114 "device_code_url": format!("{API}/device/code"),
115 "device_token_url": format!("{API}/device/token"),
116 "oauth_metadata_url": format!("{API}/.well-known/oauth-authorization-server"),
117 "git_url": "https://g1t.sh/{owner}/{name}.git",
118 })
119}
120
121// Signing in from a tool. Accounts are created, and passwords typed, only
122// in a browser; a tool gets its token by having a person approve a code.
123
124async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
125 let body = json_body(request).await;
126 let started: DeviceStart = g1t_kit::call(
127 &services.identity,
128 "device_start",
129 &DeviceStartArgs {
130 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
131 },
132 )
133 .await?;
134 Response::from_json(&json!({
135 "device_code": started.device_code,
136 "user_code": started.user_code,
137 "verification_uri": "https://g1t.sh/device",
138 "verification_uri_complete": format!("https://g1t.sh/device?code={}", started.user_code),
139 "expires_in": started.expires_in,
140 "interval": started.interval,
141 }))
142}
143
144async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
145 let body = json_body(request).await;
146 let claim: DeviceClaim = g1t_kit::call(
147 &services.identity,
148 "device_claim",
149 &DeviceClaimArgs {
150 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
151 },
152 )
153 .await?;
154 Response::from_json(&match claim {
155 DeviceClaim::Approved { token, user } => json!({
156 "status": "approved",
157 "token": token,
158 "username": user.username,
159 "verified": user.verified,
160 }),
161 DeviceClaim::Pending => json!({ "status": "pending" }),
162 DeviceClaim::Denied => json!({ "status": "denied" }),
163 DeviceClaim::Expired => json!({ "status": "expired" }),
164 })
165}
166
167/// A sandbox reporting on its run of a pull request's acceptance checks.
168/// The run's own token, in the body, is the credential: it was given to
169/// that sandbox and to nothing else.
170async fn report_checks(
171 request: &mut Request,
172 services: &Services,
173 run_id: &str,
174) -> Result<Response> {
175 let body = json_body(request).await;
176 let reported: Outcome<CheckRun> = g1t_kit::call(
177 &services.work,
178 "report_checks",
179 &ReportChecksArgs {
180 run_id: run_id.to_owned(),
181 token: body["token"].as_str().unwrap_or_default().to_owned(),
182 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
183 error: body["error"].as_str().map(str::to_owned),
184 skip: false,
185 },
186 )
187 .await?;
188 match reported {
189 Outcome::Ok(run) => Response::from_json(&json!({ "status": run.status })),
190 Outcome::Fail(refused) => failure(&refused),
191 }
192}
193
194/// A sandbox reporting one tested state of a merge queue. As with checks,
195/// the entry's own token is the credential.
196async fn report_queue(
197 request: &mut Request,
198 services: &Services,
199 entry_id: &str,
200) -> Result<Response> {
201 let body = json_body(request).await;
202 let reported: Outcome<QueueState> = g1t_kit::call(
203 &services.work,
204 "report_queue",
205 &ReportQueueArgs {
206 entry_id: entry_id.to_owned(),
207 token: body["token"].as_str().unwrap_or_default().to_owned(),
208 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
209 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
210 error: body["error"].as_str().map(str::to_owned),
211 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
212 },
213 )
214 .await?;
215 match reported {
216 Outcome::Ok(state) => Response::from_json(&json!({ "state": state })),
217 Outcome::Fail(refused) => failure(&refused),
218 }
219}
220
221/// A sandbox reporting the review its agent wrote. As with checks, the
222/// run's own token is the credential.
223async fn report_review(
224 request: &mut Request,
225 services: &Services,
226 run_id: &str,
227) -> Result<Response> {
228 let body = json_body(request).await;
229 let reported: Outcome<bool> = g1t_kit::call(
230 &services.work,
231 "report_review",
232 &ReportReviewArgs {
233 run_id: run_id.to_owned(),
234 token: body["token"].as_str().unwrap_or_default().to_owned(),
235 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
236 body: body["body"].as_str().unwrap_or_default().to_owned(),
237 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
238 model: body["model"].as_str().map(str::to_owned),
239 error: body["error"].as_str().map(str::to_owned),
240 },
241 )
242 .await?;
243 match reported {
244 Outcome::Ok(_) => Response::from_json(&json!({ "recorded": true })),
245 Outcome::Fail(refused) => failure(&refused),
246 }
247}
248
249/// A sandbox reporting the plan its agent wrote. As with checks, the
250/// plan's own token is the credential.
251async fn report_plan(
252 request: &mut Request,
253 services: &Services,
254 plan_id: &str,
255) -> Result<Response> {
256 let body = json_body(request).await;
257 let reported: Outcome<bool> = g1t_kit::call(
258 &services.work,
259 "report_plan",
260 &ReportPlanArgs {
261 plan_id: plan_id.to_owned(),
262 token: body["token"].as_str().unwrap_or_default().to_owned(),
263 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
264 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
265 error: body["error"].as_str().map(str::to_owned),
266 },
267 )
268 .await?;
269 match reported {
270 Outcome::Ok(_) => Response::from_json(&json!({ "recorded": true })),
271 Outcome::Fail(refused) => failure(&refused),
272 }
273}
274
275/// A sandbox reporting what its agent's run cost, so that the workspace
276/// it worked for is charged. As with checks, the run's own token is the
277/// credential.
278async fn report_usage(
279 request: &mut Request,
280 services: &Services,
281 run_id: &str,
282) -> Result<Response> {
283 let body = json_body(request).await;
284 let charged: Outcome<bool> = g1t_kit::call(
285 &services.billing,
286 "finish_run",
287 &FinishRunArgs {
288 run_id: run_id.to_owned(),
289 token: body["token"].as_str().unwrap_or_default().to_owned(),
290 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
291 turns: body["turns"].as_u64().unwrap_or_default() as u32,
292 },
293 )
294 .await?;
295 match charged {
296 Outcome::Ok(_) => Response::from_json(&json!({ "recorded": true })),
297 Outcome::Fail(refused) => failure(&refused),
298 }
299}
300
301async fn respond(mut request: Request, env: &Env) -> Result<Response> {
302 let method = method_name(request.method());
303 if method == "OPTIONS" {
304 return Ok(Response::empty()?.with_status(204));
305 }
306 let url = request.url()?;
307 // Paths carry no version. An earlier form began with `/v1`, which is
308 // still accepted so that nothing already written against it breaks.
309 let path = match url.path().strip_prefix("/v1") {
310 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
311 _ => url.path().to_owned(),
312 };
313 let on_mcp = url.host_str().is_some_and(|host| host.starts_with("mcp."));
314 let mut services = Services::new(env)?;
315
316 let viewer = match authenticate(&request, &services).await? {
317 Ok(viewer) => viewer,
318 Err(refused) => return Ok(refused),
319 };
320 // An agent's token: what it may do comes with it.
321 if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
322 let header = request.headers().get("authorization")?.unwrap_or_default();
323 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
324 let scope: Option<AgentScope> = g1t_kit::call(
325 &services.identity,
326 "agent_scope",
327 &TokenArgs {
328 token: token.to_owned(),
329 },
330 )
331 .await?;
332 // A scope is what lets an agent's token do anything at all.
333 let Some(scope) = scope else {
334 return fail(FailureCode::Unauthenticated, "Invalid access token.");
335 };
336 services.scope = Some(scope);
337 }
338 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
339 return Ok(response);
340 }
341 if on_mcp {
342 return mcp::handle(request, &services, &viewer).await;
343 }
344
345 match (method, path.trim_end_matches('/')) {
346 ("GET", "") => return Response::from_json(&index()),
347 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
348 ("POST", "/device/code") => return device_code(&mut request, &services).await,
349 ("POST", "/device/token") => return device_token(&mut request, &services).await,
350 ("POST", path) if path.starts_with("/queue/") => {
351 let entry_id = path.trim_start_matches("/queue/").to_owned();
352 return report_queue(&mut request, &services, &entry_id).await;
353 }
354 ("POST", path) if path.starts_with("/checks/") => {
355 let run_id = path.trim_start_matches("/checks/").to_owned();
356 return report_checks(&mut request, &services, &run_id).await;
357 }
358 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
359 let run_id = path
360 .trim_start_matches("/runs/")
361 .trim_end_matches("/usage")
362 .to_owned();
363 return report_usage(&mut request, &services, &run_id).await;
364 }
365 ("POST", path) if path.starts_with("/plans/") => {
366 let plan_id = path.trim_start_matches("/plans/").to_owned();
367 return report_plan(&mut request, &services, &plan_id).await;
368 }
369 ("POST", path) if path.starts_with("/reviews/") => {
370 let run_id = path.trim_start_matches("/reviews/").to_owned();
371 return report_review(&mut request, &services, &run_id).await;
372 }
373 _ => {}
374 }
375
376 let query: Vec<(String, String)> = url
377 .query_pairs()
378 .map(|(name, value)| (name.into_owned(), value.into_owned()))
379 .collect();
380 let body = if method == "GET" {
381 Value::Null
382 } else {
383 snake_case_keys(json_body(&mut request).await)
384 };
385 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
386 return fail(FailureCode::NotFound, "No such endpoint.");
387 };
388 match route.op.run(&services, &viewer, &input).await? {
389 Outcome::Ok(value) => Response::from_json(&value),
390 Outcome::Fail(refused) => failure(&refused),
391 }
392}
393
394/// Request bodies take the same keys as the MCP tools, `snake_case`; the
395/// `camelCase` that responses use is accepted too, so a client can send
396/// back what it read.
397fn snake_case_keys(body: Value) -> Value {
398 let Value::Object(fields) = body else {
399 return body;
400 };
401 let mut out = serde_json::Map::new();
402 for (key, value) in fields {
403 let mut snake = String::with_capacity(key.len() + 4);
404 for c in key.chars() {
405 if c.is_ascii_uppercase() {
406 snake.push('_');
407 snake.push(c.to_ascii_lowercase());
408 } else {
409 snake.push(c);
410 }
411 }
412 // A key given in both spellings keeps the snake_case one.
413 if snake != key && out.contains_key(&snake) {
414 continue;
415 }
416 out.insert(snake, value);
417 }
418 Value::Object(out)
419}
420
421#[cfg(test)]
422mod tests {
423 use super::snake_case_keys;
424 use serde_json::json;
425
426 #[test]
427 fn camel_case_keys_are_accepted() {
428 assert_eq!(
429 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
430 json!({ "count_agent_approvals": false, "title": "x" })
431 );
432 }
433
434 #[test]
435 fn snake_case_wins_when_both_are_given() {
436 assert_eq!(
437 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
438 json!({ "keep_issue_open": true })
439 );
440 }
441}
442
443// The API is called from browsers too: the reference's explorer, and apps
444// built on g1t. It carries no cookies, so any origin may call it.
445#[event(fetch)]
446async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
447 let mut response = respond(request, &env).await?;
448 let headers = response.headers_mut();
449 headers.set("access-control-allow-origin", "*")?;
450 headers.set(
451 "access-control-allow-headers",
452 "authorization, content-type",
453 )?;
454 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
455 headers.set("access-control-expose-headers", "www-authenticate")?;
456 Ok(response)
457}