| 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 g1t_contracts::scopes::scope_for; |
| 8 | use serde_json::{Map, Value, json}; |
| 9 | |
| 10 | use crate::operations::Op; |
| 11 | use crate::rules::RulesOp; |
| 12 | use crate::security::SecurityOp; |
| 13 | use crate::rest::{ROUTES, Route}; |
| 14 | |
| 15 | /// The sections of the API reference: a name, what it covers, and its |
| 16 | /// operations in the order a reader meets them. |
| 17 | const SECTIONS: &[(&str, &str, &[Op])] = &[ |
| 18 | ( |
| 19 | "Accounts", |
| 20 | "Signing in from a tool, who a token acts as, and your email addresses.", |
| 21 | &[Op::Whoami, Op::ListEmails, Op::AddEmail, Op::RemoveEmail, Op::UpdateEmailSettings], |
| 22 | ), |
| 23 | ( |
| 24 | "Notifications", |
| 25 | "Your inbox: a thread for each thing you were told about (an issue, a pull request, a workflow on a branch, a deployment), why you were told, and what you subscribe to and watch. Your own: personal tokens and sessions only.", |
| 26 | &[ |
| 27 | Op::ListNotifications, |
| 28 | Op::MarkNotificationsRead, |
| 29 | Op::GetNotificationThread, |
| 30 | Op::MarkThreadRead, |
| 31 | Op::MarkThreadDone, |
| 32 | Op::SaveThread, |
| 33 | Op::SnoozeThread, |
| 34 | Op::GetThreadSubscription, |
| 35 | Op::SetThreadSubscription, |
| 36 | Op::DeleteThreadSubscription, |
| 37 | Op::GetRepoSubscription, |
| 38 | Op::SetRepoSubscription, |
| 39 | Op::DeleteRepoSubscription, |
| 40 | Op::ListWatchedRepos, |
| 41 | ], |
| 42 | ), |
| 43 | ( |
| 44 | "Pinned projects", |
| 45 | "The projects you keep at the top of a workspace's sidebar, in your order, up to eight a workspace. Your own: personal tokens and sessions only.", |
| 46 | &[Op::ListPinnedProjects, Op::PinProject, Op::UnpinProject, Op::ReorderPinnedProjects], |
| 47 | ), |
| 48 | ( |
| 49 | "Projects", |
| 50 | "A project is what a workspace builds and runs, from a repository or a root directory in one. Each says what it is, where it runs and where to find it: its homepage, docs and other links.", |
| 51 | &[Op::ListProjects, Op::GetProject, Op::UpdateProject], |
| 52 | ), |
| 53 | ( |
| 54 | "Workspaces", |
| 55 | "A workspace owns repositories and is the first part of their address. People and agents work in workspaces.", |
| 56 | &[Op::GetWorkspace, Op::CreateWorkspace, Op::UpdateWorkspace, Op::DeleteWorkspace], |
| 57 | ), |
| 58 | ( |
| 59 | "Invites", |
| 60 | "While g1t is invite-only, every new account needs an invite. Your invites, and inviting people into a workspace by email.", |
| 61 | &[ |
| 62 | Op::ListInvites, |
| 63 | Op::CreateInvite, |
| 64 | Op::RevokeInvite, |
| 65 | Op::ListWorkspaceInvites, |
| 66 | Op::InviteMember, |
| 67 | Op::RevokeWorkspaceInvite, |
| 68 | ], |
| 69 | ), |
| 70 | ( |
| 71 | "Billing", |
| 72 | "A workspace's usage, its budget, its AI credit, its invoices and its AI Gateway requests. Members read them; owners change the budget and buy credit, as people. g1t's agents never change billing.", |
| 73 | &[ |
| 74 | Op::GetUsage, |
| 75 | Op::GetBudget, |
| 76 | Op::SetBudget, |
| 77 | Op::GetAiCredit, |
| 78 | Op::BuyAiCredit, |
| 79 | Op::ListInvoices, |
| 80 | Op::GetBillingDetails, |
| 81 | Op::ListGatewayRequests, |
| 82 | ], |
| 83 | ), |
| 84 | ( |
| 85 | "Repositories", |
| 86 | "A repository, how it handles pull requests, and its timeline: renaming, archiving, moving and deleting it.", |
| 87 | &[ |
| 88 | Op::ListRepos, |
| 89 | Op::CreateRepo, |
| 90 | Op::GetRepo, |
| 91 | Op::UpdateRepo, |
| 92 | Op::RenameRepo, |
| 93 | Op::RenameBranch, |
| 94 | Op::SetRepoVisibility, |
| 95 | Op::ArchiveRepo, |
| 96 | Op::UnarchiveRepo, |
| 97 | Op::TransferRepo, |
| 98 | Op::DeleteRepo, |
| 99 | Op::ListDeletedRepos, |
| 100 | Op::RestoreRepo, |
| 101 | Op::PurgeRepo, |
| 102 | Op::GetRepoSettings, |
| 103 | Op::UpdateRepoSettings, |
| 104 | Op::ListCheckNames, |
| 105 | Op::GetCodeownersErrors, |
| 106 | Op::ListEvents, |
| 107 | ], |
| 108 | ), |
| 109 | ( |
| 110 | "Access", |
| 111 | "Who can do what in a repository: repository roles, people given a role on one repository (outside collaborators when they are not members), invitations, and a workspace's base permission.", |
| 112 | &[ |
| 113 | Op::ListCollaborators, |
| 114 | Op::AddCollaborator, |
| 115 | Op::UpdateCollaborator, |
| 116 | Op::RemoveCollaborator, |
| 117 | Op::GetCollaboratorPermission, |
| 118 | Op::ListRepoInvitations, |
| 119 | Op::RevokeRepoInvitation, |
| 120 | Op::ListMyRepoInvitations, |
| 121 | Op::AcceptRepoInvitation, |
| 122 | Op::DeclineRepoInvitation, |
| 123 | Op::SetBasePermission, |
| 124 | Op::ListOutsideCollaborators, |
| 125 | ], |
| 126 | ), |
| 127 | ( |
| 128 | "Teams", |
| 129 | "Groups of a workspace's members: given a role on repositories together, mentioned together as @workspace/team, and asked to review together. Any member may create a team; the workspace's owners and the team's maintainers manage it.", |
| 130 | &[ |
| 131 | Op::ListTeams, |
| 132 | Op::CreateTeam, |
| 133 | Op::GetTeam, |
| 134 | Op::UpdateTeam, |
| 135 | Op::DeleteTeam, |
| 136 | Op::ListTeamMembers, |
| 137 | Op::SetTeamMember, |
| 138 | Op::RemoveTeamMember, |
| 139 | Op::ListChildTeams, |
| 140 | Op::ListTeamRepos, |
| 141 | Op::SetTeamRepo, |
| 142 | Op::RemoveTeamRepo, |
| 143 | Op::SetTeamReviewAssignment, |
| 144 | Op::ListUserTeams, |
| 145 | ], |
| 146 | ), |
| 147 | ( |
| 148 | "Security", |
| 149 | "Secrets found in what is pushed and in a repository's history, and dependencies with known vulnerabilities: listing the alerts, and dismissing or reopening them.", |
| 150 | &[Op::ListSecurityAlerts, Op::DismissSecurityAlert, Op::ReopenSecurityAlert], |
| 151 | ), |
| 152 | ( |
| 153 | "Secret scanning", |
| 154 | "Secrets found in pushes and history, where each one is, pushing past push protection with a reason (and asking for approval when the workspace delegates bypasses), checking with a secret's issuer whether it still works, and custom patterns.", |
| 155 | &[ |
| 156 | Op::Security(SecurityOp::ListSecretAlerts), |
| 157 | Op::Security(SecurityOp::GetSecretAlert), |
| 158 | Op::Security(SecurityOp::UpdateSecretAlert), |
| 159 | Op::Security(SecurityOp::ListSecretLocations), |
| 160 | Op::Security(SecurityOp::BypassPushProtection), |
| 161 | Op::Security(SecurityOp::CheckSecretValidity), |
| 162 | Op::Security(SecurityOp::ListBypassRequests), |
| 163 | Op::Security(SecurityOp::ReviewBypassRequest), |
| 164 | Op::Security(SecurityOp::ListCustomPatterns), |
| 165 | Op::Security(SecurityOp::CreateCustomPattern), |
| 166 | Op::Security(SecurityOp::UpdateCustomPattern), |
| 167 | Op::Security(SecurityOp::DeleteCustomPattern), |
| 168 | Op::Security(SecurityOp::DryRunCustomPattern), |
| 169 | ], |
| 170 | ), |
| 171 | ( |
| 172 | "Code scanning", |
| 173 | "Results of static analysis tools, uploaded as SARIF: alerts on the default branch, the analyses that made them, uploads, and putting g1t on an alert to fix it.", |
| 174 | &[ |
| 175 | Op::Security(SecurityOp::ListCodeAlerts), |
| 176 | Op::Security(SecurityOp::GetCodeAlert), |
| 177 | Op::Security(SecurityOp::UpdateCodeAlert), |
| 178 | Op::Security(SecurityOp::ListAnalyses), |
| 179 | Op::Security(SecurityOp::UploadSarif), |
| 180 | Op::Security(SecurityOp::GetSarifUpload), |
| 181 | Op::Security(SecurityOp::FixAlert), |
| 182 | ], |
| 183 | ), |
| 184 | ( |
| 185 | "Supply chain", |
| 186 | "What a repository depends on: vulnerability alerts, the dependency graph, an SPDX SBOM of it, and comparing two commits' dependencies as dependency review does.", |
| 187 | &[ |
| 188 | Op::Security(SecurityOp::ListVulnerabilityAlerts), |
| 189 | Op::Security(SecurityOp::GetVulnerabilityAlert), |
| 190 | Op::Security(SecurityOp::UpdateVulnerabilityAlert), |
| 191 | Op::Security(SecurityOp::GetDependencyGraph), |
| 192 | Op::Security(SecurityOp::GetSbom), |
| 193 | Op::Security(SecurityOp::CompareDependencies), |
| 194 | ], |
| 195 | ), |
| 196 | ( |
| 197 | "Security settings", |
| 198 | "When pull request checks fail, dependency review's policy, delegated bypass and validity checks, and a workspace's security overview.", |
| 199 | &[ |
| 200 | Op::Security(SecurityOp::GetSettings), |
| 201 | Op::Security(SecurityOp::UpdateSettings), |
| 202 | Op::Security(SecurityOp::GetWorkspaceSettings), |
| 203 | Op::Security(SecurityOp::UpdateWorkspaceSettings), |
| 204 | Op::Security(SecurityOp::GetOverview), |
| 205 | ], |
| 206 | ), |
| 207 | ( |
| 208 | "Rules", |
| 209 | "Rulesets: what may happen to a repository's branches and tags and what a pull request needs before it merges, for a repository or across a workspace; the rules that hold for one branch; and how they judged each push and merge, with insights.", |
| 210 | &[ |
| 211 | Op::Rules(RulesOp::ListRepoRulesets), |
| 212 | Op::Rules(RulesOp::CreateRepoRuleset), |
| 213 | Op::Rules(RulesOp::GetRepoRuleset), |
| 214 | Op::Rules(RulesOp::UpdateRepoRuleset), |
| 215 | Op::Rules(RulesOp::DeleteRepoRuleset), |
| 216 | Op::Rules(RulesOp::GetBranchRules), |
| 217 | Op::Rules(RulesOp::ListRuleEvaluations), |
| 218 | Op::Rules(RulesOp::ListWorkspaceRulesets), |
| 219 | Op::Rules(RulesOp::CreateWorkspaceRuleset), |
| 220 | Op::Rules(RulesOp::GetWorkspaceRuleset), |
| 221 | Op::Rules(RulesOp::UpdateWorkspaceRuleset), |
| 222 | Op::Rules(RulesOp::DeleteWorkspaceRuleset), |
| 223 | Op::Rules(RulesOp::ListWorkspaceRuleEvaluations), |
| 224 | ], |
| 225 | ), |
| 226 | ( |
| 227 | "Issues", |
| 228 | "What should change in a repository, with labels and comments. Issues and pull requests share one sequence of numbers.", |
| 229 | &[ |
| 230 | Op::ListIssues, |
| 231 | Op::CreateIssue, |
| 232 | Op::GetIssue, |
| 233 | Op::UpdateIssue, |
| 234 | Op::CloseIssue, |
| 235 | Op::ReopenIssue, |
| 236 | Op::AssignIssue, |
| 237 | Op::Delegate, |
| 238 | Op::AddComment, |
| 239 | Op::ListIssueLabels, |
| 240 | Op::AddIssueLabels, |
| 241 | Op::SetIssueLabels, |
| 242 | Op::RemoveIssueLabels, |
| 243 | ], |
| 244 | ), |
| 245 | ( |
| 246 | "Labels and milestones", |
| 247 | "A repository's labels, which issues and pull requests carry by name, and its milestones, which gather them under a goal and a due date.", |
| 248 | &[ |
| 249 | Op::ListLabels, |
| 250 | Op::CreateLabel, |
| 251 | Op::UpdateLabel, |
| 252 | Op::DeleteLabel, |
| 253 | Op::AddDefaultLabels, |
| 254 | Op::ListMilestones, |
| 255 | Op::CreateMilestone, |
| 256 | Op::GetMilestone, |
| 257 | Op::UpdateMilestone, |
| 258 | Op::DeleteMilestone, |
| 259 | ], |
| 260 | ), |
| 261 | ( |
| 262 | "Plans", |
| 263 | "An outcome turned into the issues that would get there, with the order they must merge in.", |
| 264 | &[Op::PlanWork, Op::GetPlan, Op::ApplyPlan], |
| 265 | ), |
| 266 | ( |
| 267 | "Pull requests", |
| 268 | "A proposed change in its own fork or on a branch. Several can be made for one issue; the one merged resolves it.", |
| 269 | &[ |
| 270 | Op::ListPullRequests, |
| 271 | Op::CreatePullRequest, |
| 272 | Op::GetPullRequest, |
| 273 | Op::UpdatePullRequest, |
| 274 | Op::GetPullRequestChanges, |
| 275 | Op::MarkPullRequestReady, |
| 276 | Op::RequestReviewers, |
| 277 | Op::RemoveRequestedReviewers, |
| 278 | Op::ReviewPullRequest, |
| 279 | Op::MergePullRequest, |
| 280 | Op::ClosePullRequest, |
| 281 | Op::GetMergeQueue, |
| 282 | Op::MessageAgent, |
| 283 | Op::AnswerMessage, |
| 284 | Op::TakeMessages, |
| 285 | ], |
| 286 | ), |
| 287 | ( |
| 288 | "Sessions", |
| 289 | "The record of how a pull request was made: prompts, reasoning and the tools that ran.", |
| 290 | &[Op::ReadSession, Op::RecordSession], |
| 291 | ), |
| 292 | ( |
| 293 | "Memory", |
| 294 | "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.", |
| 295 | &[Op::Remember, Op::Recall], |
| 296 | ), |
| 297 | ( |
| 298 | "Search", |
| 299 | "One search across all of g1t: repositories, code, issues, pull requests, people and workspaces. Public content for everyone, and private content in workspaces you belong to.", |
| 300 | &[Op::Search], |
| 301 | ), |
| 302 | ( |
| 303 | "Context", |
| 304 | "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.", |
| 305 | &[Op::SearchContext, Op::GetEntity], |
| 306 | ), |
| 307 | ( |
| 308 | "Actions", |
| 309 | "GitHub Actions workflows in .g1t/workflows, their runs, and their jobs' logs.", |
| 310 | &[ |
| 311 | Op::ListWorkflows, |
| 312 | Op::ListWorkflowRuns, |
| 313 | Op::GetWorkflowRun, |
| 314 | Op::GetJobLogs, |
| 315 | Op::DispatchWorkflow, |
| 316 | Op::CancelWorkflowRun, |
| 317 | Op::RerunWorkflowRun, |
| 318 | Op::UpdateWorkflow, |
| 319 | ], |
| 320 | ), |
| 321 | ( |
| 322 | "Secrets and variables", |
| 323 | "Values that workflows and deployments read, per repository or for a whole workspace, with a row per environment.", |
| 324 | &[ |
| 325 | Op::ListActionsSecrets, |
| 326 | Op::SetActionsSecret, |
| 327 | Op::DeleteActionsSecret, |
| 328 | Op::ListActionsVariables, |
| 329 | Op::SetActionsVariable, |
| 330 | Op::DeleteActionsVariable, |
| 331 | ], |
| 332 | ), |
| 333 | ( |
| 334 | "Runners", |
| 335 | "Self-hosted runners: your own machines, which run your workflow jobs (and, if you choose, your agents' work) for $0 of g1t compute. They register with a short-lived token and only ever connect out.", |
| 336 | &[ |
| 337 | Op::ListRunners, |
| 338 | Op::CreateRunnerRegistrationToken, |
| 339 | Op::RemoveRunner, |
| 340 | Op::ListRunnerGroups, |
| 341 | Op::CreateRunnerGroup, |
| 342 | Op::UpdateRunnerGroup, |
| 343 | Op::DeleteRunnerGroup, |
| 344 | Op::GetRunnerSettings, |
| 345 | Op::UpdateRunnerSettings, |
| 346 | ], |
| 347 | ), |
| 348 | ( |
| 349 | "Webhooks", |
| 350 | "Signed HTTPS requests sent to your own address as things happen, for a repository or a whole workspace.", |
| 351 | &[ |
| 352 | Op::ListWebhooks, |
| 353 | Op::CreateWebhook, |
| 354 | Op::UpdateWebhook, |
| 355 | Op::DeleteWebhook, |
| 356 | Op::PingWebhook, |
| 357 | Op::ListWebhookDeliveries, |
| 358 | Op::RedeliverWebhook, |
| 359 | ], |
| 360 | ), |
| 361 | ( |
| 362 | "Integrations", |
| 363 | "A workspace's connections to outside systems: model providers, alert sources and issue trackers.", |
| 364 | &[ |
| 365 | Op::ListIntegrations, |
| 366 | Op::ConnectIntegration, |
| 367 | Op::DisconnectIntegration, |
| 368 | Op::TestIntegration, |
| 369 | Op::GetModelRoutes, |
| 370 | Op::SetModelRoutes, |
| 371 | Op::GetContext, |
| 372 | Op::ImportIssue, |
| 373 | ], |
| 374 | ), |
| 375 | ]; |
| 376 | |
| 377 | /// The section of the API reference an operation is listed under. |
| 378 | fn tag(op: Op) -> &'static str { |
| 379 | SECTIONS |
| 380 | .iter() |
| 381 | .find(|(_, _, ops)| ops.contains(&op)) |
| 382 | .map_or("Repositories", |(name, _, _)| name) |
| 383 | } |
| 384 | |
| 385 | /// What an operation's page is called, as a short sentence. |
| 386 | fn title(op: Op) -> &'static str { |
| 387 | match op { |
| 388 | Op::Whoami => "Get the current user", |
| 389 | Op::GetWorkspace => "Get a workspace", |
| 390 | Op::CreateWorkspace => "Create a workspace", |
| 391 | Op::DeleteWorkspace => "Delete a workspace", |
| 392 | Op::UpdateWorkspace => "Update a workspace", |
| 393 | Op::ListEmails => "List your email addresses", |
| 394 | Op::AddEmail => "Add an email address", |
| 395 | Op::RemoveEmail => "Remove an email address", |
| 396 | Op::UpdateEmailSettings => "Change your email settings", |
| 397 | Op::ListInvites => "List your invites", |
| 398 | Op::CreateInvite => "Create an invite", |
| 399 | Op::RevokeInvite => "Revoke an invite", |
| 400 | Op::ListWorkspaceInvites => "List a workspace's invites", |
| 401 | Op::InviteMember => "Invite someone to a workspace", |
| 402 | Op::RevokeWorkspaceInvite => "Revoke a workspace's invite", |
| 403 | Op::TransferRepo => "Transfer a repository", |
| 404 | Op::RenameRepo => "Rename a repository", |
| 405 | Op::RenameBranch => "Rename a branch", |
| 406 | Op::ArchiveRepo => "Archive a repository", |
| 407 | Op::UnarchiveRepo => "Unarchive a repository", |
| 408 | Op::SetRepoVisibility => "Change a repository's visibility", |
| 409 | Op::DeleteRepo => "Delete a repository", |
| 410 | Op::ListDeletedRepos => "List recently deleted repositories", |
| 411 | Op::RestoreRepo => "Restore a deleted repository", |
| 412 | Op::PurgeRepo => "Purge a deleted repository", |
| 413 | Op::ListRepos => "List repositories", |
| 414 | Op::GetRepo => "Get a repository", |
| 415 | Op::CreateRepo => "Create a repository", |
| 416 | Op::UpdateRepo => "Update a repository", |
| 417 | Op::GetRepoSettings => "Get repository settings", |
| 418 | Op::UpdateRepoSettings => "Update repository settings", |
| 419 | Op::ListCheckNames => "List check names", |
| 420 | Op::GetMergeQueue => "Get the merge queue", |
| 421 | Op::MessageAgent => "Message an agent", |
| 422 | Op::AnswerMessage => "Answer a message", |
| 423 | Op::TakeMessages => "Take new messages", |
| 424 | Op::Remember => "Remember something", |
| 425 | Op::Recall => "Recall memory", |
| 426 | Op::SearchContext => "Search the context hub", |
| 427 | Op::GetEntity => "Get a catalog entry", |
| 428 | Op::Search => "Search g1t", |
| 429 | Op::ListIssues => "List issues", |
| 430 | Op::GetIssue => "Get an issue", |
| 431 | Op::CreateIssue => "Create an issue", |
| 432 | Op::UpdateIssue => "Update an issue", |
| 433 | Op::CloseIssue => "Close an issue", |
| 434 | Op::ReopenIssue => "Reopen an issue", |
| 435 | Op::AssignIssue => "Assign an issue to g1t", |
| 436 | Op::Delegate => "Put an agent on it", |
| 437 | Op::PlanWork => "Plan work", |
| 438 | Op::GetPlan => "Get a plan", |
| 439 | Op::ApplyPlan => "Apply a plan", |
| 440 | Op::ListLabels => "List labels", |
| 441 | Op::CreateLabel => "Create a label", |
| 442 | Op::UpdateLabel => "Update a label", |
| 443 | Op::DeleteLabel => "Delete a label", |
| 444 | Op::AddDefaultLabels => "Add the default labels", |
| 445 | Op::ListIssueLabels => "List an issue's labels", |
| 446 | Op::AddIssueLabels => "Add labels to an issue", |
| 447 | Op::SetIssueLabels => "Set an issue's labels", |
| 448 | Op::RemoveIssueLabels => "Remove labels from an issue", |
| 449 | Op::ListMilestones => "List milestones", |
| 450 | Op::GetMilestone => "Get a milestone", |
| 451 | Op::CreateMilestone => "Create a milestone", |
| 452 | Op::UpdateMilestone => "Update a milestone", |
| 453 | Op::DeleteMilestone => "Delete a milestone", |
| 454 | Op::UpdatePullRequest => "Update a pull request", |
| 455 | Op::AddComment => "Add a comment", |
| 456 | Op::ReviewPullRequest => "Review a pull request", |
| 457 | Op::ListPullRequests => "List pull requests", |
| 458 | Op::GetPullRequest => "Get a pull request", |
| 459 | Op::CreatePullRequest => "Create a pull request", |
| 460 | Op::RecordSession => "Record session entries", |
| 461 | Op::ReadSession => "Read a session", |
| 462 | Op::MarkPullRequestReady => "Mark a pull request ready", |
| 463 | Op::ClosePullRequest => "Close a pull request", |
| 464 | Op::GetPullRequestChanges => "Get a pull request's changes", |
| 465 | Op::MergePullRequest => "Merge a pull request", |
| 466 | Op::ListEvents => "List repository events", |
| 467 | Op::ListIntegrations => "List integrations", |
| 468 | Op::ConnectIntegration => "Connect an integration", |
| 469 | Op::DisconnectIntegration => "Disconnect an integration", |
| 470 | Op::TestIntegration => "Test an integration", |
| 471 | Op::GetContext => "Look up a ticket", |
| 472 | Op::ImportIssue => "Import an issue", |
| 473 | Op::GetModelRoutes => "Get model routes", |
| 474 | Op::SetModelRoutes => "Set model routes", |
| 475 | Op::ListWebhooks => "List webhooks", |
| 476 | Op::CreateWebhook => "Create a webhook", |
| 477 | Op::UpdateWebhook => "Update a webhook", |
| 478 | Op::DeleteWebhook => "Delete a webhook", |
| 479 | Op::PingWebhook => "Ping a webhook", |
| 480 | Op::ListWebhookDeliveries => "List webhook deliveries", |
| 481 | Op::RedeliverWebhook => "Redeliver a webhook delivery", |
| 482 | Op::ListWorkflows => "List workflows", |
| 483 | Op::ListWorkflowRuns => "List workflow runs", |
| 484 | Op::GetWorkflowRun => "Get a workflow run", |
| 485 | Op::GetJobLogs => "Get a job's log", |
| 486 | Op::DispatchWorkflow => "Run a workflow", |
| 487 | Op::CancelWorkflowRun => "Cancel a workflow run", |
| 488 | Op::RerunWorkflowRun => "Re-run a workflow run", |
| 489 | Op::UpdateWorkflow => "Turn a workflow on or off", |
| 490 | Op::ListActionsSecrets => "List secrets", |
| 491 | Op::SetActionsSecret => "Set a secret", |
| 492 | Op::DeleteActionsSecret => "Delete a secret", |
| 493 | Op::ListActionsVariables => "List variables", |
| 494 | Op::SetActionsVariable => "Set a variable", |
| 495 | Op::DeleteActionsVariable => "Delete a variable", |
| 496 | Op::ListRunners => "List self-hosted runners", |
| 497 | Op::ListRunnerGroups => "List runner groups", |
| 498 | Op::GetRunnerSettings => "Get runner settings", |
| 499 | Op::CreateRunnerRegistrationToken => "Create a runner registration token", |
| 500 | Op::RemoveRunner => "Remove a self-hosted runner", |
| 501 | Op::CreateRunnerGroup => "Create a runner group", |
| 502 | Op::UpdateRunnerGroup => "Change a runner group", |
| 503 | Op::DeleteRunnerGroup => "Delete a runner group", |
| 504 | Op::UpdateRunnerSettings => "Change runner settings", |
| 505 | Op::ListCollaborators => "List who has access", |
| 506 | Op::AddCollaborator => "Add a collaborator", |
| 507 | Op::UpdateCollaborator => "Change a collaborator's role", |
| 508 | Op::RemoveCollaborator => "Remove a collaborator", |
| 509 | Op::GetCollaboratorPermission => "Get someone's permission", |
| 510 | Op::ListRepoInvitations => "List a repository's invitations", |
| 511 | Op::RevokeRepoInvitation => "Revoke a repository invitation", |
| 512 | Op::ListMyRepoInvitations => "List your repository invitations", |
| 513 | Op::AcceptRepoInvitation => "Accept a repository invitation", |
| 514 | Op::DeclineRepoInvitation => "Decline a repository invitation", |
| 515 | Op::SetBasePermission => "Set the base permission", |
| 516 | Op::ListOutsideCollaborators => "List outside collaborators", |
| 517 | Op::ListSecurityAlerts => "List security alerts", |
| 518 | Op::DismissSecurityAlert => "Dismiss a security alert", |
| 519 | Op::ReopenSecurityAlert => "Reopen a security alert", |
| 520 | Op::ListNotifications => "List notifications", |
| 521 | Op::MarkNotificationsRead => "Mark notifications read", |
| 522 | Op::GetNotificationThread => "Get a thread", |
| 523 | Op::MarkThreadRead => "Mark a thread read", |
| 524 | Op::MarkThreadDone => "Mark a thread done", |
| 525 | Op::SaveThread => "Save a thread", |
| 526 | Op::SnoozeThread => "Snooze a thread", |
| 527 | Op::GetThreadSubscription => "Get a thread subscription", |
| 528 | Op::SetThreadSubscription => "Set a thread subscription", |
| 529 | Op::DeleteThreadSubscription => "Unsubscribe from a thread", |
| 530 | Op::GetRepoSubscription => "Get how you watch a repository", |
| 531 | Op::SetRepoSubscription => "Watch a repository", |
| 532 | Op::DeleteRepoSubscription => "Stop watching a repository", |
| 533 | Op::ListWatchedRepos => "List repositories you watch", |
| 534 | Op::ListPinnedProjects => "List your pinned projects", |
| 535 | Op::GetUsage => "Get a workspace's usage", |
| 536 | Op::GetBudget => "Get a workspace's budget", |
| 537 | Op::SetBudget => "Change a workspace's budget", |
| 538 | Op::GetAiCredit => "Get a workspace's AI credit", |
| 539 | Op::BuyAiCredit => "Buy AI credit", |
| 540 | Op::ListInvoices => "List a workspace's invoices", |
| 541 | Op::GetBillingDetails => "Get a workspace's billing details", |
| 542 | Op::ListGatewayRequests => "List a workspace's AI Gateway requests", |
| 543 | Op::PinProject => "Pin a project", |
| 544 | Op::UnpinProject => "Unpin a project", |
| 545 | Op::ReorderPinnedProjects => "Reorder your pinned projects", |
| 546 | Op::ListProjects => "List a workspace's projects", |
| 547 | Op::GetProject => "Get a project", |
| 548 | Op::UpdateProject => "Update a project", |
| 549 | Op::ListTeams => "List teams", |
| 550 | Op::GetTeam => "Get a team", |
| 551 | Op::CreateTeam => "Create a team", |
| 552 | Op::UpdateTeam => "Update a team", |
| 553 | Op::DeleteTeam => "Delete a team", |
| 554 | Op::ListTeamMembers => "List a team's members", |
| 555 | Op::SetTeamMember => "Add or change a team member", |
| 556 | Op::RemoveTeamMember => "Remove a team member", |
| 557 | Op::ListChildTeams => "List child teams", |
| 558 | Op::ListTeamRepos => "List a team's repositories", |
| 559 | Op::SetTeamRepo => "Give a team a role on a repository", |
| 560 | Op::RemoveTeamRepo => "Remove a team from a repository", |
| 561 | Op::SetTeamReviewAssignment => "Set a team's review assignment", |
| 562 | Op::ListUserTeams => "List someone's teams", |
| 563 | Op::RequestReviewers => "Request reviewers", |
| 564 | Op::RemoveRequestedReviewers => "Remove requested reviewers", |
| 565 | Op::GetCodeownersErrors => "List CODEOWNERS errors", |
| 566 | Op::Security(op) => op.title(), |
| 567 | Op::Rules(op) => op.title(), |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | /// Why an operation can be refused with `402 payment_required`, if it |
| 572 | /// can: the ones that start an agent, when the workspace has no credit, |
| 573 | /// and the ones that make a repository private in a workspace, when a free |
| 574 | /// workspace's private storage has no room for it. |
| 575 | fn may_need_payment(op: Op) -> Option<&'static str> { |
| 576 | match op { |
| 577 | Op::AssignIssue | Op::PlanWork | Op::ApplyPlan => Some("The workspace has no agent credit."), |
| 578 | Op::UpdateRepo | Op::SetRepoVisibility | Op::TransferRepo => Some( |
| 579 | "A free workspace's private storage has no room for this private repository.", |
| 580 | ), |
| 581 | _ => None, |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | /// What the reference says beyond each operation's own description, keyed |
| 586 | /// by operation id, written by hand from what the services return: `notes` |
| 587 | /// (Markdown, added to the description) and example `params` (path), |
| 588 | /// `query`, `request` (body) and `response`. |
| 589 | const REFERENCE: &str = include_str!("reference.json"); |
| 590 | |
| 591 | fn examples() -> Map<String, Value> { |
| 592 | match serde_json::from_str(REFERENCE) { |
| 593 | Ok(Value::Object(examples)) => examples, |
| 594 | _ => Map::new(), |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | /// `/repos/:owner/:name` as OpenAPI writes it: `/repos/{owner}/{name}`. |
| 599 | fn openapi_path(route: &Route) -> String { |
| 600 | route |
| 601 | .path |
| 602 | .split('/') |
| 603 | .map(|segment| match segment.strip_prefix(':') { |
| 604 | Some(name) => format!("{{{name}}}"), |
| 605 | None => segment.to_owned(), |
| 606 | }) |
| 607 | .collect::<Vec<_>>() |
| 608 | .join("/") |
| 609 | } |
| 610 | |
| 611 | fn error_response(description: &str) -> Value { |
| 612 | json!({ |
| 613 | "description": description, |
| 614 | "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }, |
| 615 | }) |
| 616 | } |
| 617 | |
| 618 | /// A parameter in the path or the query, described by the operation's |
| 619 | /// input schema where it has the same name. |
| 620 | fn parameter(name: &str, place: &str, required: bool, schema: Option<&Value>) -> Value { |
| 621 | let mut schema = schema.cloned().unwrap_or_else(|| json!({ "type": "string" })); |
| 622 | let description = match name { |
| 623 | "owner" => Some(Value::from("The workspace that owns the repository.")), |
| 624 | "name" => Some(Value::from("The repository's name.")), |
| 625 | _ => schema.as_object_mut().and_then(|schema| schema.remove("description")), |
| 626 | }; |
| 627 | let mut parameter = json!({ |
| 628 | "name": name, |
| 629 | "in": place, |
| 630 | "required": required, |
| 631 | "schema": schema, |
| 632 | }); |
| 633 | if let Some(description) = description { |
| 634 | parameter["description"] = description; |
| 635 | } |
| 636 | parameter |
| 637 | } |
| 638 | |
| 639 | /// The operation id of a route. An operation reached at a workspace's |
| 640 | /// address as well as a repository's is documented once for each, with its |
| 641 | /// own id; GitHub's alternative addresses for one operation keep GitHub's |
| 642 | /// names. |
| 643 | fn operation_id(route: &Route) -> String { |
| 644 | let op = route.op; |
| 645 | let base = match (route.method, route.path.rsplit('/').next().unwrap_or_default()) { |
| 646 | ("PUT", "enable") => "enable_workflow".to_owned(), |
| 647 | ("PUT", "disable") => "disable_workflow".to_owned(), |
| 648 | ("POST", "rerun-failed-jobs") => "rerun_failed_jobs".to_owned(), |
| 649 | ("PATCH", ":setting") => "update_actions_variable".to_owned(), |
| 650 | ("GET", "runs") if route.path.contains("/workflows/:workflow/") => "list_runs_of_workflow".to_owned(), |
| 651 | // One repository's notifications, and an issue's subscription by |
| 652 | // its number rather than a thread's id. |
| 653 | (_, "notifications") if route.path.starts_with("/repos/") => match op { |
| 654 | Op::ListNotifications => "list_repo_notifications".to_owned(), |
| 655 | _ => "mark_repo_notifications_read".to_owned(), |
| 656 | }, |
| 657 | (method, "subscription") if route.path.contains("/issues/:number/") => match method { |
| 658 | "GET" => "get_issue_subscription".to_owned(), |
| 659 | "PUT" => "set_issue_subscription".to_owned(), |
| 660 | _ => "delete_issue_subscription".to_owned(), |
| 661 | }, |
| 662 | // One label off an issue, by its name in the path. |
| 663 | ("DELETE", ":label") if route.path.contains("/issues/:number/") => "remove_issue_label".to_owned(), |
| 664 | ("DELETE", "saved") => "unsave_thread".to_owned(), |
| 665 | ("DELETE", "snooze") => "unsnooze_thread".to_owned(), |
| 666 | _ => op.name().to_owned(), |
| 667 | }; |
| 668 | if route.path.starts_with("/workspaces/") && ROUTES.iter().any(|other| other.op == op && other.path.starts_with("/repos/")) { |
| 669 | format!("{base}_for_workspace") |
| 670 | } else { |
| 671 | base |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | /// The summary of a route: its operation's title, or for one of GitHub's |
| 676 | /// alternative addresses, what that address does. |
| 677 | fn summary(route: &Route, id: &str) -> String { |
| 678 | let base = match id.trim_end_matches("_for_workspace") { |
| 679 | "enable_workflow" => "Turn a workflow on", |
| 680 | "disable_workflow" => "Turn a workflow off", |
| 681 | "rerun_failed_jobs" => "Re-run failed jobs", |
| 682 | "update_actions_variable" => "Update a variable", |
| 683 | "list_runs_of_workflow" => "List a workflow's runs", |
| 684 | "list_repo_notifications" => "List a repository's notifications", |
| 685 | "mark_repo_notifications_read" => "Mark a repository's notifications read", |
| 686 | "get_issue_subscription" => "Get your subscription to an issue", |
| 687 | "set_issue_subscription" => "Subscribe to an issue", |
| 688 | "delete_issue_subscription" => "Unsubscribe from an issue", |
| 689 | "unsave_thread" => "Unsave a thread", |
| 690 | "unsnooze_thread" => "Bring a snoozed thread back", |
| 691 | _ => title(route.op), |
| 692 | }; |
| 693 | if id.ends_with("_for_workspace") { |
| 694 | format!("{base} for a workspace") |
| 695 | } else { |
| 696 | base.to_owned() |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | fn operation(route: &Route) -> Value { |
| 701 | let op = route.op; |
| 702 | let path_params: Vec<&str> = route.params().collect(); |
| 703 | // `owner` and `name` in the path stand for the operation's `repo` input. |
| 704 | let covered = |name: &str| name == "repo" || path_params.contains(&name); |
| 705 | let all_properties = op.properties(); |
| 706 | let mut properties = all_properties.clone(); |
| 707 | properties.retain(|name, _| !covered(name)); |
| 708 | let required: Vec<String> = op |
| 709 | .required() |
| 710 | .into_iter() |
| 711 | .filter(|name| !covered(name)) |
| 712 | .collect(); |
| 713 | |
| 714 | let mut parameters: Vec<Value> = path_params |
| 715 | .iter() |
| 716 | .map(|name| parameter(name, "path", true, all_properties.get(*name))) |
| 717 | .collect(); |
| 718 | let mut body = Value::Null; |
| 719 | if route.method == "GET" { |
| 720 | for (name, key) in route.query { |
| 721 | parameters.push(parameter( |
| 722 | name, |
| 723 | "query", |
| 724 | required.iter().any(|required| required == key), |
| 725 | properties.get(*key), |
| 726 | )); |
| 727 | } |
| 728 | } else if !properties.is_empty() { |
| 729 | let mut schema = json!({ "type": "object", "properties": properties }); |
| 730 | if !required.is_empty() { |
| 731 | schema["required"] = json!(required); |
| 732 | } |
| 733 | body = json!({ |
| 734 | "required": !required.is_empty(), |
| 735 | "content": { "application/json": { "schema": schema } }, |
| 736 | }); |
| 737 | } |
| 738 | |
| 739 | let id = operation_id(route); |
| 740 | let mut responses = Map::new(); |
| 741 | responses.insert( |
| 742 | "200".into(), |
| 743 | json!({ |
| 744 | "description": "Success.", |
| 745 | "content": { "application/json": { "schema": {} } }, |
| 746 | }), |
| 747 | ); |
| 748 | responses.insert( |
| 749 | "401".into(), |
| 750 | error_response("A token is required, or the one sent is not valid."), |
| 751 | ); |
| 752 | if let Some(reason) = may_need_payment(op) { |
| 753 | responses.insert("402".into(), error_response(reason)); |
| 754 | } |
| 755 | responses.insert( |
| 756 | "403".into(), |
| 757 | error_response("Signed in, but not allowed to do this: the role you have is not enough, or the token lacks the scope it needs, which `needed_scope` names."), |
| 758 | ); |
| 759 | if !matches!(op, Op::Whoami | Op::ListRepos | Op::Search) { |
| 760 | responses.insert("404".into(), error_response("It does not exist, or you cannot see it.")); |
| 761 | } |
| 762 | if route.method != "GET" { |
| 763 | responses.insert( |
| 764 | "409".into(), |
| 765 | error_response("The request conflicts with the current state."), |
| 766 | ); |
| 767 | } |
| 768 | if op != Op::Whoami { |
| 769 | responses.insert("422".into(), error_response("The input is not valid.")); |
| 770 | } |
| 771 | // Public data can be read without a token; everything else needs one. |
| 772 | let scope: Vec<&str> = scope_for(op.name()).map(|scope| scope.as_str()).into_iter().collect(); |
| 773 | let security = if op.needs_user() { |
| 774 | json!([{ "token": scope }]) |
| 775 | } else { |
| 776 | json!([{ "token": scope }, {}]) |
| 777 | }; |
| 778 | let (tool, action) = crate::tools::TOOLS |
| 779 | .iter() |
| 780 | .find_map(|tool| { |
| 781 | tool.actions |
| 782 | .iter() |
| 783 | .find(|action| action.op == op) |
| 784 | .map(|action| (tool.name, action.name)) |
| 785 | }) |
| 786 | .unwrap_or_default(); |
| 787 | let mut described = json!({ |
| 788 | "operationId": id, |
| 789 | "tags": [tag(op)], |
| 790 | "summary": summary(route, &id), |
| 791 | "description": op.description(), |
| 792 | "x-operation": op.name(), |
| 793 | "x-mcp-tool": tool, |
| 794 | "x-mcp-action": action, |
| 795 | "x-scope": scope.first().copied(), |
| 796 | "security": security, |
| 797 | "parameters": parameters, |
| 798 | "responses": responses, |
| 799 | }); |
| 800 | if !body.is_null() { |
| 801 | described["requestBody"] = body; |
| 802 | } |
| 803 | described |
| 804 | } |
| 805 | |
| 806 | /// Entries for device sign-in, which is not an operation. |
| 807 | fn onboarding() -> Map<String, Value> { |
| 808 | let paths = json!({ |
| 809 | "/device/code": { |
| 810 | "post": { |
| 811 | "operationId": "device_code", |
| 812 | "tags": ["Accounts"], |
| 813 | "summary": "Start signing in", |
| 814 | "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`.", |
| 815 | "security": [], |
| 816 | "requestBody": { |
| 817 | "content": { "application/json": { "schema": { |
| 818 | "type": "object", |
| 819 | "properties": { |
| 820 | "client_name": { |
| 821 | "type": "string", |
| 822 | "description": "What is asking, shown to the person approving. For example, Claude Code.", |
| 823 | }, |
| 824 | }, |
| 825 | } } }, |
| 826 | }, |
| 827 | "responses": { "200": { |
| 828 | "description": "The codes for this sign-in.", |
| 829 | "content": { "application/json": { "schema": { |
| 830 | "type": "object", |
| 831 | "properties": { |
| 832 | "device_code": { "type": "string", "description": "Secret. Send it to /device/token." }, |
| 833 | "user_code": { "type": "string", "description": "Shown to the person, like WDJB-MJHT." }, |
| 834 | "verification_uri": { "type": "string" }, |
| 835 | "verification_uri_complete": { |
| 836 | "type": "string", |
| 837 | "description": "The link to give the person; it carries the code.", |
| 838 | }, |
| 839 | "expires_in": { "type": "integer", "description": "Seconds until the codes expire." }, |
| 840 | "interval": { "type": "integer", "description": "Seconds to wait between polls." }, |
| 841 | }, |
| 842 | } } }, |
| 843 | } }, |
| 844 | }, |
| 845 | }, |
| 846 | "/device/token": { |
| 847 | "post": { |
| 848 | "operationId": "device_token", |
| 849 | "tags": ["Accounts"], |
| 850 | "summary": "Finish signing in", |
| 851 | "description": "Asks whether the person has approved. Poll no faster than the interval. The token is returned once.", |
| 852 | "security": [], |
| 853 | "requestBody": { |
| 854 | "required": true, |
| 855 | "content": { "application/json": { "schema": { |
| 856 | "type": "object", |
| 857 | "required": ["device_code"], |
| 858 | "properties": { "device_code": { "type": "string" } }, |
| 859 | } } }, |
| 860 | }, |
| 861 | "responses": { "200": { |
| 862 | "description": "The state of the sign-in.", |
| 863 | "content": { "application/json": { "schema": { |
| 864 | "type": "object", |
| 865 | "required": ["status"], |
| 866 | "properties": { |
| 867 | "status": { "type": "string", "enum": ["pending", "approved", "denied", "expired"] }, |
| 868 | "token": { "type": "string", "description": "Present when approved." }, |
| 869 | "username": { "type": "string" }, |
| 870 | "verified": { |
| 871 | "type": "boolean", |
| 872 | "description": "Whether the account's email is confirmed.", |
| 873 | }, |
| 874 | }, |
| 875 | } } }, |
| 876 | } }, |
| 877 | }, |
| 878 | }, |
| 879 | }); |
| 880 | match paths { |
| 881 | Value::Object(paths) => paths, |
| 882 | _ => Map::new(), |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | |
| 887 | /// Puts each operation's examples, where it has them, into its request |
| 888 | /// and response. Path and query values go under `x-example-params` and |
| 889 | /// `x-example-query`, which tools that build a request can use. |
| 890 | fn attach_examples(paths: &mut Map<String, Value>) { |
| 891 | let examples = examples(); |
| 892 | for methods in paths.values_mut() { |
| 893 | let Some(methods) = methods.as_object_mut() else { continue }; |
| 894 | for operation in methods.values_mut() { |
| 895 | let id = operation["operationId"].as_str().unwrap_or_default().to_owned(); |
| 896 | let name = operation["x-operation"].as_str().unwrap_or_default().to_owned(); |
| 897 | let Some(example) = examples.get(&id).or_else(|| examples.get(&name)) else { |
| 898 | continue; |
| 899 | }; |
| 900 | if let Some(notes) = example.get("notes").and_then(Value::as_str) { |
| 901 | let description = operation["description"].as_str().unwrap_or_default(); |
| 902 | operation["description"] = json!(format!("{description}\n\n{notes}")); |
| 903 | } |
| 904 | if let Some(response) = example.get("response") { |
| 905 | let content = &mut operation["responses"]["200"]["content"]["application/json"]; |
| 906 | if content.is_object() { |
| 907 | content["example"] = response.clone(); |
| 908 | } |
| 909 | } |
| 910 | if let Some(request) = example.get("request") { |
| 911 | let content = &mut operation["requestBody"]["content"]["application/json"]; |
| 912 | if content.is_object() { |
| 913 | content["example"] = request.clone(); |
| 914 | } |
| 915 | } |
| 916 | for (key, extension) in [("params", "x-example-params"), ("query", "x-example-query")] { |
| 917 | if let Some(values) = example.get(key) { |
| 918 | operation[extension] = values.clone(); |
| 919 | } |
| 920 | } |
| 921 | } |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | pub fn document() -> Value { |
| 926 | let mut paths = onboarding(); |
| 927 | for route in ROUTES { |
| 928 | let entry = paths |
| 929 | .entry(openapi_path(route)) |
| 930 | .or_insert_with(|| json!({})); |
| 931 | entry[route.method.to_lowercase()] = operation(route); |
| 932 | } |
| 933 | attach_examples(&mut paths); |
| 934 | let tags: Vec<Value> = SECTIONS |
| 935 | .iter() |
| 936 | .map(|(name, description, ops)| { |
| 937 | json!({ |
| 938 | "name": name, |
| 939 | "description": description, |
| 940 | // The section's operations in reading order, by MCP tool name. |
| 941 | "x-tools": ops.iter().map(|op| op.name()).collect::<Vec<_>>(), |
| 942 | }) |
| 943 | }) |
| 944 | .collect(); |
| 945 | let codes = ["unauthenticated", "payment_required", "forbidden", "not_found", "conflict", "invalid"]; |
| 946 | json!({ |
| 947 | "openapi": "3.1.0", |
| 948 | "info": { |
| 949 | "title": "g1t API", |
| 950 | "version": "1", |
| 951 | "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.", |
| 952 | "license": { "name": "MIT", "identifier": "MIT" }, |
| 953 | }, |
| 954 | "servers": [{ "url": "https://api.g1t.sh" }], |
| 955 | "security": [{ "token": [] }, {}], |
| 956 | "tags": tags, |
| 957 | "paths": paths, |
| 958 | "components": { |
| 959 | "securitySchemes": { |
| 960 | "token": { |
| 961 | "type": "http", |
| 962 | "scheme": "bearer", |
| 963 | "description": "An access token, `g1t_…`. Public data needs none. Each operation names the scope a token needs for it; see https://docs.g1t.sh/guides/authentication/#scopes.", |
| 964 | }, |
| 965 | }, |
| 966 | "schemas": { |
| 967 | "Error": { |
| 968 | "type": "object", |
| 969 | "required": ["error"], |
| 970 | "properties": { |
| 971 | "error": { |
| 972 | "type": "object", |
| 973 | "required": ["code", "message"], |
| 974 | "properties": { |
| 975 | "code": { "type": "string", "enum": codes }, |
| 976 | "message": { "type": "string" }, |
| 977 | "needed_scope": { |
| 978 | "type": "string", |
| 979 | "description": "On a 403 for an access token without the scope the call needs: that scope, such as `issues:write`.", |
| 980 | }, |
| 981 | }, |
| 982 | }, |
| 983 | }, |
| 984 | }, |
| 985 | }, |
| 986 | }, |
| 987 | }) |
| 988 | } |
| 989 | |
| 990 | #[cfg(test)] |
| 991 | mod tests { |
| 992 | use super::*; |
| 993 | |
| 994 | #[test] |
| 995 | fn every_route_is_documented_once() { |
| 996 | let document = document(); |
| 997 | let mut ids = Vec::new(); |
| 998 | for (_, methods) in document["paths"].as_object().unwrap() { |
| 999 | for (_, operation) in methods.as_object().unwrap() { |
| 1000 | ids.push(operation["operationId"].as_str().unwrap().to_owned()); |
| 1001 | } |
| 1002 | } |
| 1003 | for op in Op::ALL { |
| 1004 | assert_eq!( |
| 1005 | ids.iter().filter(|id| *id == op.name()).count(), |
| 1006 | 1, |
| 1007 | "{}", |
| 1008 | op.name() |
| 1009 | ); |
| 1010 | } |
| 1011 | let mut unique = ids.clone(); |
| 1012 | unique.sort(); |
| 1013 | unique.dedup(); |
| 1014 | assert_eq!(unique.len(), ids.len(), "operation ids repeat"); |
| 1015 | } |
| 1016 | |
| 1017 | #[test] |
| 1018 | fn path_and_query_inputs_are_not_repeated_in_the_body() { |
| 1019 | let document = document(); |
| 1020 | let merge = &document["paths"]["/repos/{owner}/{name}/pulls/{number}/merge"]["post"]; |
| 1021 | let body = &merge["requestBody"]["content"]["application/json"]["schema"]["properties"]; |
| 1022 | assert!(body.get("keep_issue_open").is_some()); |
| 1023 | assert!(body.get("repo").is_none() && body.get("number").is_none()); |
| 1024 | let list = &document["paths"]["/repos"]["get"]; |
| 1025 | assert_eq!(list["parameters"][0]["name"], "q"); |
| 1026 | assert!(list.get("requestBody").is_none()); |
| 1027 | } |
| 1028 | |
| 1029 | #[test] |
| 1030 | fn every_operation_is_in_one_section() { |
| 1031 | for op in Op::ALL { |
| 1032 | let sections = SECTIONS |
| 1033 | .iter() |
| 1034 | .filter(|(_, _, ops)| ops.contains(&op)) |
| 1035 | .count(); |
| 1036 | assert_eq!(sections, 1, "{}", op.name()); |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | #[test] |
| 1041 | fn titles_read_as_sentences() { |
| 1042 | assert_eq!(title(Op::CreateIssue), "Create an issue"); |
| 1043 | assert_eq!(title(Op::Whoami), "Get the current user"); |
| 1044 | } |
| 1045 | |
| 1046 | #[test] |
| 1047 | fn every_operation_has_an_example_response() { |
| 1048 | let examples = examples(); |
| 1049 | assert!(!examples.is_empty(), "reference.json does not parse"); |
| 1050 | let document = document(); |
| 1051 | let mut known = Vec::new(); |
| 1052 | for (path, methods) in document["paths"].as_object().unwrap() { |
| 1053 | for (method, operation) in methods.as_object().unwrap() { |
| 1054 | known.push(operation["operationId"].as_str().unwrap().to_owned()); |
| 1055 | let example = &operation["responses"]["200"]["content"]["application/json"]["example"]; |
| 1056 | assert!(!example.is_null(), "{method} {path} has no example response"); |
| 1057 | } |
| 1058 | } |
| 1059 | for id in examples.keys() { |
| 1060 | assert!(known.contains(id), "reference.json names {id}, which is not an operation"); |
| 1061 | } |
| 1062 | } |
| 1063 | |
| 1064 | #[test] |
| 1065 | fn example_requests_send_only_what_the_body_takes() { |
| 1066 | let document = document(); |
| 1067 | for (path, methods) in document["paths"].as_object().unwrap() { |
| 1068 | for (method, operation) in methods.as_object().unwrap() { |
| 1069 | let content = &operation["requestBody"]["content"]["application/json"]; |
| 1070 | let Some(example) = content["example"].as_object() else { continue }; |
| 1071 | let properties = &content["schema"]["properties"]; |
| 1072 | for key in example.keys() { |
| 1073 | assert!(!properties[key].is_null(), "{method} {path}: {key} is not in the body"); |
| 1074 | } |
| 1075 | } |
| 1076 | } |
| 1077 | } |
| 1078 | |
| 1079 | /// The docs site's copy of the document. Run with `G1T_WRITE_OPENAPI=1` |
| 1080 | /// to rewrite it after changing an operation. |
| 1081 | #[test] |
| 1082 | fn the_docs_copy_is_current() { |
| 1083 | let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../docs/src/data/openapi.json"); |
| 1084 | let current = serde_json::to_string_pretty(&document()).unwrap() + "\n"; |
| 1085 | if std::env::var_os("G1T_WRITE_OPENAPI").is_some() { |
| 1086 | std::fs::write(path, ¤t).unwrap(); |
| 1087 | return; |
| 1088 | } |
| 1089 | let copy = std::fs::read_to_string(path).unwrap_or_default().replace("\r\n", "\n"); |
| 1090 | assert!( |
| 1091 | copy == current, |
| 1092 | "apps/docs/src/data/openapi.json is out of date: run G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi" |
| 1093 | ); |
| 1094 | } |
| 1095 | |
| 1096 | /// The reference shows responses as they are sent: `snake_case`. |
| 1097 | #[test] |
| 1098 | fn example_responses_are_snake_case() { |
| 1099 | let document = document(); |
| 1100 | for (path, methods) in document["paths"].as_object().unwrap() { |
| 1101 | for (method, operation) in methods.as_object().unwrap() { |
| 1102 | let example = &operation["responses"]["200"]["content"]["application/json"]["example"]; |
| 1103 | let leaked = g1t_kit::wire::camel_case_keys(example); |
| 1104 | assert!(leaked.is_empty(), "{method} {path} shows {leaked:?}"); |
| 1105 | } |
| 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | /// Examples never hold anything that reads as a real credential, which |
| 1110 | /// secret scanners rightly flag in a public repository: they end in `…` |
| 1111 | /// after the prefix, as `whsec_…` and `g1t_…` do. |
| 1112 | #[test] |
| 1113 | fn examples_hold_no_real_looking_secrets() { |
| 1114 | let prefixes = ["whsec_", "g1t_", "g1tr_", "g1trt_", "sk_live_", "sk_test_", "ghp_", "github_pat_", "xoxb-", "AKIA"]; |
| 1115 | for (line, text) in REFERENCE.lines().enumerate() { |
| 1116 | for prefix in prefixes { |
| 1117 | let mut rest = text; |
| 1118 | while let Some(at) = rest.find(prefix) { |
| 1119 | let after = &rest[at + prefix.len()..]; |
| 1120 | let run = after.chars().take_while(|c| c.is_ascii_alphanumeric()).count(); |
| 1121 | assert!( |
| 1122 | run < 12, |
| 1123 | "reference.json line {}: `{prefix}` followed by {run} characters reads as a real secret; write `{prefix}…`", |
| 1124 | line + 1 |
| 1125 | ); |
| 1126 | rest = after; |
| 1127 | } |
| 1128 | } |
| 1129 | } |
| 1130 | } |
| 1131 | } |