Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
1,989 linesCodeBlameRaw
1//! Scopes: what an access token may do on its owner's behalf.
2//!
3//! A personal access token, a workspace's token and an application signed
4//! in with OAuth each carry a set of scopes. A token reaches whatever the
5//! one it acts as can reach: a person's token, that person's workspaces and
6//! repositories; a workspace's token, that workspace. What a request may do
7//! is the intersection of two things: the role of whoever the token acts as
8//! (see [`crate::access`]) and the token's scopes.
9//!
10//! Each scope is a resource and a level, written `resource:level`, such as
11//! `issues:write`. A higher level of a resource includes the lower ones:
12//! `repo:admin` includes `repo:write`, which includes `repo:read`.
13//!
14//! This module is the one source of truth: the API (REST and MCP) and git
15//! enforce it, and identity stores it. `packages/contracts/src/scopes.ts`
16//! mirrors the table for the site; a test keeps the two the same.
17
18use serde::{Deserialize, Serialize};
19
20use crate::credentials::Decision;
21
22/// Something a token can be given access to.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24pub enum Resource {
25 Account,
26 Notifications,
27 /// Chat: the conversations a person is in (channels, direct messages,
28 /// threads), read and answered as them on the site's chat routes and
29 /// live sockets. A person's own; no preset gives it.
30 Chat,
31 Workspace,
32 Billing,
33 Repo,
34 Code,
35 Security,
36 Packages,
37 Issues,
38 PullRequests,
39 Agents,
40 Workflows,
41 WorkflowFiles,
42 Checks,
43 Deployments,
44 /// Observability: what a project's running software did, as requests,
45 /// logs, traces, errors and metrics, and how they are collected.
46 Observability,
47 /// Retired with project and workspace memory ([`Resource::retired`]).
48 Memory,
49 Access,
50 Webhooks,
51 Secrets,
52 Runners,
53 Models,
54 /// Artifacts mode's docs, slides, designs and dashboards (folios in
55 /// code): the `artifact` MCP tool and `/workspaces/{ws}/artifacts`.
56 /// Not workflow runs' artifacts, which are `workflows:*`.
57 Artifacts,
58}
59
60impl Resource {
61 pub const ALL: [Resource; 24] = [
62 Resource::Repo,
63 Resource::Code,
64 Resource::Security,
65 Resource::Packages,
66 Resource::Issues,
67 Resource::PullRequests,
68 Resource::Agents,
69 Resource::Workflows,
70 Resource::WorkflowFiles,
71 Resource::Checks,
72 Resource::Deployments,
73 Resource::Observability,
74 Resource::Memory,
75 Resource::Account,
76 Resource::Notifications,
77 Resource::Chat,
78 Resource::Workspace,
79 Resource::Billing,
80 Resource::Access,
81 Resource::Webhooks,
82 Resource::Secrets,
83 Resource::Runners,
84 Resource::Models,
85 Resource::Artifacts,
86 ];
87
88 pub fn as_str(self) -> &'static str {
89 match self {
90 Resource::Account => "account",
91 Resource::Notifications => "notifications",
92 Resource::Chat => "chat",
93 Resource::Workspace => "workspace",
94 Resource::Billing => "billing",
95 Resource::Repo => "repo",
96 Resource::Code => "code",
97 Resource::Security => "security",
98 Resource::Packages => "packages",
99 Resource::Issues => "issues",
100 Resource::PullRequests => "pull_requests",
101 Resource::Agents => "agents",
102 Resource::Workflows => "workflows",
103 Resource::WorkflowFiles => "workflow_files",
104 Resource::Checks => "checks",
105 Resource::Deployments => "deployments",
106 Resource::Observability => "observability",
107 Resource::Memory => "memory",
108 Resource::Access => "access",
109 Resource::Webhooks => "webhooks",
110 Resource::Secrets => "secrets",
111 Resource::Runners => "runners",
112 Resource::Models => "models",
113 Resource::Artifacts => "artifacts",
114 }
115 }
116
117 /// Its name, for people.
118 pub fn label(self) -> &'static str {
119 match self {
120 Resource::Account => "Your account",
121 Resource::Notifications => "Notifications",
122 Resource::Chat => "Chat",
123 Resource::Workspace => "Workspaces",
124 Resource::Billing => "Billing",
125 Resource::Repo => "Repositories",
126 Resource::Code => "Code",
127 Resource::Security => "Security",
128 Resource::Packages => "Packages",
129 Resource::Issues => "Issues",
130 Resource::PullRequests => "Pull requests",
131 Resource::Agents => "g1t agents",
132 Resource::Workflows => "Workflows",
133 Resource::WorkflowFiles => "Workflow files",
134 Resource::Checks => "Checks and statuses",
135 Resource::Deployments => "Deployments",
136 Resource::Observability => "Observability",
137 Resource::Memory => "Memory",
138 Resource::Access => "Who has access",
139 Resource::Webhooks => "Webhooks",
140 Resource::Secrets => "Secrets and variables",
141 Resource::Runners => "Self-hosted runners",
142 Resource::Models => "AI Gateway",
143 Resource::Artifacts => "Artifacts",
144 }
145 }
146
147 /// Whether tokens are offered it. A resource being built can be in
148 /// the table before its API ships (so its scopes parse, and the
149 /// TypeScript mirror lists it under `UPCOMING_RESOURCES`) while nothing
150 /// hands it out: presets, full access, OAuth and the token form leave
151 /// it out, and no operation needs it. A [`Resource::retired`] one is
152 /// never offered again.
153 pub fn offered(self) -> bool {
154 !self.retired()
155 }
156
157 /// Whether it belonged to something g1t no longer has: `agents` (g1t's
158 /// own agents), `memory` (project and workspace memory) and `models`
159 /// (its model proxy and AI Gateway). Their
160 /// scopes still parse, so tokens and OAuth grants that stored them read
161 /// as before, but [`parse_scopes`] leaves them out, nothing hands them
162 /// out and no operation needs them: they grant nothing. The TypeScript
163 /// mirror lists them under `RETIRED_RESOURCES` and `RETIRED_SCOPES`.
164 pub fn retired(self) -> bool {
165 matches!(self, Resource::Agents | Resource::Memory | Resource::Models)
166 }
167}
168
169/// How much of a resource.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
171pub enum Level {
172 Read,
173 Write,
174 /// Starting g1t's own agents: only `agents:run`, which is retired.
175 Run,
176 /// Deleting what cannot be brought back, such as a package's versions.
177 Delete,
178 Admin,
179}
180
181impl Level {
182 pub fn as_str(self) -> &'static str {
183 match self {
184 Level::Read => "read",
185 Level::Write => "write",
186 Level::Run => "run",
187 Level::Delete => "delete",
188 Level::Admin => "admin",
189 }
190 }
191}
192
193/// One scope. Its text form, `resource:level`, is what tokens store, OAuth
194/// clients ask for, and errors name.
195#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
196pub enum Scope {
197 RepoRead,
198 RepoWrite,
199 RepoAdmin,
200 CodeRead,
201 CodeWrite,
202 SecurityRead,
203 SecurityWrite,
204 PackagesRead,
205 PackagesWrite,
206 PackagesDelete,
207 IssuesRead,
208 IssuesWrite,
209 PullRequestsRead,
210 PullRequestsWrite,
211 /// Retired with g1t's own agents ([`Resource::retired`]): parses, so
212 /// stored tokens still read, but is never granted and gates nothing.
213 AgentsRun,
214 WorkflowsRead,
215 WorkflowsWrite,
216 WorkflowFilesWrite,
217 ChecksRead,
218 ChecksWrite,
219 DeploymentsRead,
220 DeploymentsWrite,
221 ObservabilityRead,
222 ObservabilityWrite,
223 /// Retired with memory ([`Resource::retired`]): parses, so stored
224 /// tokens still read, but is never granted and gates nothing.
225 MemoryRead,
226 MemoryWrite,
227 AccountRead,
228 AccountWrite,
229 NotificationsRead,
230 NotificationsWrite,
231 ChatRead,
232 ChatWrite,
233 WorkspaceRead,
234 WorkspaceAdmin,
235 BillingRead,
236 BillingWrite,
237 AccessRead,
238 AccessAdmin,
239 WebhooksRead,
240 WebhooksAdmin,
241 SecretsRead,
242 SecretsAdmin,
243 RunnersRead,
244 RunnersAdmin,
245 /// Retired with the AI Gateway ([`Resource::retired`]): parses, so
246 /// stored tokens still read, but is never granted and gates nothing.
247 ModelsRead,
248 ModelsWrite,
249 ArtifactsRead,
250 ArtifactsWrite,
251 ArtifactsAdmin,
252}
253
254impl Scope {
255 /// Every scope, grouped by resource, least first.
256 pub const ALL: [Scope; 49] = [
257 Scope::RepoRead,
258 Scope::RepoWrite,
259 Scope::RepoAdmin,
260 Scope::CodeRead,
261 Scope::CodeWrite,
262 Scope::SecurityRead,
263 Scope::SecurityWrite,
264 Scope::PackagesRead,
265 Scope::PackagesWrite,
266 Scope::PackagesDelete,
267 Scope::IssuesRead,
268 Scope::IssuesWrite,
269 Scope::PullRequestsRead,
270 Scope::PullRequestsWrite,
271 Scope::AgentsRun,
272 Scope::WorkflowsRead,
273 Scope::WorkflowsWrite,
274 Scope::WorkflowFilesWrite,
275 Scope::ChecksRead,
276 Scope::ChecksWrite,
277 Scope::DeploymentsRead,
278 Scope::DeploymentsWrite,
279 Scope::ObservabilityRead,
280 Scope::ObservabilityWrite,
281 Scope::MemoryRead,
282 Scope::MemoryWrite,
283 Scope::AccountRead,
284 Scope::AccountWrite,
285 Scope::NotificationsRead,
286 Scope::NotificationsWrite,
287 Scope::ChatRead,
288 Scope::ChatWrite,
289 Scope::WorkspaceRead,
290 Scope::WorkspaceAdmin,
291 Scope::BillingRead,
292 Scope::BillingWrite,
293 Scope::AccessRead,
294 Scope::AccessAdmin,
295 Scope::WebhooksRead,
296 Scope::WebhooksAdmin,
297 Scope::SecretsRead,
298 Scope::SecretsAdmin,
299 Scope::RunnersRead,
300 Scope::RunnersAdmin,
301 Scope::ModelsRead,
302 Scope::ModelsWrite,
303 Scope::ArtifactsRead,
304 Scope::ArtifactsWrite,
305 Scope::ArtifactsAdmin,
306 ];
307
308 pub fn as_str(self) -> &'static str {
309 match self {
310 Scope::RepoRead => "repo:read",
311 Scope::RepoWrite => "repo:write",
312 Scope::RepoAdmin => "repo:admin",
313 Scope::CodeRead => "code:read",
314 Scope::CodeWrite => "code:write",
315 Scope::SecurityRead => "security:read",
316 Scope::SecurityWrite => "security:write",
317 Scope::PackagesRead => "packages:read",
318 Scope::PackagesWrite => "packages:write",
319 Scope::PackagesDelete => "packages:delete",
320 Scope::IssuesRead => "issues:read",
321 Scope::IssuesWrite => "issues:write",
322 Scope::PullRequestsRead => "pull_requests:read",
323 Scope::PullRequestsWrite => "pull_requests:write",
324 Scope::AgentsRun => "agents:run",
325 Scope::WorkflowsRead => "workflows:read",
326 Scope::WorkflowsWrite => "workflows:write",
327 Scope::WorkflowFilesWrite => "workflow_files:write",
328 Scope::ChecksRead => "checks:read",
329 Scope::ChecksWrite => "checks:write",
330 Scope::DeploymentsRead => "deployments:read",
331 Scope::DeploymentsWrite => "deployments:write",
332 Scope::ObservabilityRead => "observability:read",
333 Scope::ObservabilityWrite => "observability:write",
334 Scope::MemoryRead => "memory:read",
335 Scope::MemoryWrite => "memory:write",
336 Scope::AccountRead => "account:read",
337 Scope::AccountWrite => "account:write",
338 Scope::NotificationsRead => "notifications:read",
339 Scope::NotificationsWrite => "notifications:write",
340 Scope::ChatRead => "chat:read",
341 Scope::ChatWrite => "chat:write",
342 Scope::WorkspaceRead => "workspace:read",
343 Scope::WorkspaceAdmin => "workspace:admin",
344 Scope::BillingRead => "billing:read",
345 Scope::BillingWrite => "billing:write",
346 Scope::AccessRead => "access:read",
347 Scope::AccessAdmin => "access:admin",
348 Scope::WebhooksRead => "webhooks:read",
349 Scope::WebhooksAdmin => "webhooks:admin",
350 Scope::SecretsRead => "secrets:read",
351 Scope::SecretsAdmin => "secrets:admin",
352 Scope::RunnersRead => "runners:read",
353 Scope::RunnersAdmin => "runners:admin",
354 Scope::ModelsRead => "models:read",
355 Scope::ModelsWrite => "models:write",
356 Scope::ArtifactsRead => "artifacts:read",
357 Scope::ArtifactsWrite => "artifacts:write",
358 Scope::ArtifactsAdmin => "artifacts:admin",
359 }
360 }
361
362 pub fn parse(text: &str) -> Option<Scope> {
363 let text = text.trim().to_ascii_lowercase();
364 Scope::ALL.into_iter().find(|scope| scope.as_str() == text)
365 }
366
367 pub fn resource(self) -> Resource {
368 let name = self.as_str().split_once(':').map_or("", |(resource, _)| resource);
369 Resource::ALL
370 .into_iter()
371 .find(|resource| resource.as_str() == name)
372 .unwrap_or(Resource::Account)
373 }
374
375 pub fn level(self) -> Level {
376 match self.as_str().rsplit_once(':').map_or("", |(_, level)| level) {
377 "write" => Level::Write,
378 "run" => Level::Run,
379 "delete" => Level::Delete,
380 "admin" => Level::Admin,
381 _ => Level::Read,
382 }
383 }
384
385 /// Whether holding `self` gives `other`: the same resource, at the same
386 /// level or a lower one.
387 pub fn includes(self, other: Scope) -> bool {
388 self.resource() == other.resource() && self.level() >= other.level()
389 }
390
391 /// Changes that are hard or impossible to undo, or that decide who can
392 /// reach what. Shown behind a warning wherever scopes are chosen.
393 pub fn dangerous(self) -> bool {
394 matches!(self.level(), Level::Admin | Level::Delete)
395 }
396
397 /// What it lets a token do, in plain words.
398 pub fn describe(self) -> &'static str {
399 match self {
400 Scope::RepoRead => "See repositories, their settings, labels, timelines, releases, languages, contributors and security alerts, and search",
401 Scope::RepoWrite => "Create repositories, create, rename and delete branches, change how pull requests merge and publish releases",
402 Scope::RepoAdmin => "Rename, archive, transfer, delete or change who can see a repository, change its rulesets, and dismiss security alerts",
403 Scope::CodeRead => "Clone and fetch private repositories with git",
404 Scope::CodeWrite => "Push commits with git",
405 Scope::SecurityRead => "See secret scanning, code scanning and vulnerability alerts, custom patterns, the dependency graph and SBOM, and security settings",
406 Scope::SecurityWrite => "Dismiss and reopen alerts, bypass push protection, review bypass requests, manage custom patterns, upload SARIF and change security settings",
407 Scope::PackagesRead => "Pull container images and install private packages",
408 Scope::PackagesWrite => "Push container images and publish packages",
409 Scope::PackagesDelete => "Delete and restore packages and their versions",
410 Scope::IssuesRead => "Read issues and comments",
411 Scope::IssuesWrite => "Open, edit, close and comment on issues",
412 Scope::PullRequestsRead => "Read pull requests, their changes, sessions and merge queues",
413 Scope::PullRequestsWrite => "Open, review, close and merge pull requests",
414 Scope::AgentsRun => "Retired: put g1t's own agents to work. Grants nothing now",
415 Scope::WorkflowsRead => "Read workflows, runs and logs",
416 Scope::WorkflowsWrite => "Run, cancel, rerun and turn workflows on or off",
417 Scope::WorkflowFilesWrite => "Add, change and delete workflow files under .g1t/workflows and .github/workflows, with git or the API",
418 Scope::ChecksRead => "Read commits' statuses, check runs, check suites and annotations",
419 Scope::ChecksWrite => "Report statuses and check runs on commits, and ask for checks to run again",
420 Scope::DeploymentsRead => "See deployments, their statuses and environments",
421 Scope::DeploymentsWrite => "Report deployments and their statuses, from any CI",
422 Scope::ObservabilityRead => "See projects' requests, logs, traces, errors and metrics, and their observability settings, ingest tokens and exports",
423 Scope::ObservabilityWrite => "Resolve and ignore errors, and change projects' observability settings, ingest tokens and exports",
424 Scope::MemoryRead => "Retired: recall project and workspace memory. Grants nothing now",
425 Scope::MemoryWrite => "Retired: save project and workspace memory. Grants nothing now",
426 Scope::AccountRead => "Read your email addresses, invites, invitations, pinned projects and stars",
427 Scope::AccountWrite => "Change your email addresses, make invites, answer invitations, pin projects and star repositories",
428 Scope::NotificationsRead => "See your inbox, its threads, and what you subscribe to and watch",
429 Scope::NotificationsWrite => "Mark notifications read, done, saved or snoozed, subscribe to threads and watch repositories",
430 Scope::ChatRead => "Read the conversations you are in: channels, direct messages, threads and reactions, live",
431 Scope::ChatWrite => "Send, edit and delete your messages, react, mark conversations read, and answer cards in chat",
432 Scope::WorkspaceRead => "Read workspace settings, invites, integrations, AI providers, teams and rulesets",
433 Scope::WorkspaceAdmin => "Create and delete workspaces, invite members, connect integrations, add AI providers and choose what Ask answers with, create, change and delete teams, and change the workspace's rulesets",
434 Scope::BillingRead => "See a workspace's usage, budget and invoices",
435 Scope::BillingWrite => "Change a workspace's budget",
436 Scope::AccessRead => "See who has access to repositories",
437 Scope::AccessAdmin => "Give and take away access to repositories, a team's included",
438 Scope::WebhooksRead => "See webhooks and their deliveries",
439 Scope::WebhooksAdmin => "Create, change and delete webhooks",
440 Scope::SecretsRead => "List secrets (never their values) and read variables",
441 Scope::SecretsAdmin => "Set and delete secrets and variables",
442 Scope::RunnersRead => "See self-hosted runners and their groups",
443 Scope::RunnersAdmin => "Register and remove self-hosted runners, change their groups and settings",
444 Scope::ModelsRead => "Retired: see the AI Gateway's requests. Grants nothing now",
445 Scope::ModelsWrite => "Retired: send requests through the AI Gateway. Grants nothing now",
446 Scope::ArtifactsRead => "List, read and search artifacts you can see, their versions, and the numbers their dashboards show",
447 Scope::ArtifactsWrite => "Create, rename, move, edit, trash and restore artifacts, and propose changes to them",
448 Scope::ArtifactsAdmin => "Share artifacts, change who can open them, and delete them for good",
449 }
450 }
451
452 /// Whether tokens are offered it yet: its resource's [`Resource::offered`].
453 pub fn offered(self) -> bool {
454 self.resource().offered()
455 }
456}
457
458/// Every scope tokens are offered, in table order: what OAuth advertises.
459pub fn offered_scopes() -> Vec<Scope> {
460 Scope::ALL.into_iter().filter(|scope| scope.offered()).collect()
461}
462
463impl Serialize for Scope {
464 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
465 serializer.serialize_str(self.as_str())
466 }
467}
468
469impl<'de> Deserialize<'de> for Scope {
470 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
471 let text = String::deserialize(deserializer)?;
472 Scope::parse(&text).ok_or_else(|| serde::de::Error::custom(format!("unknown scope {text}")))
473 }
474}
475
476/// Scopes as written in a token's row or an OAuth request: separated by
477/// spaces or commas. Unknown names are left out, so a client asking for a
478/// scope from a newer version gets the rest.
479pub fn parse_scopes(text: &str) -> Vec<Scope> {
480 let mut scopes: Vec<Scope> = text
481 .split(|c: char| c.is_whitespace() || c == ',')
482 .filter_map(Scope::parse)
483 .filter(|scope| scope.offered())
484 .collect();
485 normalize(&mut scopes);
486 scopes
487}
488
489/// In table order, without repeats.
490pub fn normalize(scopes: &mut Vec<Scope>) {
491 let given = std::mem::take(scopes);
492 scopes.extend(Scope::ALL.into_iter().filter(|scope| given.contains(scope)));
493}
494
495/// Space-separated, as stored and as OAuth writes them.
496pub fn scopes_text(scopes: &[Scope]) -> String {
497 scopes.iter().map(|scope| scope.as_str()).collect::<Vec<_>>().join(" ")
498}
499
500/// Where a resource sits on the token form, and which tokens may hold it.
501#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
502#[serde(rename_all = "snake_case")]
503pub enum ResourceGroup {
504 /// About repositories: what they hold and how they are run.
505 Repository,
506 /// About a workspace itself.
507 Workspace,
508 /// About the person: only a personal token may hold these.
509 Account,
510}
511
512impl ResourceGroup {
513 pub const ALL: [ResourceGroup; 3] = [ResourceGroup::Repository, ResourceGroup::Workspace, ResourceGroup::Account];
514
515 pub fn as_str(self) -> &'static str {
516 match self {
517 ResourceGroup::Repository => "repository",
518 ResourceGroup::Workspace => "workspace",
519 ResourceGroup::Account => "account",
520 }
521 }
522}
523
524impl Resource {
525 pub fn group(self) -> ResourceGroup {
526 match self {
527 Resource::Account | Resource::Notifications | Resource::Chat => ResourceGroup::Account,
528 Resource::Workspace | Resource::Billing | Resource::Runners | Resource::Models | Resource::Artifacts => ResourceGroup::Workspace,
529 _ => ResourceGroup::Repository,
530 }
531 }
532
533 pub fn parse(text: &str) -> Option<Resource> {
534 let text = text.trim().to_ascii_lowercase();
535 Resource::ALL.into_iter().find(|resource| resource.as_str() == text)
536 }
537
538 /// Its scopes, least first.
539 pub fn scopes(self) -> Vec<Scope> {
540 Scope::ALL.into_iter().filter(|scope| scope.resource() == self).collect()
541 }
542}
543
544// --- Permissions --------------------------------------------------------------
545//
546// A token's permissions are its scopes read per resource: each resource
547// at none or one level (`{"issues": "write", "repo": "read"}`). A level
548// includes the ones below it, so the highest scope held of each resource
549// says everything; that is what a token stores. Personal tokens and a
550// workspace's own tokens are made, shown and checked this way alike.
551
552/// The highest scope of each resource held, in table order: the fewest
553/// scopes that give the same access, as tokens store them.
554pub fn top_scopes(scopes: &[Scope]) -> Vec<Scope> {
555 let mut top: Vec<Scope> = Vec::new();
556 for resource in Resource::ALL {
557 if let Some(best) = scopes.iter().filter(|scope| scope.resource() == resource).max_by_key(|scope| scope.level()) {
558 top.push(*best);
559 }
560 }
561 normalize(&mut top);
562 top
563}
564
565/// Every resource at its highest level: all a token can be given.
566pub fn everything() -> Vec<Scope> {
567 top_scopes(&offered_scopes())
568}
569
570/// Scopes as permissions: each resource held, by name, at its highest
571/// level held.
572pub fn permissions_of(scopes: &[Scope]) -> std::collections::BTreeMap<String, String> {
573 top_scopes(scopes)
574 .into_iter()
575 .map(|scope| (scope.resource().as_str().to_owned(), scope.level().as_str().to_owned()))
576 .collect()
577}
578
579/// Permissions as asked for (`{"issues": "write"}`, `none` or empty left
580/// out) into the scopes a token stores, or why they cannot be. `personal`
581/// is whether the token is a person's: only theirs may hold account ones.
582pub fn resolve_permissions(asked: &std::collections::BTreeMap<String, String>, personal: bool) -> Result<Vec<Scope>, String> {
583 let mut scopes = Vec::new();
584 for (name, level) in asked {
585 let Some(resource) = Resource::parse(name).filter(|resource| resource.offered()) else {
586 return Err(format!("There is no permission called {name}."));
587 };
588 let level = level.trim().to_ascii_lowercase();
589 if level.is_empty() || level == "none" {
590 continue;
591 }
592 let Some(scope) = Scope::parse(&format!("{}:{level}", resource.as_str())) else {
593 let levels: Vec<&str> = resource.scopes().iter().map(|scope| scope.level().as_str()).collect();
594 return Err(format!("{} is none or {}, not {level}.", resource.as_str(), levels.join(", ")));
595 };
596 if resource.group() == ResourceGroup::Account && !personal {
597 return Err(format!("{} is about a person's account: a workspace's token cannot hold it.", resource.as_str()));
598 }
599 scopes.push(scope);
600 }
601 Ok(top_scopes(&scopes))
602}
603
604/// What a token stores for full access, which is not a scope a client can
605/// ask for by name.
606pub const FULL_ACCESS: &str = "*";
607
608/// Starting points for choosing scopes.
609#[derive(Clone, Copy, Debug, PartialEq, Eq)]
610pub enum Preset {
611 ReadOnly,
612 Agent,
613 Ci,
614 Full,
615}
616
617impl Preset {
618 pub const ALL: [Preset; 4] = [Preset::ReadOnly, Preset::Agent, Preset::Ci, Preset::Full];
619
620 pub fn as_str(self) -> &'static str {
621 match self {
622 Preset::ReadOnly => "read_only",
623 Preset::Agent => "agent",
624 Preset::Ci => "ci",
625 Preset::Full => "full",
626 }
627 }
628
629 pub fn label(self) -> &'static str {
630 match self {
631 Preset::ReadOnly => "Read only",
632 Preset::Agent => "Agent",
633 Preset::Ci => "CI",
634 Preset::Full => "Full access",
635 }
636 }
637
638 /// Its scopes; `None` for full access.
639 pub fn scopes(self) -> Option<Vec<Scope>> {
640 // Chat is not in any: a person's conversations go to an application
641 // only when it asks for them by name.
642 let reads = || {
643 Scope::ALL
644 .into_iter()
645 .filter(|scope| scope.level() == Level::Read && scope.offered() && scope.resource() != Resource::Chat)
646 };
647 match self {
648 Preset::ReadOnly => Some(reads().collect()),
649 Preset::Agent => {
650 // Not the machines work runs on: an agent has no business
651 // knowing a workspace's own runners.
652 let mut scopes: Vec<Scope> = reads().filter(|scope| scope.resource() != Resource::Runners).collect();
653 // And answering what needs the person it works for: marking
654 // it done, subscribing, watching.
655 scopes.extend([
656 Scope::CodeWrite,
657 Scope::IssuesWrite,
658 Scope::PullRequestsWrite,
659 Scope::NotificationsWrite,
660 ]);
661 normalize(&mut scopes);
662 Some(scopes)
663 }
664 Preset::Ci => Some(vec![
665 Scope::RepoRead,
666 Scope::CodeRead,
667 Scope::CodeWrite,
668 Scope::PackagesRead,
669 Scope::PackagesWrite,
670 Scope::WorkflowsRead,
671 Scope::WorkflowsWrite,
672 Scope::ChecksRead,
673 Scope::ChecksWrite,
674 Scope::DeploymentsRead,
675 Scope::DeploymentsWrite,
676 ]),
677 Preset::Full => None,
678 }
679 }
680}
681
682/// What an OAuth client gets when it asks for nothing in particular: the
683/// agent preset. Never an admin scope.
684pub fn oauth_default() -> Vec<Scope> {
685 Preset::Agent.scopes().unwrap_or_default()
686}
687
688/// Set on a [`crate::User`] resolved from an access token: what the token
689/// may do. Absent on a signed-in session, which may do whatever its person
690/// can.
691#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
692pub struct TokenAccess {
693 /// The token's id, as audit entries and errors name it.
694 #[serde(default)]
695 pub token_id: String,
696 /// Its scopes, as `resource:level`. Absent: full access, everything the
697 /// person (or workspace) can do.
698 #[serde(default, skip_serializing_if = "Option::is_none")]
699 pub scopes: Option<Vec<String>>,
700 /// Made before tokens had scopes: full access until someone narrows it.
701 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
702 pub legacy: bool,
703 /// Set on a workflow job's token (`G1T_TOKEN`): the one repository it
704 /// reaches, as `owner/name`. Every other is refused, whatever its owner
705 /// could reach.
706 #[serde(default, skip_serializing_if = "Option::is_none")]
707 pub repo: Option<String>,
708 /// Set on a workflow job's token: the run and job it was made for. The
709 /// audit log records its changes as that job's, and what it changes
710 /// starts no workflows (only `workflow_dispatch` and
711 /// `repository_dispatch` do), so a workflow cannot set itself off.
712 #[serde(default, skip_serializing_if = "Option::is_none")]
713 pub job: Option<JobToken>,
714 /// The token's name, as its owner gave it, so a log can say which
715 /// token made a request. Absent where whoever resolved it did not say.
716 #[serde(default, skip_serializing_if = "Option::is_none")]
717 pub name: Option<String>,
718 /// Set on a token narrowed to less than its owner can reach: one
719 /// workspace (all, selected or none of its private repositories), or
720 /// none at all (its owner's account and public repositories). Absent
721 /// on a token that reaches every workspace its owner can.
722 ///
723 /// The wire key is `fine_grained`, kept from before tokens were one
724 /// kind, so services deployed at different moments agree on it.
725 #[serde(rename = "fine_grained", default, skip_serializing_if = "Option::is_none")]
726 pub reach: Option<TokenReach>,
727 /// Set on a workspace's own token that an owner gave Admin when making
728 /// it. Without it a workspace's token has Write on the workspace's
729 /// repositories, as a member would (see [`crate::access`]).
730 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
731 pub admin: bool,
732 /// Set on what a repository's deploy key resolves to: the key's id. Its
733 /// `repo` is the one repository it reaches.
734 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub deploy_key: Option<String>,
736 /// Set on a person's token whose owner let it use the website (g1t.sh)
737 /// as them, sent as `Authorization: Bearer`. Not a scope: no preset,
738 /// full access or OAuth grant includes it, and git, the API and MCP
739 /// ignore it.
740 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
741 pub website: bool,
742}
743
744/// Which repositories a token reaches in the workspace it is made for.
745#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
746#[serde(rename_all = "snake_case")]
747pub enum RepositorySelection {
748 /// Every repository of the workspace, ones made later included.
749 #[default]
750 All,
751 /// The repositories chosen, by id.
752 Selected,
753 /// None of the workspace's private repositories: public repositories,
754 /// read-only, and the workspace's own settings its permissions allow.
755 /// With no workspace: the owner's account and public repositories only.
756 Public,
757}
758
759impl RepositorySelection {
760 pub fn as_str(self) -> &'static str {
761 match self {
762 RepositorySelection::All => "all",
763 RepositorySelection::Selected => "selected",
764 RepositorySelection::Public => "public",
765 }
766 }
767
768 pub fn parse(text: &str) -> Option<RepositorySelection> {
769 match text.trim().to_ascii_lowercase().as_str() {
770 "all" => Some(RepositorySelection::All),
771 "selected" => Some(RepositorySelection::Selected),
772 "public" | "public_only" | "none" => Some(RepositorySelection::Public),
773 _ => None,
774 }
775 }
776}
777
778/// What a narrowed token reaches, as identity resolves it on each use.
779#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
780pub struct TokenReach {
781 /// The workspace whose repositories and settings it reaches, by slug as
782 /// it is now. Absent: its owner's account only, with public
783 /// repositories read-only.
784 #[serde(default, skip_serializing_if = "Option::is_none")]
785 pub workspace: Option<String>,
786 #[serde(default)]
787 pub repositories: RepositorySelection,
788 /// With [`RepositorySelection::Selected`]: the repositories' ids.
789 #[serde(default, skip_serializing_if = "Vec::is_empty")]
790 pub repo_ids: Vec<String>,
791}
792
793impl TokenReach {
794 /// Whether it reaches the repository with this id in the workspace
795 /// `namespace` for more than what anyone may do with a public one.
796 pub fn covers(&self, repo_id: &str, namespace: &str) -> bool {
797 let Some(workspace) = self.workspace.as_deref() else {
798 return false;
799 };
800 if !workspace.eq_ignore_ascii_case(namespace) {
801 return false;
802 }
803 match self.repositories {
804 RepositorySelection::All => true,
805 RepositorySelection::Selected => self.repo_ids.iter().any(|id| id == repo_id),
806 RepositorySelection::Public => false,
807 }
808 }
809
810 /// Whether it is made for the workspace `slug`.
811 pub fn owned_by(&self, slug: &str) -> bool {
812 self.workspace.as_deref().is_some_and(|workspace| workspace.eq_ignore_ascii_case(slug))
813 }
814}
815
816/// Where workflow files live. Adding, changing or deleting a file under
817/// one, with git or through g1t, needs [`Scope::WorkflowFilesWrite`] from a
818/// token: what GitHub's `workflow` scope and `workflows` permission do.
819pub const WORKFLOW_DIRS: [&str; 2] = [".g1t/workflows/", ".github/workflows/"];
820
821/// Whether `path` is a workflow file, or a file in one's directory.
822pub fn is_workflow_file(path: &str) -> bool {
823 let path = path.trim_start_matches('/');
824 WORKFLOW_DIRS.iter().any(|dir| {
825 path.len() >= dir.len() && path.is_char_boundary(dir.len()) && path[..dir.len()].eq_ignore_ascii_case(dir)
826 }) || WORKFLOW_DIRS.iter().any(|dir| path.eq_ignore_ascii_case(dir.trim_end_matches('/')))
827}
828
829/// Whether a token may add, change or delete the files at `paths`: a
830/// refusal naming the first workflow file it may not touch, else `None`.
831/// A signed-in person (no token) is never refused here; their role decides.
832pub fn decide_workflow_files<'a>(access: Option<&TokenAccess>, paths: impl IntoIterator<Item = &'a str>) -> Option<Decision> {
833 let access = access?;
834 if access.allows(Scope::WorkflowFilesWrite) && access.job.is_none() {
835 return None;
836 }
837 let path = paths.into_iter().find(|path| is_workflow_file(path))?;
838 let why = if access.job.is_some() {
839 "a workflow job's token can never add or change workflow files".to_owned()
840 } else {
841 format!("it needs the {} scope", Scope::WorkflowFilesWrite.as_str())
842 };
843 Some(Decision::deny(
844 "token:workflows",
845 format!("This access token cannot change the workflow file {path}: {why}."),
846 ))
847}
848
849/// The workflow job a token was made for.
850#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
851pub struct JobToken {
852 /// The run, `run_…`.
853 pub run_id: String,
854 /// The job, `job_…`.
855 pub job_id: String,
856 /// Whether it may open pull requests and approve them, by its
857 /// repository's and workspace's choice ("Allow g1t Actions to create and
858 /// approve pull requests"). Off unless chosen.
859 #[serde(default)]
860 pub pull_requests: bool,
861}
862
863impl TokenAccess {
864 /// Full access to everything: the access tokens made before scopes had.
865 pub fn full() -> Self {
866 TokenAccess::default()
867 }
868
869 /// Whether it may reach the repository `owner/name`: every token but a
870 /// workflow job's, which reaches its own repository only.
871 pub fn reaches(&self, repo: &str) -> bool {
872 self.repo.as_deref().is_none_or(|only| only.eq_ignore_ascii_case(repo))
873 }
874
875 pub fn is_full(&self) -> bool {
876 self.scopes.is_none()
877 }
878
879 /// The scopes it holds, or `None` for full access.
880 pub fn granted(&self) -> Option<Vec<Scope>> {
881 self.scopes
882 .as_ref()
883 .map(|scopes| scopes.iter().filter_map(|scope| Scope::parse(scope)).collect())
884 }
885
886 pub fn allows(&self, needed: Scope) -> bool {
887 match self.granted() {
888 None => true,
889 Some(granted) => granted.iter().any(|held| held.includes(needed)),
890 }
891 }
892
893 /// Whether it reaches the repository with this id in `namespace` for
894 /// more than reading a public one: every token but a narrowed one
895 /// outside its workspace or repository selection. Its owner's role
896 /// still decides; see [`crate::access`].
897 pub fn covers_repo(&self, repo_id: &str, namespace: &str) -> bool {
898 self.reach.as_ref().is_none_or(|reach| reach.covers(repo_id, namespace))
899 }
900}
901
902/// Every operation of the API and MCP server, with the scope it needs. An
903/// operation in [`NO_SCOPE`] needs none. The API checks that every one of
904/// its operations is in exactly one of the two.
905pub const OPERATIONS: &[(&str, Scope)] = &[
906 // Your account.
907 ("list_emails", Scope::AccountRead),
908 ("add_email", Scope::AccountWrite),
909 ("confirm_email", Scope::AccountWrite),
910 ("remove_email", Scope::AccountWrite),
911 ("update_email_settings", Scope::AccountWrite),
912 ("list_invites", Scope::AccountRead),
913 ("create_invite", Scope::AccountWrite),
914 ("revoke_invite", Scope::AccountWrite),
915 ("resend_invite", Scope::AccountWrite),
916 ("list_invitations", Scope::AccountRead),
917 ("accept_invitation", Scope::AccountWrite),
918 ("decline_invitation", Scope::AccountWrite),
919 ("list_my_repo_invitations", Scope::AccountRead),
920 ("accept_repo_invitation", Scope::AccountWrite),
921 ("decline_repo_invitation", Scope::AccountWrite),
922 // Your pinned projects: a preference of your account.
923 ("list_pinned_projects", Scope::AccountRead),
924 ("pin_project", Scope::AccountWrite),
925 // Your stars: a preference of your account.
926 ("list_starred", Scope::AccountRead),
927 ("check_starred", Scope::AccountRead),
928 ("star_repo", Scope::AccountWrite),
929 ("unstar_repo", Scope::AccountWrite),
930 ("unpin_project", Scope::AccountWrite),
931 ("reorder_pinned_projects", Scope::AccountWrite),
932 // Your inbox: notifications, subscriptions and watching.
933 ("list_notifications", Scope::NotificationsRead),
934 ("get_notification_thread", Scope::NotificationsRead),
935 ("get_thread_subscription", Scope::NotificationsRead),
936 ("get_repo_subscription", Scope::NotificationsRead),
937 ("list_watched_repos", Scope::NotificationsRead),
938 ("mark_notifications_read", Scope::NotificationsWrite),
939 ("mark_thread_read", Scope::NotificationsWrite),
940 ("mark_thread_done", Scope::NotificationsWrite),
941 ("save_thread", Scope::NotificationsWrite),
942 ("snooze_thread", Scope::NotificationsWrite),
943 ("set_thread_subscription", Scope::NotificationsWrite),
944 ("delete_thread_subscription", Scope::NotificationsWrite),
945 ("set_repo_subscription", Scope::NotificationsWrite),
946 ("delete_repo_subscription", Scope::NotificationsWrite),
947 // Workspaces, their invites and integrations.
948 ("create_workspace", Scope::WorkspaceAdmin),
949 ("delete_workspace", Scope::WorkspaceAdmin),
950 ("get_workspace", Scope::WorkspaceRead),
951 ("update_workspace", Scope::WorkspaceAdmin),
952 // Its members, and who owns it.
953 ("list_members", Scope::WorkspaceRead),
954 ("update_member", Scope::WorkspaceAdmin),
955 ("remove_member", Scope::WorkspaceAdmin),
956 ("transfer_ownership", Scope::WorkspaceAdmin),
957 ("leave_workspace", Scope::AccountWrite),
958 ("list_workspace_invites", Scope::WorkspaceRead),
959 ("invite_member", Scope::WorkspaceAdmin),
960 ("revoke_workspace_invite", Scope::WorkspaceAdmin),
961 ("list_integrations", Scope::WorkspaceRead),
962 ("connect_integration", Scope::WorkspaceAdmin),
963 ("update_integration", Scope::WorkspaceAdmin),
964 ("disconnect_integration", Scope::WorkspaceAdmin),
965 ("test_integration", Scope::WorkspaceAdmin),
966 // Its AI: the AI providers it keeps keys for, and what Ask answers with.
967 ("list_ai_providers", Scope::WorkspaceRead),
968 ("add_ai_provider", Scope::WorkspaceAdmin),
969 ("update_ai_provider", Scope::WorkspaceAdmin),
970 ("remove_ai_provider", Scope::WorkspaceAdmin),
971 ("test_ai_provider", Scope::WorkspaceAdmin),
972 ("get_ask_settings", Scope::WorkspaceRead),
973 ("set_ask_settings", Scope::WorkspaceAdmin),
974 // Teams: reading them, and managing them. A team's role on a
975 // repository is who has access.
976 ("list_teams", Scope::WorkspaceRead),
977 ("get_team", Scope::WorkspaceRead),
978 ("list_team_members", Scope::WorkspaceRead),
979 ("list_child_teams", Scope::WorkspaceRead),
980 ("list_team_repos", Scope::WorkspaceRead),
981 ("list_user_teams", Scope::WorkspaceRead),
982 ("create_team", Scope::WorkspaceAdmin),
983 ("list_workspace_rulesets", Scope::WorkspaceRead),
984 ("get_workspace_ruleset", Scope::WorkspaceRead),
985 ("list_workspace_rule_evaluations", Scope::WorkspaceRead),
986 ("create_workspace_ruleset", Scope::WorkspaceAdmin),
987 ("update_workspace_ruleset", Scope::WorkspaceAdmin),
988 ("delete_workspace_ruleset", Scope::WorkspaceAdmin),
989 ("update_team", Scope::WorkspaceAdmin),
990 ("delete_team", Scope::WorkspaceAdmin),
991 ("set_team_member", Scope::WorkspaceAdmin),
992 ("remove_team_member", Scope::WorkspaceAdmin),
993 ("set_team_review_assignment", Scope::WorkspaceAdmin),
994 // A workspace's billing: usage, budget and invoices.
995 ("get_usage", Scope::BillingRead),
996 ("get_budget", Scope::BillingRead),
997 ("list_invoices", Scope::BillingRead),
998 ("get_billing_details", Scope::BillingRead),
999 ("set_budget", Scope::BillingWrite),
1000 // Repositories.
1001 ("list_repos", Scope::RepoRead),
1002 ("get_repo", Scope::RepoRead),
1003 // A repository's files, as clone and fetch need.
1004 // A file or directory of a repository, as clone and fetch would give it.
1005 ("get_contents", Scope::CodeRead),
1006 ("list_commits", Scope::CodeRead),
1007 ("download_tarball_archive", Scope::CodeRead),
1008 ("download_zipball_archive", Scope::CodeRead),
1009 ("why", Scope::CodeRead),
1010 // Projects follow their repositories.
1011 ("list_projects", Scope::RepoRead),
1012 ("get_project", Scope::RepoRead),
1013 ("search", Scope::RepoRead),
1014 ("list_events", Scope::RepoRead),
1015 // A workspace's activity: the events of its repositories the caller can read.
1016 ("get_workspace_activity", Scope::RepoRead),
1017 // What the default branch says about a repository, who starred it, and
1018 // its releases.
1019 ("get_languages", Scope::RepoRead),
1020 ("list_contributors", Scope::RepoRead),
1021 ("get_license", Scope::RepoRead),
1022 ("list_stargazers", Scope::RepoRead),
1023 ("list_releases", Scope::RepoRead),
1024 ("get_latest_release", Scope::RepoRead),
1025 ("get_release_by_tag", Scope::RepoRead),
1026 ("get_release", Scope::RepoRead),
1027 ("create_release", Scope::RepoWrite),
1028 ("update_release", Scope::RepoWrite),
1029 ("delete_release", Scope::RepoWrite),
1030 ("list_labels", Scope::RepoRead),
1031 ("list_milestones", Scope::RepoRead),
1032 ("get_milestone", Scope::RepoRead),
1033 ("create_label", Scope::IssuesWrite),
1034 ("update_label", Scope::IssuesWrite),
1035 ("delete_label", Scope::IssuesWrite),
1036 ("add_default_labels", Scope::IssuesWrite),
1037 ("create_milestone", Scope::IssuesWrite),
1038 ("update_milestone", Scope::IssuesWrite),
1039 ("delete_milestone", Scope::IssuesWrite),
1040 ("get_repo_settings", Scope::RepoRead),
1041 ("list_check_names", Scope::RepoRead),
1042 ("list_deleted_repos", Scope::RepoRead),
1043 ("list_security_alerts", Scope::RepoRead),
1044 ("get_codeowners_errors", Scope::RepoRead),
1045 ("create_repo", Scope::RepoWrite),
1046 ("update_repo", Scope::RepoWrite),
1047 ("update_project", Scope::RepoWrite),
1048 ("update_repo_settings", Scope::RepoWrite),
1049 // Rulesets: reading them is reading the repository; changing them
1050 // changes what everyone, agents included, may do, so it is admin.
1051 ("list_repo_rulesets", Scope::RepoRead),
1052 ("get_repo_ruleset", Scope::RepoRead),
1053 ("get_branch_rules", Scope::RepoRead),
1054 ("list_rule_evaluations", Scope::RepoRead),
1055 ("create_repo_ruleset", Scope::RepoAdmin),
1056 ("update_repo_ruleset", Scope::RepoAdmin),
1057 ("delete_repo_ruleset", Scope::RepoAdmin),
1058 ("rename_branch", Scope::RepoWrite),
1059 ("create_branch", Scope::RepoWrite),
1060 ("delete_branch", Scope::RepoWrite),
1061 ("rename_repo", Scope::RepoAdmin),
1062 ("transfer_repo", Scope::RepoAdmin),
1063 ("archive_repo", Scope::RepoAdmin),
1064 ("unarchive_repo", Scope::RepoAdmin),
1065 ("set_repo_visibility", Scope::RepoAdmin),
1066 ("delete_repo", Scope::RepoAdmin),
1067 ("restore_repo", Scope::RepoAdmin),
1068 ("purge_repo", Scope::RepoAdmin),
1069 // A dismissed secret is let through push protection.
1070 ("dismiss_security_alert", Scope::RepoAdmin),
1071 ("reopen_security_alert", Scope::RepoAdmin),
1072 // The security suite: alerts, push protection, patterns, code
1073 // scanning, the supply chain and settings.
1074 ("list_secret_scanning_alerts", Scope::SecurityRead),
1075 ("get_secret_scanning_alert", Scope::SecurityRead),
1076 ("list_secret_scanning_locations", Scope::SecurityRead),
1077 ("list_bypass_requests", Scope::SecurityRead),
1078 ("list_custom_patterns", Scope::SecurityRead),
1079 ("list_code_scanning_alerts", Scope::SecurityRead),
1080 ("get_code_scanning_alert", Scope::SecurityRead),
1081 ("list_code_scanning_analyses", Scope::SecurityRead),
1082 ("get_sarif_upload", Scope::SecurityRead),
1083 ("list_vulnerability_alerts", Scope::SecurityRead),
1084 ("get_vulnerability_alert", Scope::SecurityRead),
1085 ("get_dependency_graph", Scope::SecurityRead),
1086 ("get_sbom", Scope::SecurityRead),
1087 ("compare_dependencies", Scope::SecurityRead),
1088 ("get_security_settings", Scope::SecurityRead),
1089 ("get_workspace_security_settings", Scope::SecurityRead),
1090 ("get_security_overview", Scope::SecurityRead),
1091 ("list_security_advisories", Scope::SecurityRead),
1092 ("get_security_advisory", Scope::SecurityRead),
1093 ("list_vulnerability_reports", Scope::SecurityRead),
1094 ("update_secret_scanning_alert", Scope::SecurityWrite),
1095 ("bypass_push_protection", Scope::SecurityWrite),
1096 ("check_secret_validity", Scope::SecurityWrite),
1097 ("review_bypass_request", Scope::SecurityWrite),
1098 ("create_custom_pattern", Scope::SecurityWrite),
1099 ("update_custom_pattern", Scope::SecurityWrite),
1100 ("delete_custom_pattern", Scope::SecurityWrite),
1101 ("dry_run_custom_pattern", Scope::SecurityWrite),
1102 ("update_code_scanning_alert", Scope::SecurityWrite),
1103 ("upload_sarif", Scope::SecurityWrite),
1104 ("update_vulnerability_alert", Scope::SecurityWrite),
1105 ("update_security_settings", Scope::SecurityWrite),
1106 ("update_workspace_security_settings", Scope::SecurityWrite),
1107 ("create_security_advisory", Scope::SecurityWrite),
1108 ("update_security_advisory", Scope::SecurityWrite),
1109 ("set_security_advisory_state", Scope::SecurityWrite),
1110 ("report_vulnerability", Scope::SecurityWrite),
1111 ("review_vulnerability_report", Scope::SecurityWrite),
1112 // Issues.
1113 ("list_issues", Scope::IssuesRead),
1114 ("get_issue", Scope::IssuesRead),
1115 ("create_issue", Scope::IssuesWrite),
1116 ("update_issue", Scope::IssuesWrite),
1117 ("list_issue_labels", Scope::IssuesRead),
1118 ("add_issue_labels", Scope::IssuesWrite),
1119 ("set_issue_labels", Scope::IssuesWrite),
1120 ("remove_issue_labels", Scope::IssuesWrite),
1121 ("close_issue", Scope::IssuesWrite),
1122 ("reopen_issue", Scope::IssuesWrite),
1123 ("add_comment", Scope::IssuesWrite),
1124 ("edit_comment", Scope::IssuesWrite),
1125 ("delete_comment", Scope::IssuesWrite),
1126 // Looking up a ticket the work refers to, through the workspace's
1127 // integrations, and bringing one in as an issue.
1128 ("get_context", Scope::IssuesRead),
1129 ("import_issue", Scope::IssuesWrite),
1130 // Coordinating work on issues: claims, and the context to pick one up.
1131 ("list_claims", Scope::IssuesRead),
1132 ("get_work", Scope::IssuesRead),
1133 ("claim_issue", Scope::IssuesWrite),
1134 ("release_claim", Scope::IssuesWrite),
1135 ("hand_off_issue", Scope::IssuesWrite),
1136 // Pull requests.
1137 ("list_pull_requests", Scope::PullRequestsRead),
1138 ("get_pull_request", Scope::PullRequestsRead),
1139 ("get_pull_request_changes", Scope::PullRequestsRead),
1140 ("read_session", Scope::PullRequestsRead),
1141 ("get_merge_queue", Scope::PullRequestsRead),
1142 ("list_decisions", Scope::PullRequestsRead),
1143 ("create_pull_request", Scope::PullRequestsWrite),
1144 ("update_pull_request", Scope::PullRequestsWrite),
1145 ("record_session", Scope::PullRequestsWrite),
1146 ("record_decision", Scope::PullRequestsWrite),
1147 ("mark_pull_request_ready", Scope::PullRequestsWrite),
1148 ("close_pull_request", Scope::PullRequestsWrite),
1149 ("reopen_pull_request", Scope::PullRequestsWrite),
1150 ("convert_pull_request_to_draft", Scope::PullRequestsWrite),
1151 ("review_pull_request", Scope::PullRequestsWrite),
1152 ("merge_pull_request", Scope::PullRequestsWrite),
1153 ("request_reviewers", Scope::PullRequestsWrite),
1154 ("remove_requested_reviewers", Scope::PullRequestsWrite),
1155 // Harness sessions, which record how pull requests are made.
1156 ("get_session", Scope::PullRequestsRead),
1157 ("list_sessions", Scope::PullRequestsRead),
1158 ("start_session", Scope::PullRequestsWrite),
1159 ("update_session", Scope::PullRequestsWrite),
1160 ("end_session", Scope::PullRequestsWrite),
1161 ("record_session_entries", Scope::PullRequestsWrite),
1162 ("start_agent_session", Scope::PullRequestsWrite),
1163 // Workflows.
1164 ("list_workflows", Scope::WorkflowsRead),
1165 ("get_workflow", Scope::WorkflowsRead),
1166 ("list_workflow_runs", Scope::WorkflowsRead),
1167 ("get_workflow_run", Scope::WorkflowsRead),
1168 ("get_job_logs", Scope::WorkflowsRead),
1169 ("dispatch_workflow", Scope::WorkflowsWrite),
1170 ("cancel_workflow_run", Scope::WorkflowsWrite),
1171 ("rerun_workflow_run", Scope::WorkflowsWrite),
1172 ("update_workflow", Scope::WorkflowsWrite),
1173 ("list_artifacts", Scope::WorkflowsRead),
1174 ("list_workflow_run_artifacts", Scope::WorkflowsRead),
1175 ("get_artifact", Scope::WorkflowsRead),
1176 ("download_artifact", Scope::WorkflowsRead),
1177 ("get_artifact_retention", Scope::WorkflowsRead),
1178 ("delete_artifact", Scope::WorkflowsWrite),
1179 ("set_artifact_retention", Scope::WorkflowsWrite),
1180 ("list_caches", Scope::WorkflowsRead),
1181 ("get_cache_usage", Scope::WorkflowsRead),
1182 ("delete_caches_by_key", Scope::WorkflowsWrite),
1183 ("delete_cache", Scope::WorkflowsWrite),
1184 // Checks: statuses, check runs and check suites on commits.
1185 ("list_commit_statuses", Scope::ChecksRead),
1186 ("get_combined_status", Scope::ChecksRead),
1187 ("list_check_runs_for_ref", Scope::ChecksRead),
1188 ("get_check_run", Scope::ChecksRead),
1189 ("list_check_run_annotations", Scope::ChecksRead),
1190 ("list_check_suites_for_ref", Scope::ChecksRead),
1191 ("get_check_suite", Scope::ChecksRead),
1192 ("create_commit_status", Scope::ChecksWrite),
1193 ("create_check_run", Scope::ChecksWrite),
1194 ("update_check_run", Scope::ChecksWrite),
1195 ("rerequest_check_run", Scope::ChecksWrite),
1196 ("rerequest_check_suite", Scope::ChecksWrite),
1197 // Deployments, wherever they run: reading them, and reporting them.
1198 ("list_deployments", Scope::DeploymentsRead),
1199 ("get_deployment", Scope::DeploymentsRead),
1200 ("list_deployment_statuses", Scope::DeploymentsRead),
1201 ("list_environments", Scope::DeploymentsRead),
1202 ("get_environment", Scope::DeploymentsRead),
1203 ("create_deployment", Scope::DeploymentsWrite),
1204 ("create_deployment_status", Scope::DeploymentsWrite),
1205 ("start_deployment_build", Scope::DeploymentsWrite),
1206 // Observability: what a project's software did, and how it is collected.
1207 ("get_observability_overview", Scope::ObservabilityRead),
1208 ("list_requests", Scope::ObservabilityRead),
1209 ("get_request", Scope::ObservabilityRead),
1210 ("list_logs", Scope::ObservabilityRead),
1211 ("list_traces", Scope::ObservabilityRead),
1212 ("get_trace", Scope::ObservabilityRead),
1213 ("list_errors", Scope::ObservabilityRead),
1214 ("list_metrics", Scope::ObservabilityRead),
1215 ("get_metric", Scope::ObservabilityRead),
1216 ("get_observability_settings", Scope::ObservabilityRead),
1217 ("list_ingest_tokens", Scope::ObservabilityRead),
1218 ("list_telemetry_exports", Scope::ObservabilityRead),
1219 ("get_observability_usage", Scope::ObservabilityRead),
1220 ("update_error", Scope::ObservabilityWrite),
1221 ("update_observability_settings", Scope::ObservabilityWrite),
1222 ("create_ingest_token", Scope::ObservabilityWrite),
1223 ("delete_ingest_token", Scope::ObservabilityWrite),
1224 ("create_telemetry_export", Scope::ObservabilityWrite),
1225 ("update_telemetry_export", Scope::ObservabilityWrite),
1226 ("delete_telemetry_export", Scope::ObservabilityWrite),
1227 // What keeps runs safe: the runs environments hold and reviewing them,
1228 // approving a pull request's run, and a repository's own rules for
1229 // its environments and tokens, which are an admin's.
1230 ("get_pending_deployments", Scope::WorkflowsRead),
1231 ("review_pending_deployments", Scope::WorkflowsWrite),
1232 ("approve_workflow_run", Scope::WorkflowsWrite),
1233 ("get_workflow_permissions", Scope::RepoRead),
1234 ("get_fork_pr_approval", Scope::RepoRead),
1235 ("get_actions_access", Scope::RepoRead),
1236 ("update_environment", Scope::RepoAdmin),
1237 ("delete_environment", Scope::RepoAdmin),
1238 ("set_workflow_permissions", Scope::RepoAdmin),
1239 ("set_fork_pr_approval", Scope::RepoAdmin),
1240 ("set_actions_access", Scope::RepoAdmin),
1241 // Starting workflows from outside, as a push would.
1242 ("create_repository_dispatch", Scope::CodeWrite),
1243 // A workspace's policy for its repositories' tokens.
1244 ("get_workspace_workflow_permissions", Scope::WorkspaceRead),
1245 ("set_workspace_workflow_permissions", Scope::WorkspaceAdmin),
1246 // The workflows a workspace runs in its repositories: its owners'.
1247 ("list_workspace_managed_workflows", Scope::WorkspaceRead),
1248 ("create_workspace_managed_workflow", Scope::WorkspaceAdmin),
1249 ("update_workspace_managed_workflow", Scope::WorkspaceAdmin),
1250 ("delete_workspace_managed_workflow", Scope::WorkspaceAdmin),
1251 // A workspace's rules for personal access tokens, and the members'
1252 // tokens that reach it: who has access.
1253 ("get_token_policy", Scope::WorkspaceRead),
1254 ("set_token_policy", Scope::WorkspaceAdmin),
1255 ("list_member_tokens", Scope::AccessRead),
1256 ("list_token_requests", Scope::AccessRead),
1257 ("review_token_request", Scope::AccessAdmin),
1258 ("revoke_member_token", Scope::AccessAdmin),
1259 // Who has access.
1260 ("list_collaborators", Scope::AccessRead),
1261 ("get_collaborator_permission", Scope::AccessRead),
1262 ("list_repo_invitations", Scope::AccessRead),
1263 ("list_outside_collaborators", Scope::AccessRead),
1264 ("add_collaborator", Scope::AccessAdmin),
1265 ("update_collaborator", Scope::AccessAdmin),
1266 ("remove_collaborator", Scope::AccessAdmin),
1267 ("revoke_repo_invitation", Scope::AccessAdmin),
1268 ("set_base_permission", Scope::AccessAdmin),
1269 ("set_team_repo", Scope::AccessAdmin),
1270 ("remove_team_repo", Scope::AccessAdmin),
1271 // Deploy keys: each lets a machine reach one repository, so they
1272 // are part of who has access.
1273 ("list_deploy_keys", Scope::AccessRead),
1274 ("get_deploy_key", Scope::AccessRead),
1275 ("create_deploy_key", Scope::AccessAdmin),
1276 ("delete_deploy_key", Scope::AccessAdmin),
1277 // Webhooks.
1278 ("list_webhooks", Scope::WebhooksRead),
1279 ("list_webhook_deliveries", Scope::WebhooksRead),
1280 ("create_webhook", Scope::WebhooksAdmin),
1281 ("update_webhook", Scope::WebhooksAdmin),
1282 ("delete_webhook", Scope::WebhooksAdmin),
1283 ("ping_webhook", Scope::WebhooksAdmin),
1284 ("redeliver_webhook", Scope::WebhooksAdmin),
1285 // Secrets and variables.
1286 ("list_actions_secrets", Scope::SecretsRead),
1287 ("list_actions_variables", Scope::SecretsRead),
1288 ("set_actions_secret", Scope::SecretsAdmin),
1289 ("delete_actions_secret", Scope::SecretsAdmin),
1290 ("set_actions_variable", Scope::SecretsAdmin),
1291 ("delete_actions_variable", Scope::SecretsAdmin),
1292 // Self-hosted runners.
1293 ("list_runners", Scope::RunnersRead),
1294 ("list_runner_groups", Scope::RunnersRead),
1295 ("get_runner_settings", Scope::RunnersRead),
1296 ("create_runner_registration_token", Scope::RunnersAdmin),
1297 ("remove_runner", Scope::RunnersAdmin),
1298 ("create_runner_group", Scope::RunnersAdmin),
1299 ("update_runner_group", Scope::RunnersAdmin),
1300 ("delete_runner_group", Scope::RunnersAdmin),
1301 ("update_runner_settings", Scope::RunnersAdmin),
1302 // Packages: reading them, their versions and who may use them needs
1303 // `packages:read`; changing their settings, access and Manage Actions
1304 // access `packages:write` (and the Admin role on the package, which the
1305 // packages service checks); deleting and restoring packages and
1306 // versions `packages:delete`, as the registries' own deletes do.
1307 ("list_packages", Scope::PackagesRead),
1308 ("get_package", Scope::PackagesRead),
1309 ("list_package_versions", Scope::PackagesRead),
1310 ("get_package_version", Scope::PackagesRead),
1311 ("list_package_access", Scope::PackagesRead),
1312 ("list_package_actions_access", Scope::PackagesRead),
1313 ("update_package", Scope::PackagesWrite),
1314 ("link_package", Scope::PackagesWrite),
1315 ("unlink_package", Scope::PackagesWrite),
1316 ("set_package_access", Scope::PackagesWrite),
1317 ("remove_package_access", Scope::PackagesWrite),
1318 ("set_package_actions_access", Scope::PackagesWrite),
1319 ("remove_package_actions_access", Scope::PackagesWrite),
1320 ("delete_package", Scope::PackagesDelete),
1321 ("restore_package", Scope::PackagesDelete),
1322 ("delete_package_version", Scope::PackagesDelete),
1323 ("restore_package_version", Scope::PackagesDelete),
1324 // Artifacts mode's docs, slides, designs and dashboards (the `artifact`
1325 // MCP tool). Reading takes artifacts:read, making and changing them
1326 // artifacts:write, and sharing them or deleting them for good
1327 // artifacts:admin. The artifacts service then checks the person's own role
1328 // on each one.
1329 ("list_workspace_artifacts", Scope::ArtifactsRead),
1330 ("search_workspace_artifacts", Scope::ArtifactsRead),
1331 ("get_workspace_artifact", Scope::ArtifactsRead),
1332 ("get_workspace_artifact_content", Scope::ArtifactsRead),
1333 ("list_workspace_artifact_versions", Scope::ArtifactsRead),
1334 ("get_workspace_artifact_access", Scope::ArtifactsRead),
1335 ("list_workspace_artifact_templates", Scope::ArtifactsRead),
1336 ("list_workspace_artifact_spaces", Scope::ArtifactsRead),
1337 ("query_workspace_dataset", Scope::ArtifactsRead),
1338 ("create_workspace_artifact", Scope::ArtifactsWrite),
1339 ("update_workspace_artifact", Scope::ArtifactsWrite),
1340 ("edit_workspace_artifact", Scope::ArtifactsWrite),
1341 ("trash_workspace_artifact", Scope::ArtifactsWrite),
1342 ("restore_workspace_artifact", Scope::ArtifactsWrite),
1343 ("restore_workspace_artifact_version", Scope::ArtifactsWrite),
1344 ("set_workspace_artifact_access", Scope::ArtifactsAdmin),
1345 ("purge_workspace_artifact", Scope::ArtifactsAdmin),
1346];
1347
1348/// Operations any token may use: saying who it is.
1349pub const NO_SCOPE: &[&str] = &["whoami"];
1350
1351/// The scope `operation` needs. `None` for one in [`NO_SCOPE`]; an
1352/// operation in neither list needs full access.
1353pub fn scope_for(operation: &str) -> Option<Scope> {
1354 OPERATIONS
1355 .iter()
1356 .find(|(name, _)| *name == operation)
1357 .map(|(_, scope)| *scope)
1358}
1359
1360/// What a token needs for `operation` with this input beyond its own
1361/// scope: changing who has access, rerunning a workflow, and making a
1362/// repository public or private.
1363pub fn extra_scopes(operation: &str, input: &serde_json::Value) -> Vec<Scope> {
1364 let mut extra = Vec::new();
1365 // A workspace's base permission is who has access.
1366 if operation == "update_workspace" && input.get("base_permission").is_some_and(|v| !v.is_null()) {
1367 extra.push(Scope::AccessAdmin);
1368 }
1369 // Asking a g1t Actions job or run to run again reruns its workflow.
1370 if matches!(operation, "rerequest_check_run" | "rerequest_check_suite")
1371 && input["id"].as_str().is_some_and(|id| id.starts_with("job_") || id.starts_with("run_"))
1372 {
1373 extra.push(Scope::WorkflowsWrite);
1374 }
1375 if operation == "update_repo" && (input.get("private").is_some_and(|v| !v.is_null()) || input.get("default_branch").is_some_and(|v| !v.is_null())) {
1376 extra.push(Scope::RepoAdmin);
1377 }
1378 extra
1379}
1380
1381/// The scopes a call needs, its own first.
1382pub fn needed(operation: &str, input: &serde_json::Value) -> Vec<Scope> {
1383 scope_for(operation)
1384 .into_iter()
1385 .chain(extra_scopes(operation, input))
1386 .collect()
1387}
1388
1389/// Whether `access` may use `operation` with `input`. The person's (or
1390/// workspace's) role is checked after this, by the service that owns what
1391/// was asked about.
1392pub fn decide(access: &TokenAccess, operation: &str, input: &serde_json::Value) -> Decision {
1393 let rule = if access.legacy { "token:legacy" } else { "token:scope" };
1394 // A workflow job may open or approve pull requests only where its
1395 // repository and workspace let it, as on GitHub.
1396 if let Some(job) = &access.job
1397 && !job.pull_requests
1398 && (operation == "create_pull_request" || (operation == "review_pull_request" && input["verdict"].as_str() == Some("approve")))
1399 {
1400 return Decision::deny(
1401 "token:pull-requests",
1402 "A workflow job cannot open or approve pull requests here: an admin can allow it under Settings, Actions.",
1403 );
1404 }
1405 if let Some(only) = access.repo.as_deref()
1406 && !NO_SCOPE.contains(&operation)
1407 {
1408 match input["repo"].as_str() {
1409 Some(repo) if access.reaches(repo) => {}
1410 Some(repo) => {
1411 return Decision::deny("token:repository", format!("{} {only}: it cannot reach {repo}.", one_repository(access)));
1412 }
1413 None => {
1414 return Decision::deny("token:repository", format!("{} {only}, and {operation} is not about one repository.", one_repository(access)));
1415 }
1416 }
1417 }
1418 // A token made for one workspace (or none) only reads outside it:
1419 // public repositories, as anyone may. Inside it, its repository
1420 // selection is checked with its owner's role (`access::granted`).
1421 if let Some(reach) = &access.reach
1422 && let Some(repo) = input["repo"].as_str()
1423 && !NO_SCOPE.contains(&operation)
1424 {
1425 let namespace = repo.split('/').next().unwrap_or_default();
1426 let changes = needed(operation, input).iter().any(|scope| scope.level() != Level::Read);
1427 if changes && !reach.owned_by(namespace) {
1428 let made_for = reach.workspace.as_deref().map_or_else(|| "your account only".to_owned(), |workspace| format!("the workspace {workspace}"));
1429 return Decision::deny(
1430 "token:resource-owner",
1431 format!("This access token is made for {made_for}: elsewhere it can only read public repositories, and {repo} is not in its reach."),
1432 );
1433 }
1434 }
1435 if access.scopes.is_some() {
1436 let known = NO_SCOPE.contains(&operation) || scope_for(operation).is_some();
1437 if !known {
1438 return Decision::deny("token:scope", format!("This access token cannot use {operation}: it needs full access."));
1439 }
1440 if let Some(missing) = needed(operation, input).into_iter().find(|scope| !access.allows(*scope)) {
1441 return Decision::deny(
1442 "token:scope",
1443 format!("This access token needs the {} scope to use {operation}.", missing.as_str()),
1444 );
1445 }
1446 }
1447 Decision::allow(rule)
1448}
1449
1450/// What a token held to one repository is, for saying why it was refused.
1451fn one_repository(access: &TokenAccess) -> &'static str {
1452 if access.job.is_some() { "This token is a workflow job's in" } else { "This token reaches only" }
1453}
1454
1455/// Whether a token may use the repository `owner/name` at all: a refusal
1456/// for a workflow job's token or a deploy key in another repository,
1457/// else `None`. Git and
1458/// the package registries ask this before [`decide_git`] and
1459/// [`decide_packages`].
1460pub fn decide_repo(access: &TokenAccess, repo: &str) -> Option<Decision> {
1461 let only = access.repo.as_deref()?;
1462 let why = if access.deploy_key.is_some() {
1463 format!("This deploy key is for {only}: it cannot reach {repo}.")
1464 } else {
1465 format!("{} {only}: it cannot reach {repo}.", one_repository(access))
1466 };
1467 (!access.reaches(repo)).then(|| Decision::deny("token:repository", why))
1468}
1469
1470/// Whether a token may clone or fetch (`write` false), or push to (`write`
1471/// true), a repository with git. `public` is whether anyone may read it,
1472/// which needs no scope.
1473pub fn decide_git(access: &TokenAccess, write: bool, public: bool) -> Decision {
1474 let needed = if write { Scope::CodeWrite } else { Scope::CodeRead };
1475 if !access.allows(needed) && (write || !public) {
1476 if access.deploy_key.is_some() {
1477 return Decision::deny(
1478 "token:scope",
1479 "This deploy key is read-only. An admin of the repository can add it again with write access to push with it.",
1480 );
1481 }
1482 return Decision::deny(
1483 "token:scope",
1484 format!("This access token needs the {} scope to {} with git.", needed.as_str(), if write { "push" } else { "clone or fetch a private repository" }),
1485 );
1486 }
1487 Decision::allow(if access.legacy { "token:legacy" } else { "token:scope" })
1488}
1489
1490/// Whether a token may pull (`Level::Read`), push or publish
1491/// (`Level::Write`), or delete (`Level::Delete`) packages. `public` is
1492/// whether anyone may pull the package, which needs no scope.
1493pub fn decide_packages(access: &TokenAccess, level: Level, public: bool) -> Decision {
1494 let (needed, doing) = match level {
1495 Level::Read => (Scope::PackagesRead, "pull a private package"),
1496 Level::Delete | Level::Admin => (Scope::PackagesDelete, "delete packages"),
1497 Level::Write | Level::Run => (Scope::PackagesWrite, "push or publish packages"),
1498 };
1499 if !access.allows(needed) && !(level == Level::Read && public) {
1500 return Decision::deny(
1501 "token:scope",
1502 format!("This access token needs the {} scope to {doing}.", needed.as_str()),
1503 );
1504 }
1505 Decision::allow(if access.legacy { "token:legacy" } else { "token:scope" })
1506}
1507
1508#[cfg(test)]
1509mod tests {
1510 use super::*;
1511 use serde_json::json;
1512
1513 fn token(scopes: &[Scope]) -> TokenAccess {
1514 TokenAccess {
1515 token_id: "tok_1".to_owned(),
1516 scopes: Some(scopes.iter().map(|scope| scope.as_str().to_owned()).collect()),
1517 legacy: false,
1518 name: None,
1519 ..TokenAccess::default()
1520 }
1521 }
1522
1523 #[test]
1524 fn every_scope_reads_back_and_belongs_to_a_resource() {
1525 for scope in Scope::ALL {
1526 assert_eq!(Scope::parse(scope.as_str()), Some(scope));
1527 assert!(scope.as_str().starts_with(scope.resource().as_str()));
1528 assert!(scope.includes(scope));
1529 }
1530 assert_eq!(Scope::parse(" Issues:Write "), Some(Scope::IssuesWrite));
1531 assert_eq!(Scope::parse("issues"), None);
1532 }
1533
1534 #[test]
1535 fn a_higher_level_includes_the_lower_ones_of_its_resource_only() {
1536 assert!(Scope::RepoAdmin.includes(Scope::RepoRead));
1537 assert!(Scope::RepoAdmin.includes(Scope::RepoWrite));
1538 assert!(Scope::IssuesWrite.includes(Scope::IssuesRead));
1539 assert!(!Scope::IssuesRead.includes(Scope::IssuesWrite));
1540 assert!(!Scope::RepoAdmin.includes(Scope::CodeWrite));
1541 assert!(!Scope::PullRequestsWrite.includes(Scope::IssuesWrite));
1542 }
1543
1544 #[test]
1545 fn operations_are_listed_once_and_never_also_free() {
1546 let mut seen = std::collections::HashSet::new();
1547 for (name, _) in OPERATIONS {
1548 assert!(seen.insert(*name), "{name} twice");
1549 assert!(!NO_SCOPE.contains(name), "{name}");
1550 }
1551 }
1552
1553 #[test]
1554 fn scopes_are_parsed_from_oauth_text_leaving_out_unknown_ones() {
1555 assert_eq!(
1556 parse_scopes("issues:write repo:read,bogus:thing issues:write"),
1557 vec![Scope::RepoRead, Scope::IssuesWrite]
1558 );
1559 assert_eq!(scopes_text(&[Scope::RepoRead, Scope::IssuesWrite]), "repo:read issues:write");
1560 }
1561
1562 #[test]
1563 fn the_oauth_default_is_the_agent_preset_and_never_admin() {
1564 let scopes = oauth_default();
1565 assert!(scopes.contains(&Scope::IssuesWrite));
1566 assert!(scopes.contains(&Scope::PullRequestsWrite));
1567 assert!(!scopes.contains(&Scope::AgentsRun));
1568 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{scopes:?}");
1569 for read in Scope::ALL.into_iter().filter(|scope| scope.level() == Level::Read && scope.offered()) {
1570 // Every read offered but the machines work runs on, and chat.
1571 assert_eq!(scopes.contains(&read), read != Scope::RunnersRead && read != Scope::ChatRead, "{read:?}");
1572 }
1573 assert!(Preset::ReadOnly.scopes().unwrap().iter().all(|scope| scope.level() == Level::Read));
1574 assert_eq!(Preset::Full.scopes(), None);
1575 }
1576
1577 #[test]
1578 fn retired_scopes_parse_but_are_never_granted() {
1579 // Stored tokens and OAuth grants that hold them still read.
1580 for text in ["agents:run", "memory:read", "memory:write", "models:read", "models:write"] {
1581 let scope = Scope::parse(text).unwrap();
1582 assert!(scope.resource().retired() && !scope.offered(), "{text}");
1583 let back: Scope = serde_json::from_value(json!(text)).unwrap();
1584 assert_eq!(back, scope);
1585 }
1586 // But nothing hands them out, and asking for them gets the rest.
1587 assert_eq!(parse_scopes("agents:run issues:read memory:write models:write"), vec![Scope::IssuesRead]);
1588 assert!(!offered_scopes().iter().any(|scope| scope.resource().retired()));
1589 assert!(!everything().iter().any(|scope| scope.resource().retired()));
1590 for preset in Preset::ALL {
1591 let scopes = preset.scopes().unwrap_or_default();
1592 assert!(!scopes.iter().any(|scope| scope.resource().retired()), "{}", preset.as_str());
1593 }
1594 // And no operation needs them.
1595 assert!(!OPERATIONS.iter().any(|(_, scope)| scope.resource().retired()));
1596 }
1597
1598 #[test]
1599 fn billing_is_read_by_presets_and_changed_by_none_but_full_access() {
1600 assert!(Preset::ReadOnly.scopes().unwrap().contains(&Scope::BillingRead));
1601 for preset in [Preset::ReadOnly, Preset::Agent, Preset::Ci] {
1602 assert!(!preset.scopes().unwrap().contains(&Scope::BillingWrite), "{}", preset.as_str());
1603 }
1604 assert_eq!(scope_for("set_budget"), Some(Scope::BillingWrite));
1605 assert_eq!(scope_for("get_usage"), Some(Scope::BillingRead));
1606 let reader = token(&[Scope::BillingRead]);
1607 assert!(decide(&reader, "list_invoices", &json!({})).allowed);
1608 assert!(decide(&reader, "set_budget", &json!({})).reason.unwrap().contains("billing:write"));
1609 }
1610
1611 #[test]
1612 fn artifacts_are_offered_read_by_presets_and_shared_only_with_admin() {
1613 for scope in [Scope::ArtifactsRead, Scope::ArtifactsWrite, Scope::ArtifactsAdmin] {
1614 assert_eq!(scope.resource(), Resource::Artifacts);
1615 assert!(scope.offered());
1616 assert!(offered_scopes().contains(&scope));
1617 assert_eq!(parse_scopes(scope.as_str()), vec![scope]);
1618 assert!(OPERATIONS.iter().any(|(_, needed)| *needed == scope), "{scope:?} gates nothing");
1619 }
1620 // Reading them is a read like any other; changing them is chosen.
1621 for preset in [Preset::ReadOnly, Preset::Agent] {
1622 let scopes = preset.scopes().unwrap();
1623 assert!(scopes.contains(&Scope::ArtifactsRead), "{}", preset.as_str());
1624 assert!(!scopes.contains(&Scope::ArtifactsWrite) && !scopes.contains(&Scope::ArtifactsAdmin), "{}", preset.as_str());
1625 }
1626 assert!(!Preset::Ci.scopes().unwrap().contains(&Scope::ArtifactsRead));
1627 assert!(everything().contains(&Scope::ArtifactsAdmin));
1628 assert!(Scope::ArtifactsAdmin.includes(Scope::ArtifactsWrite));
1629 assert!(Scope::ArtifactsAdmin.dangerous());
1630 assert!(!Scope::ArtifactsWrite.dangerous());
1631 assert_eq!(Resource::Artifacts.group(), ResourceGroup::Workspace);
1632 let asked = std::collections::BTreeMap::from([("artifacts".to_owned(), "write".to_owned())]);
1633 assert_eq!(resolve_permissions(&asked, true), Ok(vec![Scope::ArtifactsWrite]));
1634 assert!(offered_scopes().contains(&Scope::ArtifactsAdmin));
1635 // Sharing and deleting for good need admin; editing needs write.
1636 assert_eq!(scope_for("set_workspace_artifact_access"), Some(Scope::ArtifactsAdmin));
1637 assert_eq!(scope_for("purge_workspace_artifact"), Some(Scope::ArtifactsAdmin));
1638 assert_eq!(scope_for("edit_workspace_artifact"), Some(Scope::ArtifactsWrite));
1639 assert_eq!(scope_for("get_workspace_artifact_content"), Some(Scope::ArtifactsRead));
1640 let writer = token(&[Scope::ArtifactsWrite]);
1641 assert!(decide(&writer, "edit_workspace_artifact", &json!({})).allowed);
1642 assert!(decide(&writer, "list_workspace_artifacts", &json!({})).allowed, "write includes read");
1643 assert!(decide(&writer, "set_workspace_artifact_access", &json!({})).reason.unwrap().contains("artifacts:admin"));
1644 // Workflow runs' artifacts are another thing, with their own scope.
1645 let reader = token(&[Scope::ArtifactsRead]);
1646 assert!(!decide(&reader, "list_artifacts", &json!({ "repo": "acme/web" })).allowed);
1647 assert!(!decide(&token(&[Scope::WorkflowsRead]), "list_workspace_artifacts", &json!({})).allowed);
1648 }
1649
1650 #[test]
1651 fn chat_is_a_persons_own_and_given_only_when_asked_for() {
1652 for scope in [Scope::ChatRead, Scope::ChatWrite] {
1653 assert_eq!(scope.resource(), Resource::Chat);
1654 assert!(!scope.dangerous());
1655 assert_eq!(Scope::parse(scope.as_str()), Some(scope));
1656 }
1657 assert_eq!(Resource::Chat.label(), "Chat");
1658 assert_eq!(Resource::Chat.group(), ResourceGroup::Account);
1659 assert!(Scope::ChatWrite.includes(Scope::ChatRead));
1660 assert!(!Scope::ChatRead.includes(Scope::ChatWrite));
1661 // No preset, and so no OAuth default, gives it.
1662 for preset in Preset::ALL {
1663 let scopes = preset.scopes().unwrap_or_default();
1664 assert!(!scopes.iter().any(|scope| scope.resource() == Resource::Chat), "{}", preset.as_str());
1665 }
1666 assert!(!oauth_default().iter().any(|scope| scope.resource() == Resource::Chat));
1667 // An application that asks for it by name gets it; full access holds it.
1668 assert_eq!(parse_scopes("chat:read chat:write"), vec![Scope::ChatRead, Scope::ChatWrite]);
1669 assert!(offered_scopes().contains(&Scope::ChatWrite));
1670 assert!(everything().contains(&Scope::ChatWrite));
1671 assert!(TokenAccess::full().allows(Scope::ChatWrite));
1672 // Only a person's token may hold it.
1673 let asked = std::collections::BTreeMap::from([("chat".to_owned(), "write".to_owned())]);
1674 assert_eq!(resolve_permissions(&asked, true), Ok(vec![Scope::ChatWrite]));
1675 assert!(resolve_permissions(&asked, false).is_err());
1676 }
1677
1678 #[test]
1679 fn checks_are_reported_with_checks_write_which_ci_gets() {
1680 assert_eq!(scope_for("create_check_run"), Some(Scope::ChecksWrite));
1681 assert_eq!(scope_for("create_commit_status"), Some(Scope::ChecksWrite));
1682 assert_eq!(scope_for("list_check_runs_for_ref"), Some(Scope::ChecksRead));
1683 let ci = Preset::Ci.scopes().unwrap();
1684 assert!(ci.contains(&Scope::ChecksWrite));
1685 assert!(!Preset::Agent.scopes().unwrap().contains(&Scope::ChecksWrite));
1686 let reporter = token(&[Scope::ChecksWrite]);
1687 assert!(decide(&reporter, "update_check_run", &json!({ "id": "cr_1" })).allowed);
1688 assert!(decide(&reporter, "rerequest_check_run", &json!({ "id": "cr_1" })).allowed);
1689 // A g1t Actions job runs again as its workflow does.
1690 let refused = decide(&reporter, "rerequest_check_run", &json!({ "id": "job_1" }));
1691 assert!(refused.reason.unwrap().contains("workflows:write"));
1692 }
1693
1694 #[test]
1695 fn a_job_token_reaches_its_repository_only() {
1696 let job = TokenAccess {
1697 repo: Some("acme/web".into()),
1698 job: Some(JobToken { run_id: "run_1".into(), job_id: "job_1".into(), pull_requests: false }),
1699 ..token(&[Scope::RepoRead, Scope::IssuesWrite, Scope::IssuesRead, Scope::PullRequestsWrite])
1700 };
1701 assert!(decide(&job, "create_issue", &json!({ "repo": "acme/web" })).allowed);
1702 assert!(decide(&job, "create_issue", &json!({ "repo": "Acme/Web" })).allowed, "names compare without case");
1703 let elsewhere = decide(&job, "create_issue", &json!({ "repo": "acme/api" }));
1704 assert!(!elsewhere.allowed);
1705 assert_eq!(elsewhere.rule, "token:repository");
1706 // Nothing beyond the one repository, a workspace's listing included.
1707 assert!(!decide(&job, "list_repos", &json!({})).allowed);
1708 assert!(decide(&job, "whoami", &json!({})).allowed);
1709 // Its scopes still hold inside it.
1710 assert!(!decide(&job, "create_pull_request", &json!({ "repo": "acme/web" })).allowed);
1711 assert!(decide_repo(&job, "acme/web").is_none());
1712 assert!(!decide_repo(&job, "acme/api").unwrap().allowed);
1713 assert!(decide_repo(&token(&[Scope::CodeRead]), "acme/api").is_none(), "other tokens reach what their owner can");
1714 // Opening and approving pull requests is off unless allowed.
1715 assert_eq!(decide(&job, "create_pull_request", &json!({ "repo": "acme/web" })).rule, "token:pull-requests");
1716 assert!(!decide(&job, "review_pull_request", &json!({ "repo": "acme/web", "verdict": "approve" })).allowed);
1717 assert!(decide(&job, "review_pull_request", &json!({ "repo": "acme/web", "verdict": "request_changes" })).allowed);
1718 let allowed = TokenAccess { job: Some(JobToken { pull_requests: true, ..job.job.clone().unwrap() }), ..job.clone() };
1719 assert!(decide(&allowed, "create_pull_request", &json!({ "repo": "acme/web" })).allowed);
1720 }
1721
1722 #[test]
1723 fn workflow_files_need_their_own_scope() {
1724 for path in [".g1t/workflows/ci.yml", ".github/workflows/deploy.yaml", "/.github/workflows/x.yml", ".GitHub/Workflows/ci.yml", ".github/workflows"] {
1725 assert!(is_workflow_file(path), "{path}");
1726 }
1727 for path in ["README.md", ".github/CODEOWNERS", ".github/workflowsx/ci.yml", "docs/.github/workflows/ci.yml", ".g1t/actions/ci.yml"] {
1728 assert!(!is_workflow_file(path), "{path}");
1729 }
1730 let code = token(&[Scope::CodeWrite]);
1731 let refused = decide_workflow_files(Some(&code), ["README.md", ".github/workflows/ci.yml"]).unwrap();
1732 assert_eq!(refused.rule, "token:workflows");
1733 assert!(refused.reason.as_deref().unwrap().contains(".github/workflows/ci.yml"));
1734 assert!(refused.reason.as_deref().unwrap().contains("workflow_files:write"));
1735 assert!(decide_workflow_files(Some(&code), ["README.md"]).is_none());
1736 assert!(decide_workflow_files(Some(&token(&[Scope::CodeWrite, Scope::WorkflowFilesWrite])), [".g1t/workflows/ci.yml"]).is_none());
1737 assert!(decide_workflow_files(Some(&TokenAccess::full()), [".g1t/workflows/ci.yml"]).is_none(), "full access");
1738 assert!(decide_workflow_files(None, [".g1t/workflows/ci.yml"]).is_none(), "a signed-in person");
1739 // A job's token never may, as GITHUB_TOKEN never may.
1740 let job = TokenAccess { job: Some(JobToken::default()), ..TokenAccess::full() };
1741 assert!(decide_workflow_files(Some(&job), [".g1t/workflows/ci.yml"]).unwrap().reason.unwrap().contains("job"));
1742 // Nothing in a preset changes workflow files but full access.
1743 for preset in [Preset::ReadOnly, Preset::Agent, Preset::Ci] {
1744 assert!(!preset.scopes().unwrap().contains(&Scope::WorkflowFilesWrite), "{}", preset.as_str());
1745 }
1746 assert!(!Scope::WorkflowFilesWrite.includes(Scope::WorkflowsWrite) && !Scope::WorkflowsWrite.includes(Scope::WorkflowFilesWrite));
1747 }
1748
1749 #[test]
1750 fn a_narrowed_token_only_reads_outside_its_workspace() {
1751 let reach = TokenReach { workspace: Some("acme".into()), repositories: RepositorySelection::All, repo_ids: Vec::new() };
1752 let fine = TokenAccess { reach: Some(reach), ..token(&[Scope::RepoRead, Scope::IssuesRead, Scope::IssuesWrite]) };
1753 assert!(decide(&fine, "create_issue", &json!({ "repo": "acme/web" })).allowed);
1754 assert!(decide(&fine, "create_issue", &json!({ "repo": "Acme/web" })).allowed);
1755 let elsewhere = decide(&fine, "create_issue", &json!({ "repo": "globex/site" }));
1756 assert_eq!(elsewhere.rule, "token:resource-owner");
1757 assert!(elsewhere.reason.unwrap().contains("acme"));
1758 assert!(decide(&fine, "get_issue", &json!({ "repo": "globex/site" })).allowed, "public repositories elsewhere read");
1759 assert!(!decide(&fine, "create_pull_request", &json!({ "repo": "acme/web" })).allowed, "its scopes still hold");
1760 let mine = TokenAccess { reach: Some(TokenReach::default()), ..token(&[Scope::IssuesWrite]) };
1761 assert!(decide(&mine, "create_issue", &json!({ "repo": "acme/web" })).reason.unwrap().contains("your account"));
1762 assert!(fine.covers_repo("rep_1", "acme") && !fine.covers_repo("rep_1", "globex"));
1763 let selected = TokenReach { workspace: Some("acme".into()), repositories: RepositorySelection::Selected, repo_ids: vec!["rep_1".into()] };
1764 assert!(selected.covers("rep_1", "ACME") && !selected.covers("rep_2", "acme"));
1765 let public = TokenReach { repositories: RepositorySelection::Public, ..selected.clone() };
1766 assert!(!public.covers("rep_1", "acme") && public.owned_by("acme"));
1767 assert!(token(&[]).covers_repo("rep_1", "anything"), "a token for every workspace reaches what its owner can");
1768 assert_eq!(RepositorySelection::parse("public_only"), Some(RepositorySelection::Public));
1769 }
1770
1771 #[test]
1772 fn permissions_are_scopes_read_per_resource() {
1773 let asked: std::collections::BTreeMap<String, String> =
1774 [("issues", "write"), ("repo", "read"), ("code", "none"), ("packages", "delete")].iter().map(|(a, b)| ((*a).to_owned(), (*b).to_owned())).collect();
1775 let scopes = resolve_permissions(&asked, true).unwrap();
1776 assert_eq!(scopes, vec![Scope::RepoRead, Scope::PackagesDelete, Scope::IssuesWrite]);
1777 let back = permissions_of(&scopes);
1778 assert_eq!(back.get("issues").map(String::as_str), Some("write"));
1779 assert_eq!(back.get("packages").map(String::as_str), Some("delete"));
1780 assert!(!back.contains_key("code"));
1781 // Lower levels held beside a higher one say nothing more.
1782 assert_eq!(top_scopes(&[Scope::RepoRead, Scope::RepoAdmin, Scope::RepoWrite]), vec![Scope::RepoAdmin]);
1783 // Every offered resource's top, and nothing a level can lose.
1784 let all = everything();
1785 assert_eq!(all.len(), Resource::ALL.into_iter().filter(|resource| resource.offered()).count());
1786 for scope in offered_scopes() {
1787 assert!(all.iter().any(|held| held.includes(scope)), "{scope:?}");
1788 }
1789 }
1790
1791 #[test]
1792 fn permissions_are_checked_by_name_level_and_owner() {
1793 let one = |name: &str, level: &str| -> std::collections::BTreeMap<String, String> { [(name.to_owned(), level.to_owned())].into() };
1794 assert!(resolve_permissions(&one("wiki", "read"), true).unwrap_err().contains("wiki"));
1795 assert!(resolve_permissions(&one("issues", "admin"), true).unwrap_err().contains("read, write"));
1796 assert!(resolve_permissions(&one("workflow_files", "read"), true).is_err(), "workflow files are written only");
1797 assert!(resolve_permissions(&one("notifications", "read"), false).unwrap_err().contains("account"));
1798 assert_eq!(resolve_permissions(&one("notifications", "read"), true).unwrap(), vec![Scope::NotificationsRead]);
1799 assert!(resolve_permissions(&one("agents", "run"), false).unwrap_err().contains("agents"), "retired");
1800 assert!(resolve_permissions(&one("models", "read"), false).is_err(), "retired");
1801 for resource in Resource::ALL {
1802 assert_eq!(Resource::parse(resource.as_str()), Some(resource));
1803 assert!(!resource.scopes().is_empty());
1804 }
1805 }
1806
1807 #[test]
1808 fn a_legacy_token_can_do_everything() {
1809 let legacy = TokenAccess { legacy: true, ..TokenAccess::full() };
1810 for (operation, _) in OPERATIONS {
1811 assert!(decide(&legacy, operation, &json!({})).allowed, "{operation}");
1812 }
1813 assert_eq!(decide(&legacy, "delete_repo", &json!({})).rule, "token:legacy");
1814 }
1815
1816 #[test]
1817 fn a_missing_scope_is_named() {
1818 let read = token(&[Scope::IssuesRead]);
1819 assert!(decide(&read, "get_issue", &json!({})).allowed);
1820 assert!(decide(&read, "whoami", &json!({})).allowed);
1821 let refused = decide(&read, "create_issue", &json!({}));
1822 assert!(!refused.allowed);
1823 assert_eq!(refused.reason.as_deref(), Some("This access token needs the issues:write scope to use create_issue."));
1824 // An operation the table does not know needs full access.
1825 assert!(!decide(&read, "something_new", &json!({})).allowed);
1826 }
1827
1828 #[test]
1829 fn making_a_repository_public_or_private_needs_repo_admin() {
1830 let maintainer = token(&[Scope::RepoWrite]);
1831 assert!(decide(&maintainer, "update_repo", &json!({ "description": "x" })).allowed);
1832 assert!(!decide(&maintainer, "update_repo", &json!({ "private": true })).allowed);
1833 }
1834
1835 #[test]
1836 fn a_workspaces_base_permission_needs_access_admin_too() {
1837 let admin = token(&[Scope::WorkspaceAdmin]);
1838 assert!(decide(&admin, "update_workspace", &json!({ "name": "Acme" })).allowed);
1839 let refused = decide(&admin, "update_workspace", &json!({ "name": "Acme", "base_permission": "read" }));
1840 assert!(refused.reason.unwrap().contains("access:admin"));
1841 let both = token(&[Scope::WorkspaceAdmin, Scope::AccessAdmin]);
1842 assert!(decide(&both, "update_workspace", &json!({ "base_permission": "read" })).allowed);
1843 assert!(!decide(&token(&[Scope::WorkspaceRead]), "update_workspace", &json!({ "name": "Acme" })).allowed);
1844 }
1845
1846 #[test]
1847 fn git_push_needs_code_write_and_private_reads_need_code_read() {
1848 let reader = token(&[Scope::CodeRead]);
1849 assert!(decide_git(&reader, false, false).allowed);
1850 let refused = decide_git(&reader, true, false);
1851 assert!(!refused.allowed);
1852 assert!(refused.reason.unwrap().contains("code:write"));
1853 let issues = token(&[Scope::IssuesWrite]);
1854 assert!(!decide_git(&issues, false, false).allowed);
1855 assert!(decide_git(&issues, false, true).allowed, "public code needs no scope");
1856 assert!(!decide_git(&issues, true, true).allowed, "pushing to public code still needs code:write");
1857 let writer = token(&[Scope::CodeWrite]);
1858 assert!(decide_git(&writer, true, false).allowed);
1859 assert!(decide_git(&writer, false, false).allowed, "code:write includes code:read");
1860 assert!(decide_git(&TokenAccess::full(), true, false).allowed);
1861 }
1862
1863 #[test]
1864 fn packages_need_their_own_scopes_and_public_pulls_none() {
1865 let reader = token(&[Scope::PackagesRead]);
1866 assert!(decide_packages(&reader, Level::Read, false).allowed);
1867 assert!(!decide_packages(&reader, Level::Write, false).allowed);
1868 let code = token(&[Scope::CodeWrite]);
1869 assert!(!decide_packages(&code, Level::Read, false).allowed, "code scopes are not package scopes");
1870 assert!(decide_packages(&code, Level::Read, true).allowed, "public packages pull with any token");
1871 let writer = token(&[Scope::PackagesWrite]);
1872 assert!(decide_packages(&writer, Level::Write, false).allowed);
1873 assert!(decide_packages(&writer, Level::Read, false).allowed, "packages:write includes packages:read");
1874 let refused = decide_packages(&writer, Level::Delete, false);
1875 assert!(refused.reason.unwrap().contains("packages:delete"));
1876 assert!(decide_packages(&token(&[Scope::PackagesDelete]), Level::Write, false).allowed);
1877 assert!(Scope::PackagesDelete.dangerous());
1878 // Tokens made before these scopes, and full-access ones, keep working.
1879 let legacy = TokenAccess { legacy: true, ..TokenAccess::full() };
1880 assert!(decide_packages(&legacy, Level::Delete, false).allowed);
1881 assert!(decide_packages(&TokenAccess::full(), Level::Write, false).allowed);
1882 }
1883
1884 #[test]
1885 fn token_access_travels_as_json() {
1886 let access = token(&[Scope::IssuesRead]);
1887 let wire = serde_json::to_value(&access).unwrap();
1888 assert_eq!(wire["scopes"], json!(["issues:read"]));
1889 assert!(wire.get("resources").is_none());
1890 let back: TokenAccess = serde_json::from_value(wire).unwrap();
1891 assert_eq!(back, access);
1892 let full: TokenAccess = serde_json::from_value(json!({})).unwrap();
1893 assert!(full.is_full());
1894 // A reach written by an older version is ignored: a token reaches
1895 // whatever its owner can.
1896 let older: TokenAccess = serde_json::from_value(json!({
1897 "token_id": "tok_1",
1898 "scopes": ["issues:read"],
1899 "resources": { "kind": "repositories", "repositories": ["acme/rocket"] },
1900 }))
1901 .unwrap();
1902 assert_eq!(older, access);
1903 // Using the website is off unless set, and said only when on.
1904 assert!(!access.website);
1905 assert!(wire_of(&access).get("website").is_none());
1906 let website = TokenAccess { website: true, ..access };
1907 assert_eq!(wire_of(&website)["website"], json!(true));
1908 // Never part of full access.
1909 assert!(!TokenAccess::full().website);
1910 }
1911
1912 fn wire_of(access: &TokenAccess) -> serde_json::Value {
1913 serde_json::to_value(access).unwrap()
1914 }
1915
1916 /// The site's copy of the table, `packages/contracts/src/scopes.ts`,
1917 /// lists the same scopes in the same order, the same operations with
1918 /// the same scopes, and the same presets.
1919 #[test]
1920 fn the_typescript_mirror_has_the_same_table() {
1921 let ts = include_str!("../../../packages/contracts/src/scopes.ts");
1922 let section = |start: &str| {
1923 ts.split_once(start)
1924 .and_then(|(_, rest)| rest.split_once("] as const"))
1925 .map(|(table, _)| table)
1926 .unwrap_or_else(|| panic!("{start} in scopes.ts"))
1927 };
1928 let names = |table: &str| -> Vec<String> {
1929 section(table)
1930 .lines()
1931 .filter_map(|line| line.split_once("scope: \"").and_then(|(_, rest)| rest.split_once('"')).map(|(scope, _)| scope.to_owned()))
1932 .collect()
1933 };
1934 // Offered scopes in `SCOPES`, retired ones in `RETIRED_SCOPES`, the
1935 // rest in `UPCOMING_SCOPES`.
1936 let listed = |keep: fn(&Scope) -> bool| -> Vec<String> { Scope::ALL.iter().filter(|scope| keep(scope)).map(|scope| scope.as_str().to_owned()).collect() };
1937 assert_eq!(names("export const SCOPES = ["), listed(|scope| scope.offered()));
1938 assert_eq!(names("export const UPCOMING_SCOPES"), listed(|scope| !scope.offered() && !scope.resource().retired()));
1939 assert_eq!(names("export const RETIRED_SCOPES"), listed(|scope| scope.resource().retired()));
1940 let operations: Vec<(String, String)> = section("export const OPERATION_SCOPES = [")
1941 .lines()
1942 .filter_map(|line| {
1943 let mut quoted = line.split('"').skip(1).step_by(2);
1944 Some((quoted.next()?.to_owned(), quoted.next()?.to_owned()))
1945 })
1946 .collect();
1947 let expected: Vec<(String, String)> = OPERATIONS
1948 .iter()
1949 .map(|(name, scope)| ((*name).to_owned(), scope.as_str().to_owned()))
1950 .collect();
1951 assert_eq!(operations, expected);
1952 for preset in Preset::ALL {
1953 let list = section(&format!("{}: [", preset.as_str()));
1954 let mirrored: Vec<&str> = list
1955 .split(',')
1956 .map(|item| item.trim().trim_matches('"'))
1957 .filter(|item| !item.is_empty())
1958 .collect();
1959 let expected: Vec<&str> = preset
1960 .scopes()
1961 .map(|scopes| scopes.iter().map(|scope| scope.as_str()).collect())
1962 .unwrap_or_else(|| vec!["*"]);
1963 assert_eq!(mirrored, expected, "{}", preset.as_str());
1964 }
1965 // Each resource with its group, in the same order: offered ones in
1966 // `SCOPE_RESOURCES`, retired ones in `RETIRED_RESOURCES`, the rest in
1967 // `UPCOMING_RESOURCES`.
1968 let tables: [(&str, fn(Resource) -> bool); 3] = [
1969 ("export const SCOPE_RESOURCES", |resource| resource.offered()),
1970 ("export const UPCOMING_RESOURCES", |resource| !resource.offered() && !resource.retired()),
1971 ("export const RETIRED_RESOURCES", |resource| resource.retired()),
1972 ];
1973 for (table, keep) in tables {
1974 let resources = ts
1975 .split_once(table)
1976 .and_then(|(_, rest)| rest.split_once("
1977];"))
1978 .map(|(table, _)| table)
1979 .unwrap_or_else(|| panic!("{table} in scopes.ts"));
1980 let rows: Vec<&str> = resources.lines().filter(|line| line.trim_start().starts_with("{ resource:")).collect();
1981 let expected: Vec<Resource> = Resource::ALL.into_iter().filter(|resource| keep(*resource)).collect();
1982 assert_eq!(rows.len(), expected.len(), "{table}");
1983 for (row, resource) in rows.iter().zip(expected) {
1984 assert!(row.contains(&format!("resource: \"{}\"", resource.as_str())), "{row}");
1985 assert!(row.contains(&format!("group: \"{}\"", resource.group().as_str())), "{row}");
1986 }
1987 }
1988 }
1989}