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/openapi.rs

741 lines29,374 bytesCodeBlame
1//! The OpenAPI document, generated from the same list the routes are.
2//!
3//! The docs site builds its API reference from a copy of this document,
4//! `apps/docs/src/data/openapi.json`. A test keeps the copy current: run
5//! `G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi` to rewrite it.
6
7use serde_json::{Map, Value, json};
8
9use crate::operations::Op;
10use crate::rest::{ROUTES, Route};
11
12/// The sections of the API reference: a name, what it covers, and its
13/// operations in the order a reader meets them.
14const SECTIONS: &[(&str, &str, &[Op])] = &[
15 (
16 "Accounts",
17 "Signing in from a tool, and who a token acts as.",
18 &[Op::Whoami],
19 ),
20 (
21 "Workspaces",
22 "A workspace owns repositories and is the first part of their address. People and agents work in workspaces.",
23 &[Op::CreateWorkspace],
24 ),
25 (
26 "Repositories",
27 "A repository, how it handles pull requests, and its timeline.",
28 &[
29 Op::ListRepos,
30 Op::CreateRepo,
31 Op::GetRepo,
32 Op::UpdateRepo,
33 Op::GetRepoSettings,
34 Op::UpdateRepoSettings,
35 Op::ListEvents,
36 ],
37 ),
38 (
39 "Issues",
40 "What should change in a repository, with labels and comments. Issues and pull requests share one sequence of numbers.",
41 &[
42 Op::ListIssues,
43 Op::CreateIssue,
44 Op::GetIssue,
45 Op::UpdateIssue,
46 Op::CloseIssue,
47 Op::ReopenIssue,
48 Op::AssignIssue,
49 Op::AddComment,
50 Op::ListLabels,
51 ],
52 ),
53 (
54 "Plans",
55 "An outcome turned into the issues that would get there, with the order they must merge in.",
56 &[Op::PlanWork, Op::GetPlan, Op::ApplyPlan],
57 ),
58 (
59 "Pull requests",
60 "A proposed change in its own fork or on a branch. Several can be made for one issue; the one merged resolves it.",
61 &[
62 Op::ListPullRequests,
63 Op::CreatePullRequest,
64 Op::GetPullRequest,
65 Op::GetPullRequestChanges,
66 Op::MarkPullRequestReady,
67 Op::ReviewPullRequest,
68 Op::MergePullRequest,
69 Op::ClosePullRequest,
70 Op::GetMergeQueue,
71 Op::MessageAgent,
72 Op::AnswerMessage,
73 Op::TakeMessages,
74 ],
75 ),
76 (
77 "Sessions",
78 "The record of how a pull request was made: prompts, reasoning and the tools that ran.",
79 &[Op::ReadSession, Op::RecordSession],
80 ),
81 (
82 "Memory",
83 "What agents and people learned that the next agent should know, for one project or across a workspace. Members and g1t's agents only; never a secret.",
84 &[Op::Remember, Op::Recall],
85 ),
86 (
87 "Context",
88 "A workspace's context hub: a catalog of what it builds and runs, built from its repositories, deployments and integrations, and one search across the catalog, docs, issues, pull requests and memory.",
89 &[Op::SearchContext, Op::GetEntity],
90 ),
91 (
92 "Actions",
93 "GitHub Actions workflows in .g1t/workflows, their runs, and their jobs' logs.",
94 &[
95 Op::ListWorkflows,
96 Op::ListWorkflowRuns,
97 Op::GetWorkflowRun,
98 Op::GetJobLogs,
99 Op::DispatchWorkflow,
100 Op::CancelWorkflowRun,
101 Op::RerunWorkflowRun,
102 Op::UpdateWorkflow,
103 ],
104 ),
105 (
106 "Secrets and variables",
107 "Values that workflows and deployments read, per repository or for a whole workspace, with a row per environment.",
108 &[
109 Op::ListActionsSecrets,
110 Op::SetActionsSecret,
111 Op::DeleteActionsSecret,
112 Op::ListActionsVariables,
113 Op::SetActionsVariable,
114 Op::DeleteActionsVariable,
115 ],
116 ),
117 (
118 "Webhooks",
119 "Signed HTTPS requests sent to your own address as things happen, for a repository or a whole workspace.",
120 &[
121 Op::ListWebhooks,
122 Op::CreateWebhook,
123 Op::UpdateWebhook,
124 Op::DeleteWebhook,
125 Op::PingWebhook,
126 Op::ListWebhookDeliveries,
127 Op::RedeliverWebhook,
128 ],
129 ),
130 (
131 "Integrations",
132 "A workspace's connections to outside systems: model providers, alert sources and issue trackers.",
133 &[
134 Op::ListIntegrations,
135 Op::ConnectIntegration,
136 Op::DisconnectIntegration,
137 Op::TestIntegration,
138 Op::GetModelRoutes,
139 Op::SetModelRoutes,
140 Op::GetContext,
141 Op::ImportIssue,
142 ],
143 ),
144];
145
146/// The section of the API reference an operation is listed under.
147fn tag(op: Op) -> &'static str {
148 SECTIONS
149 .iter()
150 .find(|(_, _, ops)| ops.contains(&op))
151 .map_or("Repositories", |(name, _, _)| name)
152}
153
154/// What an operation's page is called, as a short sentence.
155fn title(op: Op) -> &'static str {
156 match op {
157 Op::Whoami => "Get the current user",
158 Op::CreateWorkspace => "Create a workspace",
159 Op::ListRepos => "List repositories",
160 Op::GetRepo => "Get a repository",
161 Op::CreateRepo => "Create a repository",
162 Op::UpdateRepo => "Update a repository",
163 Op::GetRepoSettings => "Get repository settings",
164 Op::UpdateRepoSettings => "Update repository settings",
165 Op::GetMergeQueue => "Get the merge queue",
166 Op::MessageAgent => "Message an agent",
167 Op::AnswerMessage => "Answer a message",
168 Op::TakeMessages => "Take new messages",
169 Op::Remember => "Remember something",
170 Op::Recall => "Recall memory",
171 Op::SearchContext => "Search the context hub",
172 Op::GetEntity => "Get a catalog entry",
173 Op::ListIssues => "List issues",
174 Op::GetIssue => "Get an issue",
175 Op::CreateIssue => "Create an issue",
176 Op::UpdateIssue => "Update an issue",
177 Op::CloseIssue => "Close an issue",
178 Op::ReopenIssue => "Reopen an issue",
179 Op::AssignIssue => "Assign an issue to the g1t agent",
180 Op::PlanWork => "Plan work",
181 Op::GetPlan => "Get a plan",
182 Op::ApplyPlan => "Apply a plan",
183 Op::ListLabels => "List labels",
184 Op::AddComment => "Add a comment",
185 Op::ReviewPullRequest => "Review a pull request",
186 Op::ListPullRequests => "List pull requests",
187 Op::GetPullRequest => "Get a pull request",
188 Op::CreatePullRequest => "Create a pull request",
189 Op::RecordSession => "Record session entries",
190 Op::ReadSession => "Read a session",
191 Op::MarkPullRequestReady => "Mark a pull request ready",
192 Op::ClosePullRequest => "Close a pull request",
193 Op::GetPullRequestChanges => "Get a pull request's changes",
194 Op::MergePullRequest => "Merge a pull request",
195 Op::ListEvents => "List repository events",
196 Op::ListIntegrations => "List integrations",
197 Op::ConnectIntegration => "Connect an integration",
198 Op::DisconnectIntegration => "Disconnect an integration",
199 Op::TestIntegration => "Test an integration",
200 Op::GetContext => "Look up a ticket",
201 Op::ImportIssue => "Import an issue",
202 Op::GetModelRoutes => "Get model routes",
203 Op::SetModelRoutes => "Set model routes",
204 Op::ListWebhooks => "List webhooks",
205 Op::CreateWebhook => "Create a webhook",
206 Op::UpdateWebhook => "Update a webhook",
207 Op::DeleteWebhook => "Delete a webhook",
208 Op::PingWebhook => "Ping a webhook",
209 Op::ListWebhookDeliveries => "List webhook deliveries",
210 Op::RedeliverWebhook => "Redeliver a webhook delivery",
211 Op::ListWorkflows => "List workflows",
212 Op::ListWorkflowRuns => "List workflow runs",
213 Op::GetWorkflowRun => "Get a workflow run",
214 Op::GetJobLogs => "Get a job's log",
215 Op::DispatchWorkflow => "Run a workflow",
216 Op::CancelWorkflowRun => "Cancel a workflow run",
217 Op::RerunWorkflowRun => "Re-run a workflow run",
218 Op::UpdateWorkflow => "Turn a workflow on or off",
219 Op::ListActionsSecrets => "List secrets",
220 Op::SetActionsSecret => "Set a secret",
221 Op::DeleteActionsSecret => "Delete a secret",
222 Op::ListActionsVariables => "List variables",
223 Op::SetActionsVariable => "Set a variable",
224 Op::DeleteActionsVariable => "Delete a variable",
225 }
226}
227
228/// Whether an operation can be refused with `402 payment_required`: the
229/// ones that start an agent, when the workspace has no credit.
230fn may_need_payment(op: Op) -> bool {
231 matches!(op, Op::AssignIssue | Op::PlanWork | Op::ApplyPlan)
232}
233
234/// What the reference says beyond each operation's own description, keyed
235/// by operation id, written by hand from what the services return: `notes`
236/// (Markdown, added to the description) and example `params` (path),
237/// `query`, `request` (body) and `response`.
238const REFERENCE: &str = include_str!("reference.json");
239
240fn examples() -> Map<String, Value> {
241 match serde_json::from_str(REFERENCE) {
242 Ok(Value::Object(examples)) => examples,
243 _ => Map::new(),
244 }
245}
246
247/// `/repos/:owner/:name` as OpenAPI writes it: `/repos/{owner}/{name}`.
248fn openapi_path(route: &Route) -> String {
249 route
250 .path
251 .split('/')
252 .map(|segment| match segment.strip_prefix(':') {
253 Some(name) => format!("{{{name}}}"),
254 None => segment.to_owned(),
255 })
256 .collect::<Vec<_>>()
257 .join("/")
258}
259
260fn error_response(description: &str) -> Value {
261 json!({
262 "description": description,
263 "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } },
264 })
265}
266
267/// A parameter in the path or the query, described by the operation's
268/// input schema where it has the same name.
269fn parameter(name: &str, place: &str, required: bool, schema: Option<&Value>) -> Value {
270 let mut schema = schema.cloned().unwrap_or_else(|| json!({ "type": "string" }));
271 let description = match name {
272 "owner" => Some(Value::from("The workspace that owns the repository.")),
273 "name" => Some(Value::from("The repository's name.")),
274 _ => schema.as_object_mut().and_then(|schema| schema.remove("description")),
275 };
276 let mut parameter = json!({
277 "name": name,
278 "in": place,
279 "required": required,
280 "schema": schema,
281 });
282 if let Some(description) = description {
283 parameter["description"] = description;
284 }
285 parameter
286}
287
288/// The operation id of a route. An operation reached at a workspace's
289/// address as well as a repository's is documented once for each, with its
290/// own id; GitHub's alternative addresses for one operation keep GitHub's
291/// names.
292fn operation_id(route: &Route) -> String {
293 let op = route.op;
294 let base = match (route.method, route.path.rsplit('/').next().unwrap_or_default()) {
295 ("PUT", "enable") => "enable_workflow".to_owned(),
296 ("PUT", "disable") => "disable_workflow".to_owned(),
297 ("POST", "rerun-failed-jobs") => "rerun_failed_jobs".to_owned(),
298 ("PATCH", ":setting") => "update_actions_variable".to_owned(),
299 ("GET", "runs") if route.path.contains("/workflows/:workflow/") => "list_runs_of_workflow".to_owned(),
300 _ => op.name().to_owned(),
301 };
302 if route.path.starts_with("/workspaces/") && ROUTES.iter().any(|other| other.op == op && other.path.starts_with("/repos/")) {
303 format!("{base}_for_workspace")
304 } else {
305 base
306 }
307}
308
309/// The summary of a route: its operation's title, or for one of GitHub's
310/// alternative addresses, what that address does.
311fn summary(route: &Route, id: &str) -> String {
312 let base = match id.trim_end_matches("_for_workspace") {
313 "enable_workflow" => "Turn a workflow on",
314 "disable_workflow" => "Turn a workflow off",
315 "rerun_failed_jobs" => "Re-run failed jobs",
316 "update_actions_variable" => "Update a variable",
317 "list_runs_of_workflow" => "List a workflow's runs",
318 _ => title(route.op),
319 };
320 if id.ends_with("_for_workspace") {
321 format!("{base} for a workspace")
322 } else {
323 base.to_owned()
324 }
325}
326
327fn operation(route: &Route) -> Value {
328 let op = route.op;
329 let path_params: Vec<&str> = route.params().collect();
330 // `owner` and `name` in the path stand for the operation's `repo` input.
331 let covered = |name: &str| name == "repo" || path_params.contains(&name);
332 let all_properties = op.properties();
333 let mut properties = all_properties.clone();
334 properties.retain(|name, _| !covered(name));
335 let required: Vec<String> = op
336 .required()
337 .into_iter()
338 .filter(|name| !covered(name))
339 .collect();
340
341 let mut parameters: Vec<Value> = path_params
342 .iter()
343 .map(|name| parameter(name, "path", true, all_properties.get(*name)))
344 .collect();
345 let mut body = Value::Null;
346 if route.method == "GET" {
347 for (name, key) in route.query {
348 parameters.push(parameter(
349 name,
350 "query",
351 required.iter().any(|required| required == key),
352 properties.get(*key),
353 ));
354 }
355 } else if !properties.is_empty() {
356 let mut schema = json!({ "type": "object", "properties": properties });
357 if !required.is_empty() {
358 schema["required"] = json!(required);
359 }
360 body = json!({
361 "required": !required.is_empty(),
362 "content": { "application/json": { "schema": schema } },
363 });
364 }
365
366 let id = operation_id(route);
367 let mut responses = Map::new();
368 responses.insert(
369 "200".into(),
370 json!({
371 "description": "Success.",
372 "content": { "application/json": { "schema": {} } },
373 }),
374 );
375 responses.insert(
376 "401".into(),
377 error_response("A token is required, or the one sent is not valid."),
378 );
379 if may_need_payment(op) {
380 responses.insert(
381 "402".into(),
382 error_response("The workspace has no agent credit."),
383 );
384 }
385 responses.insert("403".into(), error_response("Signed in, but not allowed to do this."));
386 if !matches!(op, Op::Whoami | Op::ListRepos) {
387 responses.insert("404".into(), error_response("It does not exist, or you cannot see it."));
388 }
389 if route.method != "GET" {
390 responses.insert(
391 "409".into(),
392 error_response("The request conflicts with the current state."),
393 );
394 }
395 if op != Op::Whoami {
396 responses.insert("422".into(), error_response("The input is not valid."));
397 }
398 // Public data can be read without a token; everything else needs one.
399 let security = if op.needs_user() {
400 json!([{ "token": [] }])
401 } else {
402 json!([{ "token": [] }, {}])
403 };
404 let mut described = json!({
405 "operationId": id,
406 "tags": [tag(op)],
407 "summary": summary(route, &id),
408 "description": op.description(),
409 "x-mcp-tool": op.name(),
410 "security": security,
411 "parameters": parameters,
412 "responses": responses,
413 });
414 if !body.is_null() {
415 described["requestBody"] = body;
416 }
417 described
418}
419
420/// Entries for device sign-in, which is not an operation.
421fn onboarding() -> Map<String, Value> {
422 let paths = json!({
423 "/device/code": {
424 "post": {
425 "operationId": "device_code",
426 "tags": ["Accounts"],
427 "summary": "Start signing in",
428 "description": "Begins a device sign-in. Show the person `verification_uri_complete` and have them open it in a browser, where they sign in or register and approve the code. Then poll `/device/token`.",
429 "security": [],
430 "requestBody": {
431 "content": { "application/json": { "schema": {
432 "type": "object",
433 "properties": {
434 "client_name": {
435 "type": "string",
436 "description": "What is asking, shown to the person approving. For example, Claude Code.",
437 },
438 },
439 } } },
440 },
441 "responses": { "200": {
442 "description": "The codes for this sign-in.",
443 "content": { "application/json": { "schema": {
444 "type": "object",
445 "properties": {
446 "device_code": { "type": "string", "description": "Secret. Send it to /device/token." },
447 "user_code": { "type": "string", "description": "Shown to the person, like WDJB-MJHT." },
448 "verification_uri": { "type": "string" },
449 "verification_uri_complete": {
450 "type": "string",
451 "description": "The link to give the person; it carries the code.",
452 },
453 "expires_in": { "type": "integer", "description": "Seconds until the codes expire." },
454 "interval": { "type": "integer", "description": "Seconds to wait between polls." },
455 },
456 } } },
457 } },
458 },
459 },
460 "/device/token": {
461 "post": {
462 "operationId": "device_token",
463 "tags": ["Accounts"],
464 "summary": "Finish signing in",
465 "description": "Asks whether the person has approved. Poll no faster than the interval. The token is returned once.",
466 "security": [],
467 "requestBody": {
468 "required": true,
469 "content": { "application/json": { "schema": {
470 "type": "object",
471 "required": ["device_code"],
472 "properties": { "device_code": { "type": "string" } },
473 } } },
474 },
475 "responses": { "200": {
476 "description": "The state of the sign-in.",
477 "content": { "application/json": { "schema": {
478 "type": "object",
479 "required": ["status"],
480 "properties": {
481 "status": { "type": "string", "enum": ["pending", "approved", "denied", "expired"] },
482 "token": { "type": "string", "description": "Present when approved." },
483 "username": { "type": "string" },
484 "verified": {
485 "type": "boolean",
486 "description": "Whether the account's email is confirmed.",
487 },
488 },
489 } } },
490 } },
491 },
492 },
493 });
494 match paths {
495 Value::Object(paths) => paths,
496 _ => Map::new(),
497 }
498}
499
500
501/// Puts each operation's examples, where it has them, into its request
502/// and response. Path and query values go under `x-example-params` and
503/// `x-example-query`, which tools that build a request can use.
504fn attach_examples(paths: &mut Map<String, Value>) {
505 let examples = examples();
506 for methods in paths.values_mut() {
507 let Some(methods) = methods.as_object_mut() else { continue };
508 for operation in methods.values_mut() {
509 let id = operation["operationId"].as_str().unwrap_or_default().to_owned();
510 let tool = operation["x-mcp-tool"].as_str().unwrap_or_default().to_owned();
511 let Some(example) = examples.get(&id).or_else(|| examples.get(&tool)) else {
512 continue;
513 };
514 if let Some(notes) = example.get("notes").and_then(Value::as_str) {
515 let description = operation["description"].as_str().unwrap_or_default();
516 operation["description"] = json!(format!("{description}\n\n{notes}"));
517 }
518 if let Some(response) = example.get("response") {
519 let content = &mut operation["responses"]["200"]["content"]["application/json"];
520 if content.is_object() {
521 content["example"] = response.clone();
522 }
523 }
524 if let Some(request) = example.get("request") {
525 let content = &mut operation["requestBody"]["content"]["application/json"];
526 if content.is_object() {
527 content["example"] = request.clone();
528 }
529 }
530 for (key, extension) in [("params", "x-example-params"), ("query", "x-example-query")] {
531 if let Some(values) = example.get(key) {
532 operation[extension] = values.clone();
533 }
534 }
535 }
536 }
537}
538
539pub fn document() -> Value {
540 let mut paths = onboarding();
541 for route in ROUTES {
542 let entry = paths
543 .entry(openapi_path(route))
544 .or_insert_with(|| json!({}));
545 entry[route.method.to_lowercase()] = operation(route);
546 }
547 attach_examples(&mut paths);
548 let tags: Vec<Value> = SECTIONS
549 .iter()
550 .map(|(name, description, ops)| {
551 json!({
552 "name": name,
553 "description": description,
554 // The section's operations in reading order, by MCP tool name.
555 "x-tools": ops.iter().map(|op| op.name()).collect::<Vec<_>>(),
556 })
557 })
558 .collect();
559 let codes = ["unauthenticated", "payment_required", "forbidden", "not_found", "conflict", "invalid"];
560 json!({
561 "openapi": "3.1.0",
562 "info": {
563 "title": "g1t API",
564 "version": "1",
565 "description": "The REST API for g1t, a git forge built for agents. The same operations are available to agents as MCP tools at https://mcp.g1t.sh. Every name in a request or response body is `snake_case`; names you chose, such as a workflow's inputs or a secret's name, are returned as you wrote them.",
566 "license": { "name": "MIT", "identifier": "MIT" },
567 },
568 "servers": [{ "url": "https://api.g1t.sh" }],
569 "security": [{ "token": [] }, {}],
570 "tags": tags,
571 "paths": paths,
572 "components": {
573 "securitySchemes": {
574 "token": {
575 "type": "http",
576 "scheme": "bearer",
577 "description": "An access token, `g1t_…`. Public data needs none.",
578 },
579 },
580 "schemas": {
581 "Error": {
582 "type": "object",
583 "required": ["error"],
584 "properties": {
585 "error": {
586 "type": "object",
587 "required": ["code", "message"],
588 "properties": {
589 "code": { "type": "string", "enum": codes },
590 "message": { "type": "string" },
591 },
592 },
593 },
594 },
595 },
596 },
597 })
598}
599
600#[cfg(test)]
601mod tests {
602 use super::*;
603
604 #[test]
605 fn every_route_is_documented_once() {
606 let document = document();
607 let mut ids = Vec::new();
608 for (_, methods) in document["paths"].as_object().unwrap() {
609 for (_, operation) in methods.as_object().unwrap() {
610 ids.push(operation["operationId"].as_str().unwrap().to_owned());
611 }
612 }
613 for op in Op::ALL {
614 assert_eq!(
615 ids.iter().filter(|id| *id == op.name()).count(),
616 1,
617 "{}",
618 op.name()
619 );
620 }
621 let mut unique = ids.clone();
622 unique.sort();
623 unique.dedup();
624 assert_eq!(unique.len(), ids.len(), "operation ids repeat");
625 }
626
627 #[test]
628 fn path_and_query_inputs_are_not_repeated_in_the_body() {
629 let document = document();
630 let merge = &document["paths"]["/repos/{owner}/{name}/pulls/{number}/merge"]["post"];
631 let body = &merge["requestBody"]["content"]["application/json"]["schema"]["properties"];
632 assert!(body.get("keep_issue_open").is_some());
633 assert!(body.get("repo").is_none() && body.get("number").is_none());
634 let list = &document["paths"]["/repos"]["get"];
635 assert_eq!(list["parameters"][0]["name"], "q");
636 assert!(list.get("requestBody").is_none());
637 }
638
639 #[test]
640 fn every_operation_is_in_one_section() {
641 for op in Op::ALL {
642 let sections = SECTIONS
643 .iter()
644 .filter(|(_, _, ops)| ops.contains(&op))
645 .count();
646 assert_eq!(sections, 1, "{}", op.name());
647 }
648 }
649
650 #[test]
651 fn titles_read_as_sentences() {
652 assert_eq!(title(Op::CreateIssue), "Create an issue");
653 assert_eq!(title(Op::Whoami), "Get the current user");
654 }
655
656 #[test]
657 fn every_operation_has_an_example_response() {
658 let examples = examples();
659 assert!(!examples.is_empty(), "reference.json does not parse");
660 let document = document();
661 let mut known = Vec::new();
662 for (path, methods) in document["paths"].as_object().unwrap() {
663 for (method, operation) in methods.as_object().unwrap() {
664 known.push(operation["operationId"].as_str().unwrap().to_owned());
665 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
666 assert!(!example.is_null(), "{method} {path} has no example response");
667 }
668 }
669 for id in examples.keys() {
670 assert!(known.contains(id), "reference.json names {id}, which is not an operation");
671 }
672 }
673
674 #[test]
675 fn example_requests_send_only_what_the_body_takes() {
676 let document = document();
677 for (path, methods) in document["paths"].as_object().unwrap() {
678 for (method, operation) in methods.as_object().unwrap() {
679 let content = &operation["requestBody"]["content"]["application/json"];
680 let Some(example) = content["example"].as_object() else { continue };
681 let properties = &content["schema"]["properties"];
682 for key in example.keys() {
683 assert!(!properties[key].is_null(), "{method} {path}: {key} is not in the body");
684 }
685 }
686 }
687 }
688
689 /// The docs site's copy of the document. Run with `G1T_WRITE_OPENAPI=1`
690 /// to rewrite it after changing an operation.
691 #[test]
692 fn the_docs_copy_is_current() {
693 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../docs/src/data/openapi.json");
694 let current = serde_json::to_string_pretty(&document()).unwrap() + "\n";
695 if std::env::var_os("G1T_WRITE_OPENAPI").is_some() {
696 std::fs::write(path, &current).unwrap();
697 return;
698 }
699 let copy = std::fs::read_to_string(path).unwrap_or_default().replace("\r\n", "\n");
700 assert!(
701 copy == current,
702 "apps/docs/src/data/openapi.json is out of date: run G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi"
703 );
704 }
705
706 /// The reference shows responses as they are sent: `snake_case`.
707 #[test]
708 fn example_responses_are_snake_case() {
709 let document = document();
710 for (path, methods) in document["paths"].as_object().unwrap() {
711 for (method, operation) in methods.as_object().unwrap() {
712 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
713 let leaked = g1t_kit::wire::camel_case_keys(example);
714 assert!(leaked.is_empty(), "{method} {path} shows {leaked:?}");
715 }
716 }
717 }
718
719 /// Examples never hold anything that reads as a real credential, which
720 /// secret scanners rightly flag in a public repository: they end in `…`
721 /// after the prefix, as `whsec_…` and `g1t_…` do.
722 #[test]
723 fn examples_hold_no_real_looking_secrets() {
724 let prefixes = ["whsec_", "g1t_", "sk_live_", "sk_test_", "ghp_", "github_pat_", "xoxb-", "AKIA"];
725 for (line, text) in REFERENCE.lines().enumerate() {
726 for prefix in prefixes {
727 let mut rest = text;
728 while let Some(at) = rest.find(prefix) {
729 let after = &rest[at + prefix.len()..];
730 let run = after.chars().take_while(|c| c.is_ascii_alphanumeric()).count();
731 assert!(
732 run < 12,
733 "reference.json line {}: `{prefix}` followed by {run} characters reads as a real secret; write `{prefix}…`",
734 line + 1
735 );
736 rest = after;
737 }
738 }
739 }
740 }
741}