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