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