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