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