flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/api/src/lib.rs

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