Skip to content
1,981 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, teams and rulesets",
433 Scope::WorkspaceAdmin => "Create and delete workspaces, invite members, connect integrations, 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 // Teams: reading them, and managing them. A team's role on a
967 // repository is who has access.
968 ("list_teams", Scope::WorkspaceRead),
969 ("get_team", Scope::WorkspaceRead),
970 ("list_team_members", Scope::WorkspaceRead),
971 ("list_child_teams", Scope::WorkspaceRead),
972 ("list_team_repos", Scope::WorkspaceRead),
973 ("list_user_teams", Scope::WorkspaceRead),
974 ("create_team", Scope::WorkspaceAdmin),
975 ("list_workspace_rulesets", Scope::WorkspaceRead),
976 ("get_workspace_ruleset", Scope::WorkspaceRead),
977 ("list_workspace_rule_evaluations", Scope::WorkspaceRead),
978 ("create_workspace_ruleset", Scope::WorkspaceAdmin),
979 ("update_workspace_ruleset", Scope::WorkspaceAdmin),
980 ("delete_workspace_ruleset", Scope::WorkspaceAdmin),
981 ("update_team", Scope::WorkspaceAdmin),
982 ("delete_team", Scope::WorkspaceAdmin),
983 ("set_team_member", Scope::WorkspaceAdmin),
984 ("remove_team_member", Scope::WorkspaceAdmin),
985 ("set_team_review_assignment", Scope::WorkspaceAdmin),
986 // A workspace's billing: usage, budget and invoices.
987 ("get_usage", Scope::BillingRead),
988 ("get_budget", Scope::BillingRead),
989 ("list_invoices", Scope::BillingRead),
990 ("get_billing_details", Scope::BillingRead),
991 ("set_budget", Scope::BillingWrite),
992 // Repositories.
993 ("list_repos", Scope::RepoRead),
994 ("get_repo", Scope::RepoRead),
995 // A repository's files, as clone and fetch need.
996 // A file or directory of a repository, as clone and fetch would give it.
997 ("get_contents", Scope::CodeRead),
998 ("list_commits", Scope::CodeRead),
999 ("download_tarball_archive", Scope::CodeRead),
1000 ("download_zipball_archive", Scope::CodeRead),
1001 ("why", Scope::CodeRead),
1002 // Projects follow their repositories.
1003 ("list_projects", Scope::RepoRead),
1004 ("get_project", Scope::RepoRead),
1005 ("search", Scope::RepoRead),
1006 ("list_events", Scope::RepoRead),
1007 // A workspace's activity: the events of its repositories the caller can read.
1008 ("get_workspace_activity", Scope::RepoRead),
1009 // What the default branch says about a repository, who starred it, and
1010 // its releases.
1011 ("get_languages", Scope::RepoRead),
1012 ("list_contributors", Scope::RepoRead),
1013 ("get_license", Scope::RepoRead),
1014 ("list_stargazers", Scope::RepoRead),
1015 ("list_releases", Scope::RepoRead),
1016 ("get_latest_release", Scope::RepoRead),
1017 ("get_release_by_tag", Scope::RepoRead),
1018 ("get_release", Scope::RepoRead),
1019 ("create_release", Scope::RepoWrite),
1020 ("update_release", Scope::RepoWrite),
1021 ("delete_release", Scope::RepoWrite),
1022 ("list_labels", Scope::RepoRead),
1023 ("list_milestones", Scope::RepoRead),
1024 ("get_milestone", Scope::RepoRead),
1025 ("create_label", Scope::IssuesWrite),
1026 ("update_label", Scope::IssuesWrite),
1027 ("delete_label", Scope::IssuesWrite),
1028 ("add_default_labels", Scope::IssuesWrite),
1029 ("create_milestone", Scope::IssuesWrite),
1030 ("update_milestone", Scope::IssuesWrite),
1031 ("delete_milestone", Scope::IssuesWrite),
1032 ("get_repo_settings", Scope::RepoRead),
1033 ("list_check_names", Scope::RepoRead),
1034 ("list_deleted_repos", Scope::RepoRead),
1035 ("list_security_alerts", Scope::RepoRead),
1036 ("get_codeowners_errors", Scope::RepoRead),
1037 ("create_repo", Scope::RepoWrite),
1038 ("update_repo", Scope::RepoWrite),
1039 ("update_project", Scope::RepoWrite),
1040 ("update_repo_settings", Scope::RepoWrite),
1041 // Rulesets: reading them is reading the repository; changing them
1042 // changes what everyone, agents included, may do, so it is admin.
1043 ("list_repo_rulesets", Scope::RepoRead),
1044 ("get_repo_ruleset", Scope::RepoRead),
1045 ("get_branch_rules", Scope::RepoRead),
1046 ("list_rule_evaluations", Scope::RepoRead),
1047 ("create_repo_ruleset", Scope::RepoAdmin),
1048 ("update_repo_ruleset", Scope::RepoAdmin),
1049 ("delete_repo_ruleset", Scope::RepoAdmin),
1050 ("rename_branch", Scope::RepoWrite),
1051 ("create_branch", Scope::RepoWrite),
1052 ("delete_branch", Scope::RepoWrite),
1053 ("rename_repo", Scope::RepoAdmin),
1054 ("transfer_repo", Scope::RepoAdmin),
1055 ("archive_repo", Scope::RepoAdmin),
1056 ("unarchive_repo", Scope::RepoAdmin),
1057 ("set_repo_visibility", Scope::RepoAdmin),
1058 ("delete_repo", Scope::RepoAdmin),
1059 ("restore_repo", Scope::RepoAdmin),
1060 ("purge_repo", Scope::RepoAdmin),
1061 // A dismissed secret is let through push protection.
1062 ("dismiss_security_alert", Scope::RepoAdmin),
1063 ("reopen_security_alert", Scope::RepoAdmin),
1064 // The security suite: alerts, push protection, patterns, code
1065 // scanning, the supply chain and settings.
1066 ("list_secret_scanning_alerts", Scope::SecurityRead),
1067 ("get_secret_scanning_alert", Scope::SecurityRead),
1068 ("list_secret_scanning_locations", Scope::SecurityRead),
1069 ("list_bypass_requests", Scope::SecurityRead),
1070 ("list_custom_patterns", Scope::SecurityRead),
1071 ("list_code_scanning_alerts", Scope::SecurityRead),
1072 ("get_code_scanning_alert", Scope::SecurityRead),
1073 ("list_code_scanning_analyses", Scope::SecurityRead),
1074 ("get_sarif_upload", Scope::SecurityRead),
1075 ("list_vulnerability_alerts", Scope::SecurityRead),
1076 ("get_vulnerability_alert", Scope::SecurityRead),
1077 ("get_dependency_graph", Scope::SecurityRead),
1078 ("get_sbom", Scope::SecurityRead),
1079 ("compare_dependencies", Scope::SecurityRead),
1080 ("get_security_settings", Scope::SecurityRead),
1081 ("get_workspace_security_settings", Scope::SecurityRead),
1082 ("get_security_overview", Scope::SecurityRead),
1083 ("list_security_advisories", Scope::SecurityRead),
1084 ("get_security_advisory", Scope::SecurityRead),
1085 ("list_vulnerability_reports", Scope::SecurityRead),
1086 ("update_secret_scanning_alert", Scope::SecurityWrite),
1087 ("bypass_push_protection", Scope::SecurityWrite),
1088 ("check_secret_validity", Scope::SecurityWrite),
1089 ("review_bypass_request", Scope::SecurityWrite),
1090 ("create_custom_pattern", Scope::SecurityWrite),
1091 ("update_custom_pattern", Scope::SecurityWrite),
1092 ("delete_custom_pattern", Scope::SecurityWrite),
1093 ("dry_run_custom_pattern", Scope::SecurityWrite),
1094 ("update_code_scanning_alert", Scope::SecurityWrite),
1095 ("upload_sarif", Scope::SecurityWrite),
1096 ("update_vulnerability_alert", Scope::SecurityWrite),
1097 ("update_security_settings", Scope::SecurityWrite),
1098 ("update_workspace_security_settings", Scope::SecurityWrite),
1099 ("create_security_advisory", Scope::SecurityWrite),
1100 ("update_security_advisory", Scope::SecurityWrite),
1101 ("set_security_advisory_state", Scope::SecurityWrite),
1102 ("report_vulnerability", Scope::SecurityWrite),
1103 ("review_vulnerability_report", Scope::SecurityWrite),
1104 // Issues.
1105 ("list_issues", Scope::IssuesRead),
1106 ("get_issue", Scope::IssuesRead),
1107 ("create_issue", Scope::IssuesWrite),
1108 ("update_issue", Scope::IssuesWrite),
1109 ("list_issue_labels", Scope::IssuesRead),
1110 ("add_issue_labels", Scope::IssuesWrite),
1111 ("set_issue_labels", Scope::IssuesWrite),
1112 ("remove_issue_labels", Scope::IssuesWrite),
1113 ("close_issue", Scope::IssuesWrite),
1114 ("reopen_issue", Scope::IssuesWrite),
1115 ("add_comment", Scope::IssuesWrite),
1116 ("edit_comment", Scope::IssuesWrite),
1117 ("delete_comment", Scope::IssuesWrite),
1118 // Looking up a ticket the work refers to, through the workspace's
1119 // integrations, and bringing one in as an issue.
1120 ("get_context", Scope::IssuesRead),
1121 ("import_issue", Scope::IssuesWrite),
1122 // Coordinating work on issues: claims, and the context to pick one up.
1123 ("list_claims", Scope::IssuesRead),
1124 ("get_work", Scope::IssuesRead),
1125 ("claim_issue", Scope::IssuesWrite),
1126 ("release_claim", Scope::IssuesWrite),
1127 ("hand_off_issue", Scope::IssuesWrite),
1128 // Pull requests.
1129 ("list_pull_requests", Scope::PullRequestsRead),
1130 ("get_pull_request", Scope::PullRequestsRead),
1131 ("get_pull_request_changes", Scope::PullRequestsRead),
1132 ("read_session", Scope::PullRequestsRead),
1133 ("get_merge_queue", Scope::PullRequestsRead),
1134 ("list_decisions", Scope::PullRequestsRead),
1135 ("create_pull_request", Scope::PullRequestsWrite),
1136 ("update_pull_request", Scope::PullRequestsWrite),
1137 ("record_session", Scope::PullRequestsWrite),
1138 ("record_decision", Scope::PullRequestsWrite),
1139 ("mark_pull_request_ready", Scope::PullRequestsWrite),
1140 ("close_pull_request", Scope::PullRequestsWrite),
1141 ("reopen_pull_request", Scope::PullRequestsWrite),
1142 ("convert_pull_request_to_draft", Scope::PullRequestsWrite),
1143 ("review_pull_request", Scope::PullRequestsWrite),
1144 ("merge_pull_request", Scope::PullRequestsWrite),
1145 ("request_reviewers", Scope::PullRequestsWrite),
1146 ("remove_requested_reviewers", Scope::PullRequestsWrite),
1147 // Harness sessions, which record how pull requests are made.
1148 ("get_session", Scope::PullRequestsRead),
1149 ("list_sessions", Scope::PullRequestsRead),
1150 ("start_session", Scope::PullRequestsWrite),
1151 ("update_session", Scope::PullRequestsWrite),
1152 ("end_session", Scope::PullRequestsWrite),
1153 ("record_session_entries", Scope::PullRequestsWrite),
1154 ("start_agent_session", Scope::PullRequestsWrite),
1155 // Workflows.
1156 ("list_workflows", Scope::WorkflowsRead),
1157 ("get_workflow", Scope::WorkflowsRead),
1158 ("list_workflow_runs", Scope::WorkflowsRead),
1159 ("get_workflow_run", Scope::WorkflowsRead),
1160 ("get_job_logs", Scope::WorkflowsRead),
1161 ("dispatch_workflow", Scope::WorkflowsWrite),
1162 ("cancel_workflow_run", Scope::WorkflowsWrite),
1163 ("rerun_workflow_run", Scope::WorkflowsWrite),
1164 ("update_workflow", Scope::WorkflowsWrite),
1165 ("list_artifacts", Scope::WorkflowsRead),
1166 ("list_workflow_run_artifacts", Scope::WorkflowsRead),
1167 ("get_artifact", Scope::WorkflowsRead),
1168 ("download_artifact", Scope::WorkflowsRead),
1169 ("get_artifact_retention", Scope::WorkflowsRead),
1170 ("delete_artifact", Scope::WorkflowsWrite),
1171 ("set_artifact_retention", Scope::WorkflowsWrite),
1172 ("list_caches", Scope::WorkflowsRead),
1173 ("get_cache_usage", Scope::WorkflowsRead),
1174 ("delete_caches_by_key", Scope::WorkflowsWrite),
1175 ("delete_cache", Scope::WorkflowsWrite),
1176 // Checks: statuses, check runs and check suites on commits.
1177 ("list_commit_statuses", Scope::ChecksRead),
1178 ("get_combined_status", Scope::ChecksRead),
1179 ("list_check_runs_for_ref", Scope::ChecksRead),
1180 ("get_check_run", Scope::ChecksRead),
1181 ("list_check_run_annotations", Scope::ChecksRead),
1182 ("list_check_suites_for_ref", Scope::ChecksRead),
1183 ("get_check_suite", Scope::ChecksRead),
1184 ("create_commit_status", Scope::ChecksWrite),
1185 ("create_check_run", Scope::ChecksWrite),
1186 ("update_check_run", Scope::ChecksWrite),
1187 ("rerequest_check_run", Scope::ChecksWrite),
1188 ("rerequest_check_suite", Scope::ChecksWrite),
1189 // Deployments, wherever they run: reading them, and reporting them.
1190 ("list_deployments", Scope::DeploymentsRead),
1191 ("get_deployment", Scope::DeploymentsRead),
1192 ("list_deployment_statuses", Scope::DeploymentsRead),
1193 ("list_environments", Scope::DeploymentsRead),
1194 ("get_environment", Scope::DeploymentsRead),
1195 ("create_deployment", Scope::DeploymentsWrite),
1196 ("create_deployment_status", Scope::DeploymentsWrite),
1197 ("start_deployment_build", Scope::DeploymentsWrite),
1198 // Observability: what a project's software did, and how it is collected.
1199 ("get_observability_overview", Scope::ObservabilityRead),
1200 ("list_requests", Scope::ObservabilityRead),
1201 ("get_request", Scope::ObservabilityRead),
1202 ("list_logs", Scope::ObservabilityRead),
1203 ("list_traces", Scope::ObservabilityRead),
1204 ("get_trace", Scope::ObservabilityRead),
1205 ("list_errors", Scope::ObservabilityRead),
1206 ("list_metrics", Scope::ObservabilityRead),
1207 ("get_metric", Scope::ObservabilityRead),
1208 ("get_observability_settings", Scope::ObservabilityRead),
1209 ("list_ingest_tokens", Scope::ObservabilityRead),
1210 ("list_telemetry_exports", Scope::ObservabilityRead),
1211 ("get_observability_usage", Scope::ObservabilityRead),
1212 ("update_error", Scope::ObservabilityWrite),
1213 ("update_observability_settings", Scope::ObservabilityWrite),
1214 ("create_ingest_token", Scope::ObservabilityWrite),
1215 ("delete_ingest_token", Scope::ObservabilityWrite),
1216 ("create_telemetry_export", Scope::ObservabilityWrite),
1217 ("update_telemetry_export", Scope::ObservabilityWrite),
1218 ("delete_telemetry_export", Scope::ObservabilityWrite),
1219 // What keeps runs safe: the runs environments hold and reviewing them,
1220 // approving a pull request's run, and a repository's own rules for
1221 // its environments and tokens, which are an admin's.
1222 ("get_pending_deployments", Scope::WorkflowsRead),
1223 ("review_pending_deployments", Scope::WorkflowsWrite),
1224 ("approve_workflow_run", Scope::WorkflowsWrite),
1225 ("get_workflow_permissions", Scope::RepoRead),
1226 ("get_fork_pr_approval", Scope::RepoRead),
1227 ("get_actions_access", Scope::RepoRead),
1228 ("update_environment", Scope::RepoAdmin),
1229 ("delete_environment", Scope::RepoAdmin),
1230 ("set_workflow_permissions", Scope::RepoAdmin),
1231 ("set_fork_pr_approval", Scope::RepoAdmin),
1232 ("set_actions_access", Scope::RepoAdmin),
1233 // Starting workflows from outside, as a push would.
1234 ("create_repository_dispatch", Scope::CodeWrite),
1235 // A workspace's policy for its repositories' tokens.
1236 ("get_workspace_workflow_permissions", Scope::WorkspaceRead),
1237 ("set_workspace_workflow_permissions", Scope::WorkspaceAdmin),
1238 // The workflows a workspace runs in its repositories: its owners'.
1239 ("list_workspace_managed_workflows", Scope::WorkspaceRead),
1240 ("create_workspace_managed_workflow", Scope::WorkspaceAdmin),
1241 ("update_workspace_managed_workflow", Scope::WorkspaceAdmin),
1242 ("delete_workspace_managed_workflow", Scope::WorkspaceAdmin),
1243 // A workspace's rules for personal access tokens, and the members'
1244 // tokens that reach it: who has access.
1245 ("get_token_policy", Scope::WorkspaceRead),
1246 ("set_token_policy", Scope::WorkspaceAdmin),
1247 ("list_member_tokens", Scope::AccessRead),
1248 ("list_token_requests", Scope::AccessRead),
1249 ("review_token_request", Scope::AccessAdmin),
1250 ("revoke_member_token", Scope::AccessAdmin),
1251 // Who has access.
1252 ("list_collaborators", Scope::AccessRead),
1253 ("get_collaborator_permission", Scope::AccessRead),
1254 ("list_repo_invitations", Scope::AccessRead),
1255 ("list_outside_collaborators", Scope::AccessRead),
1256 ("add_collaborator", Scope::AccessAdmin),
1257 ("update_collaborator", Scope::AccessAdmin),
1258 ("remove_collaborator", Scope::AccessAdmin),
1259 ("revoke_repo_invitation", Scope::AccessAdmin),
1260 ("set_base_permission", Scope::AccessAdmin),
1261 ("set_team_repo", Scope::AccessAdmin),
1262 ("remove_team_repo", Scope::AccessAdmin),
1263 // Deploy keys: each lets a machine reach one repository, so they
1264 // are part of who has access.
1265 ("list_deploy_keys", Scope::AccessRead),
1266 ("get_deploy_key", Scope::AccessRead),
1267 ("create_deploy_key", Scope::AccessAdmin),
1268 ("delete_deploy_key", Scope::AccessAdmin),
1269 // Webhooks.
1270 ("list_webhooks", Scope::WebhooksRead),
1271 ("list_webhook_deliveries", Scope::WebhooksRead),
1272 ("create_webhook", Scope::WebhooksAdmin),
1273 ("update_webhook", Scope::WebhooksAdmin),
1274 ("delete_webhook", Scope::WebhooksAdmin),
1275 ("ping_webhook", Scope::WebhooksAdmin),
1276 ("redeliver_webhook", Scope::WebhooksAdmin),
1277 // Secrets and variables.
1278 ("list_actions_secrets", Scope::SecretsRead),
1279 ("list_actions_variables", Scope::SecretsRead),
1280 ("set_actions_secret", Scope::SecretsAdmin),
1281 ("delete_actions_secret", Scope::SecretsAdmin),
1282 ("set_actions_variable", Scope::SecretsAdmin),
1283 ("delete_actions_variable", Scope::SecretsAdmin),
1284 // Self-hosted runners.
1285 ("list_runners", Scope::RunnersRead),
1286 ("list_runner_groups", Scope::RunnersRead),
1287 ("get_runner_settings", Scope::RunnersRead),
1288 ("create_runner_registration_token", Scope::RunnersAdmin),
1289 ("remove_runner", Scope::RunnersAdmin),
1290 ("create_runner_group", Scope::RunnersAdmin),
1291 ("update_runner_group", Scope::RunnersAdmin),
1292 ("delete_runner_group", Scope::RunnersAdmin),
1293 ("update_runner_settings", Scope::RunnersAdmin),
1294 // Packages: reading them, their versions and who may use them needs
1295 // `packages:read`; changing their settings, access and Manage Actions
1296 // access `packages:write` (and the Admin role on the package, which the
1297 // packages service checks); deleting and restoring packages and
1298 // versions `packages:delete`, as the registries' own deletes do.
1299 ("list_packages", Scope::PackagesRead),
1300 ("get_package", Scope::PackagesRead),
1301 ("list_package_versions", Scope::PackagesRead),
1302 ("get_package_version", Scope::PackagesRead),
1303 ("list_package_access", Scope::PackagesRead),
1304 ("list_package_actions_access", Scope::PackagesRead),
1305 ("update_package", Scope::PackagesWrite),
1306 ("link_package", Scope::PackagesWrite),
1307 ("unlink_package", Scope::PackagesWrite),
1308 ("set_package_access", Scope::PackagesWrite),
1309 ("remove_package_access", Scope::PackagesWrite),
1310 ("set_package_actions_access", Scope::PackagesWrite),
1311 ("remove_package_actions_access", Scope::PackagesWrite),
1312 ("delete_package", Scope::PackagesDelete),
1313 ("restore_package", Scope::PackagesDelete),
1314 ("delete_package_version", Scope::PackagesDelete),
1315 ("restore_package_version", Scope::PackagesDelete),
1316 // Artifacts mode's docs, slides, designs and dashboards (the `artifact`
1317 // MCP tool). Reading takes artifacts:read, making and changing them
1318 // artifacts:write, and sharing them or deleting them for good
1319 // artifacts:admin. The artifacts service then checks the person's own role
1320 // on each one.
1321 ("list_workspace_artifacts", Scope::ArtifactsRead),
1322 ("search_workspace_artifacts", Scope::ArtifactsRead),
1323 ("get_workspace_artifact", Scope::ArtifactsRead),
1324 ("get_workspace_artifact_content", Scope::ArtifactsRead),
1325 ("list_workspace_artifact_versions", Scope::ArtifactsRead),
1326 ("get_workspace_artifact_access", Scope::ArtifactsRead),
1327 ("list_workspace_artifact_templates", Scope::ArtifactsRead),
1328 ("list_workspace_artifact_spaces", Scope::ArtifactsRead),
1329 ("query_workspace_dataset", Scope::ArtifactsRead),
1330 ("create_workspace_artifact", Scope::ArtifactsWrite),
1331 ("update_workspace_artifact", Scope::ArtifactsWrite),
1332 ("edit_workspace_artifact", Scope::ArtifactsWrite),
1333 ("trash_workspace_artifact", Scope::ArtifactsWrite),
1334 ("restore_workspace_artifact", Scope::ArtifactsWrite),
1335 ("restore_workspace_artifact_version", Scope::ArtifactsWrite),
1336 ("set_workspace_artifact_access", Scope::ArtifactsAdmin),
1337 ("purge_workspace_artifact", Scope::ArtifactsAdmin),
1338];
1339
1340/// Operations any token may use: saying who it is.
1341pub const NO_SCOPE: &[&str] = &["whoami"];
1342
1343/// The scope `operation` needs. `None` for one in [`NO_SCOPE`]; an
1344/// operation in neither list needs full access.
1345pub fn scope_for(operation: &str) -> Option<Scope> {
1346 OPERATIONS
1347 .iter()
1348 .find(|(name, _)| *name == operation)
1349 .map(|(_, scope)| *scope)
1350}
1351
1352/// What a token needs for `operation` with this input beyond its own
1353/// scope: changing who has access, rerunning a workflow, and making a
1354/// repository public or private.
1355pub fn extra_scopes(operation: &str, input: &serde_json::Value) -> Vec<Scope> {
1356 let mut extra = Vec::new();
1357 // A workspace's base permission is who has access.
1358 if operation == "update_workspace" && input.get("base_permission").is_some_and(|v| !v.is_null()) {
1359 extra.push(Scope::AccessAdmin);
1360 }
1361 // Asking a g1t Actions job or run to run again reruns its workflow.
1362 if matches!(operation, "rerequest_check_run" | "rerequest_check_suite")
1363 && input["id"].as_str().is_some_and(|id| id.starts_with("job_") || id.starts_with("run_"))
1364 {
1365 extra.push(Scope::WorkflowsWrite);
1366 }
1367 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())) {
1368 extra.push(Scope::RepoAdmin);
1369 }
1370 extra
1371}
1372
1373/// The scopes a call needs, its own first.
1374pub fn needed(operation: &str, input: &serde_json::Value) -> Vec<Scope> {
1375 scope_for(operation)
1376 .into_iter()
1377 .chain(extra_scopes(operation, input))
1378 .collect()
1379}
1380
1381/// Whether `access` may use `operation` with `input`. The person's (or
1382/// workspace's) role is checked after this, by the service that owns what
1383/// was asked about.
1384pub fn decide(access: &TokenAccess, operation: &str, input: &serde_json::Value) -> Decision {
1385 let rule = if access.legacy { "token:legacy" } else { "token:scope" };
1386 // A workflow job may open or approve pull requests only where its
1387 // repository and workspace let it, as on GitHub.
1388 if let Some(job) = &access.job
1389 && !job.pull_requests
1390 && (operation == "create_pull_request" || (operation == "review_pull_request" && input["verdict"].as_str() == Some("approve")))
1391 {
1392 return Decision::deny(
1393 "token:pull-requests",
1394 "A workflow job cannot open or approve pull requests here: an admin can allow it under Settings, Actions.",
1395 );
1396 }
1397 if let Some(only) = access.repo.as_deref()
1398 && !NO_SCOPE.contains(&operation)
1399 {
1400 match input["repo"].as_str() {
1401 Some(repo) if access.reaches(repo) => {}
1402 Some(repo) => {
1403 return Decision::deny("token:repository", format!("{} {only}: it cannot reach {repo}.", one_repository(access)));
1404 }
1405 None => {
1406 return Decision::deny("token:repository", format!("{} {only}, and {operation} is not about one repository.", one_repository(access)));
1407 }
1408 }
1409 }
1410 // A token made for one workspace (or none) only reads outside it:
1411 // public repositories, as anyone may. Inside it, its repository
1412 // selection is checked with its owner's role (`access::granted`).
1413 if let Some(reach) = &access.reach
1414 && let Some(repo) = input["repo"].as_str()
1415 && !NO_SCOPE.contains(&operation)
1416 {
1417 let namespace = repo.split('/').next().unwrap_or_default();
1418 let changes = needed(operation, input).iter().any(|scope| scope.level() != Level::Read);
1419 if changes && !reach.owned_by(namespace) {
1420 let made_for = reach.workspace.as_deref().map_or_else(|| "your account only".to_owned(), |workspace| format!("the workspace {workspace}"));
1421 return Decision::deny(
1422 "token:resource-owner",
1423 format!("This access token is made for {made_for}: elsewhere it can only read public repositories, and {repo} is not in its reach."),
1424 );
1425 }
1426 }
1427 if access.scopes.is_some() {
1428 let known = NO_SCOPE.contains(&operation) || scope_for(operation).is_some();
1429 if !known {
1430 return Decision::deny("token:scope", format!("This access token cannot use {operation}: it needs full access."));
1431 }
1432 if let Some(missing) = needed(operation, input).into_iter().find(|scope| !access.allows(*scope)) {
1433 return Decision::deny(
1434 "token:scope",
1435 format!("This access token needs the {} scope to use {operation}.", missing.as_str()),
1436 );
1437 }
1438 }
1439 Decision::allow(rule)
1440}
1441
1442/// What a token held to one repository is, for saying why it was refused.
1443fn one_repository(access: &TokenAccess) -> &'static str {
1444 if access.job.is_some() { "This token is a workflow job's in" } else { "This token reaches only" }
1445}
1446
1447/// Whether a token may use the repository `owner/name` at all: a refusal
1448/// for a workflow job's token or a deploy key in another repository,
1449/// else `None`. Git and
1450/// the package registries ask this before [`decide_git`] and
1451/// [`decide_packages`].
1452pub fn decide_repo(access: &TokenAccess, repo: &str) -> Option<Decision> {
1453 let only = access.repo.as_deref()?;
1454 let why = if access.deploy_key.is_some() {
1455 format!("This deploy key is for {only}: it cannot reach {repo}.")
1456 } else {
1457 format!("{} {only}: it cannot reach {repo}.", one_repository(access))
1458 };
1459 (!access.reaches(repo)).then(|| Decision::deny("token:repository", why))
1460}
1461
1462/// Whether a token may clone or fetch (`write` false), or push to (`write`
1463/// true), a repository with git. `public` is whether anyone may read it,
1464/// which needs no scope.
1465pub fn decide_git(access: &TokenAccess, write: bool, public: bool) -> Decision {
1466 let needed = if write { Scope::CodeWrite } else { Scope::CodeRead };
1467 if !access.allows(needed) && (write || !public) {
1468 if access.deploy_key.is_some() {
1469 return Decision::deny(
1470 "token:scope",
1471 "This deploy key is read-only. An admin of the repository can add it again with write access to push with it.",
1472 );
1473 }
1474 return Decision::deny(
1475 "token:scope",
1476 format!("This access token needs the {} scope to {} with git.", needed.as_str(), if write { "push" } else { "clone or fetch a private repository" }),
1477 );
1478 }
1479 Decision::allow(if access.legacy { "token:legacy" } else { "token:scope" })
1480}
1481
1482/// Whether a token may pull (`Level::Read`), push or publish
1483/// (`Level::Write`), or delete (`Level::Delete`) packages. `public` is
1484/// whether anyone may pull the package, which needs no scope.
1485pub fn decide_packages(access: &TokenAccess, level: Level, public: bool) -> Decision {
1486 let (needed, doing) = match level {
1487 Level::Read => (Scope::PackagesRead, "pull a private package"),
1488 Level::Delete | Level::Admin => (Scope::PackagesDelete, "delete packages"),
1489 Level::Write | Level::Run => (Scope::PackagesWrite, "push or publish packages"),
1490 };
1491 if !access.allows(needed) && !(level == Level::Read && public) {
1492 return Decision::deny(
1493 "token:scope",
1494 format!("This access token needs the {} scope to {doing}.", needed.as_str()),
1495 );
1496 }
1497 Decision::allow(if access.legacy { "token:legacy" } else { "token:scope" })
1498}
1499
1500#[cfg(test)]
1501mod tests {
1502 use super::*;
1503 use serde_json::json;
1504
1505 fn token(scopes: &[Scope]) -> TokenAccess {
1506 TokenAccess {
1507 token_id: "tok_1".to_owned(),
1508 scopes: Some(scopes.iter().map(|scope| scope.as_str().to_owned()).collect()),
1509 legacy: false,
1510 name: None,
1511 ..TokenAccess::default()
1512 }
1513 }
1514
1515 #[test]
1516 fn every_scope_reads_back_and_belongs_to_a_resource() {
1517 for scope in Scope::ALL {
1518 assert_eq!(Scope::parse(scope.as_str()), Some(scope));
1519 assert!(scope.as_str().starts_with(scope.resource().as_str()));
1520 assert!(scope.includes(scope));
1521 }
1522 assert_eq!(Scope::parse(" Issues:Write "), Some(Scope::IssuesWrite));
1523 assert_eq!(Scope::parse("issues"), None);
1524 }
1525
1526 #[test]
1527 fn a_higher_level_includes_the_lower_ones_of_its_resource_only() {
1528 assert!(Scope::RepoAdmin.includes(Scope::RepoRead));
1529 assert!(Scope::RepoAdmin.includes(Scope::RepoWrite));
1530 assert!(Scope::IssuesWrite.includes(Scope::IssuesRead));
1531 assert!(!Scope::IssuesRead.includes(Scope::IssuesWrite));
1532 assert!(!Scope::RepoAdmin.includes(Scope::CodeWrite));
1533 assert!(!Scope::PullRequestsWrite.includes(Scope::IssuesWrite));
1534 }
1535
1536 #[test]
1537 fn operations_are_listed_once_and_never_also_free() {
1538 let mut seen = std::collections::HashSet::new();
1539 for (name, _) in OPERATIONS {
1540 assert!(seen.insert(*name), "{name} twice");
1541 assert!(!NO_SCOPE.contains(name), "{name}");
1542 }
1543 }
1544
1545 #[test]
1546 fn scopes_are_parsed_from_oauth_text_leaving_out_unknown_ones() {
1547 assert_eq!(
1548 parse_scopes("issues:write repo:read,bogus:thing issues:write"),
1549 vec![Scope::RepoRead, Scope::IssuesWrite]
1550 );
1551 assert_eq!(scopes_text(&[Scope::RepoRead, Scope::IssuesWrite]), "repo:read issues:write");
1552 }
1553
1554 #[test]
1555 fn the_oauth_default_is_the_agent_preset_and_never_admin() {
1556 let scopes = oauth_default();
1557 assert!(scopes.contains(&Scope::IssuesWrite));
1558 assert!(scopes.contains(&Scope::PullRequestsWrite));
1559 assert!(!scopes.contains(&Scope::AgentsRun));
1560 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{scopes:?}");
1561 for read in Scope::ALL.into_iter().filter(|scope| scope.level() == Level::Read && scope.offered()) {
1562 // Every read offered but the machines work runs on, and chat.
1563 assert_eq!(scopes.contains(&read), read != Scope::RunnersRead && read != Scope::ChatRead, "{read:?}");
1564 }
1565 assert!(Preset::ReadOnly.scopes().unwrap().iter().all(|scope| scope.level() == Level::Read));
1566 assert_eq!(Preset::Full.scopes(), None);
1567 }
1568
1569 #[test]
1570 fn retired_scopes_parse_but_are_never_granted() {
1571 // Stored tokens and OAuth grants that hold them still read.
1572 for text in ["agents:run", "memory:read", "memory:write", "models:read", "models:write"] {
1573 let scope = Scope::parse(text).unwrap();
1574 assert!(scope.resource().retired() && !scope.offered(), "{text}");
1575 let back: Scope = serde_json::from_value(json!(text)).unwrap();
1576 assert_eq!(back, scope);
1577 }
1578 // But nothing hands them out, and asking for them gets the rest.
1579 assert_eq!(parse_scopes("agents:run issues:read memory:write models:write"), vec![Scope::IssuesRead]);
1580 assert!(!offered_scopes().iter().any(|scope| scope.resource().retired()));
1581 assert!(!everything().iter().any(|scope| scope.resource().retired()));
1582 for preset in Preset::ALL {
1583 let scopes = preset.scopes().unwrap_or_default();
1584 assert!(!scopes.iter().any(|scope| scope.resource().retired()), "{}", preset.as_str());
1585 }
1586 // And no operation needs them.
1587 assert!(!OPERATIONS.iter().any(|(_, scope)| scope.resource().retired()));
1588 }
1589
1590 #[test]
1591 fn billing_is_read_by_presets_and_changed_by_none_but_full_access() {
1592 assert!(Preset::ReadOnly.scopes().unwrap().contains(&Scope::BillingRead));
1593 for preset in [Preset::ReadOnly, Preset::Agent, Preset::Ci] {
1594 assert!(!preset.scopes().unwrap().contains(&Scope::BillingWrite), "{}", preset.as_str());
1595 }
1596 assert_eq!(scope_for("set_budget"), Some(Scope::BillingWrite));
1597 assert_eq!(scope_for("get_usage"), Some(Scope::BillingRead));
1598 let reader = token(&[Scope::BillingRead]);
1599 assert!(decide(&reader, "list_invoices", &json!({})).allowed);
1600 assert!(decide(&reader, "set_budget", &json!({})).reason.unwrap().contains("billing:write"));
1601 }
1602
1603 #[test]
1604 fn artifacts_are_offered_read_by_presets_and_shared_only_with_admin() {
1605 for scope in [Scope::ArtifactsRead, Scope::ArtifactsWrite, Scope::ArtifactsAdmin] {
1606 assert_eq!(scope.resource(), Resource::Artifacts);
1607 assert!(scope.offered());
1608 assert!(offered_scopes().contains(&scope));
1609 assert_eq!(parse_scopes(scope.as_str()), vec![scope]);
1610 assert!(OPERATIONS.iter().any(|(_, needed)| *needed == scope), "{scope:?} gates nothing");
1611 }
1612 // Reading them is a read like any other; changing them is chosen.
1613 for preset in [Preset::ReadOnly, Preset::Agent] {
1614 let scopes = preset.scopes().unwrap();
1615 assert!(scopes.contains(&Scope::ArtifactsRead), "{}", preset.as_str());
1616 assert!(!scopes.contains(&Scope::ArtifactsWrite) && !scopes.contains(&Scope::ArtifactsAdmin), "{}", preset.as_str());
1617 }
1618 assert!(!Preset::Ci.scopes().unwrap().contains(&Scope::ArtifactsRead));
1619 assert!(everything().contains(&Scope::ArtifactsAdmin));
1620 assert!(Scope::ArtifactsAdmin.includes(Scope::ArtifactsWrite));
1621 assert!(Scope::ArtifactsAdmin.dangerous());
1622 assert!(!Scope::ArtifactsWrite.dangerous());
1623 assert_eq!(Resource::Artifacts.group(), ResourceGroup::Workspace);
1624 let asked = std::collections::BTreeMap::from([("artifacts".to_owned(), "write".to_owned())]);
1625 assert_eq!(resolve_permissions(&asked, true), Ok(vec![Scope::ArtifactsWrite]));
1626 assert!(offered_scopes().contains(&Scope::ArtifactsAdmin));
1627 // Sharing and deleting for good need admin; editing needs write.
1628 assert_eq!(scope_for("set_workspace_artifact_access"), Some(Scope::ArtifactsAdmin));
1629 assert_eq!(scope_for("purge_workspace_artifact"), Some(Scope::ArtifactsAdmin));
1630 assert_eq!(scope_for("edit_workspace_artifact"), Some(Scope::ArtifactsWrite));
1631 assert_eq!(scope_for("get_workspace_artifact_content"), Some(Scope::ArtifactsRead));
1632 let writer = token(&[Scope::ArtifactsWrite]);
1633 assert!(decide(&writer, "edit_workspace_artifact", &json!({})).allowed);
1634 assert!(decide(&writer, "list_workspace_artifacts", &json!({})).allowed, "write includes read");
1635 assert!(decide(&writer, "set_workspace_artifact_access", &json!({})).reason.unwrap().contains("artifacts:admin"));
1636 // Workflow runs' artifacts are another thing, with their own scope.
1637 let reader = token(&[Scope::ArtifactsRead]);
1638 assert!(!decide(&reader, "list_artifacts", &json!({ "repo": "acme/web" })).allowed);
1639 assert!(!decide(&token(&[Scope::WorkflowsRead]), "list_workspace_artifacts", &json!({})).allowed);
1640 }
1641
1642 #[test]
1643 fn chat_is_a_persons_own_and_given_only_when_asked_for() {
1644 for scope in [Scope::ChatRead, Scope::ChatWrite] {
1645 assert_eq!(scope.resource(), Resource::Chat);
1646 assert!(!scope.dangerous());
1647 assert_eq!(Scope::parse(scope.as_str()), Some(scope));
1648 }
1649 assert_eq!(Resource::Chat.label(), "Chat");
1650 assert_eq!(Resource::Chat.group(), ResourceGroup::Account);
1651 assert!(Scope::ChatWrite.includes(Scope::ChatRead));
1652 assert!(!Scope::ChatRead.includes(Scope::ChatWrite));
1653 // No preset, and so no OAuth default, gives it.
1654 for preset in Preset::ALL {
1655 let scopes = preset.scopes().unwrap_or_default();
1656 assert!(!scopes.iter().any(|scope| scope.resource() == Resource::Chat), "{}", preset.as_str());
1657 }
1658 assert!(!oauth_default().iter().any(|scope| scope.resource() == Resource::Chat));
1659 // An application that asks for it by name gets it; full access holds it.
1660 assert_eq!(parse_scopes("chat:read chat:write"), vec![Scope::ChatRead, Scope::ChatWrite]);
1661 assert!(offered_scopes().contains(&Scope::ChatWrite));
1662 assert!(everything().contains(&Scope::ChatWrite));
1663 assert!(TokenAccess::full().allows(Scope::ChatWrite));
1664 // Only a person's token may hold it.
1665 let asked = std::collections::BTreeMap::from([("chat".to_owned(), "write".to_owned())]);
1666 assert_eq!(resolve_permissions(&asked, true), Ok(vec![Scope::ChatWrite]));
1667 assert!(resolve_permissions(&asked, false).is_err());
1668 }
1669
1670 #[test]
1671 fn checks_are_reported_with_checks_write_which_ci_gets() {
1672 assert_eq!(scope_for("create_check_run"), Some(Scope::ChecksWrite));
1673 assert_eq!(scope_for("create_commit_status"), Some(Scope::ChecksWrite));
1674 assert_eq!(scope_for("list_check_runs_for_ref"), Some(Scope::ChecksRead));
1675 let ci = Preset::Ci.scopes().unwrap();
1676 assert!(ci.contains(&Scope::ChecksWrite));
1677 assert!(!Preset::Agent.scopes().unwrap().contains(&Scope::ChecksWrite));
1678 let reporter = token(&[Scope::ChecksWrite]);
1679 assert!(decide(&reporter, "update_check_run", &json!({ "id": "cr_1" })).allowed);
1680 assert!(decide(&reporter, "rerequest_check_run", &json!({ "id": "cr_1" })).allowed);
1681 // A g1t Actions job runs again as its workflow does.
1682 let refused = decide(&reporter, "rerequest_check_run", &json!({ "id": "job_1" }));
1683 assert!(refused.reason.unwrap().contains("workflows:write"));
1684 }
1685
1686 #[test]
1687 fn a_job_token_reaches_its_repository_only() {
1688 let job = TokenAccess {
1689 repo: Some("acme/web".into()),
1690 job: Some(JobToken { run_id: "run_1".into(), job_id: "job_1".into(), pull_requests: false }),
1691 ..token(&[Scope::RepoRead, Scope::IssuesWrite, Scope::IssuesRead, Scope::PullRequestsWrite])
1692 };
1693 assert!(decide(&job, "create_issue", &json!({ "repo": "acme/web" })).allowed);
1694 assert!(decide(&job, "create_issue", &json!({ "repo": "Acme/Web" })).allowed, "names compare without case");
1695 let elsewhere = decide(&job, "create_issue", &json!({ "repo": "acme/api" }));
1696 assert!(!elsewhere.allowed);
1697 assert_eq!(elsewhere.rule, "token:repository");
1698 // Nothing beyond the one repository, a workspace's listing included.
1699 assert!(!decide(&job, "list_repos", &json!({})).allowed);
1700 assert!(decide(&job, "whoami", &json!({})).allowed);
1701 // Its scopes still hold inside it.
1702 assert!(!decide(&job, "create_pull_request", &json!({ "repo": "acme/web" })).allowed);
1703 assert!(decide_repo(&job, "acme/web").is_none());
1704 assert!(!decide_repo(&job, "acme/api").unwrap().allowed);
1705 assert!(decide_repo(&token(&[Scope::CodeRead]), "acme/api").is_none(), "other tokens reach what their owner can");
1706 // Opening and approving pull requests is off unless allowed.
1707 assert_eq!(decide(&job, "create_pull_request", &json!({ "repo": "acme/web" })).rule, "token:pull-requests");
1708 assert!(!decide(&job, "review_pull_request", &json!({ "repo": "acme/web", "verdict": "approve" })).allowed);
1709 assert!(decide(&job, "review_pull_request", &json!({ "repo": "acme/web", "verdict": "request_changes" })).allowed);
1710 let allowed = TokenAccess { job: Some(JobToken { pull_requests: true, ..job.job.clone().unwrap() }), ..job.clone() };
1711 assert!(decide(&allowed, "create_pull_request", &json!({ "repo": "acme/web" })).allowed);
1712 }
1713
1714 #[test]
1715 fn workflow_files_need_their_own_scope() {
1716 for path in [".g1t/workflows/ci.yml", ".github/workflows/deploy.yaml", "/.github/workflows/x.yml", ".GitHub/Workflows/ci.yml", ".github/workflows"] {
1717 assert!(is_workflow_file(path), "{path}");
1718 }
1719 for path in ["README.md", ".github/CODEOWNERS", ".github/workflowsx/ci.yml", "docs/.github/workflows/ci.yml", ".g1t/actions/ci.yml"] {
1720 assert!(!is_workflow_file(path), "{path}");
1721 }
1722 let code = token(&[Scope::CodeWrite]);
1723 let refused = decide_workflow_files(Some(&code), ["README.md", ".github/workflows/ci.yml"]).unwrap();
1724 assert_eq!(refused.rule, "token:workflows");
1725 assert!(refused.reason.as_deref().unwrap().contains(".github/workflows/ci.yml"));
1726 assert!(refused.reason.as_deref().unwrap().contains("workflow_files:write"));
1727 assert!(decide_workflow_files(Some(&code), ["README.md"]).is_none());
1728 assert!(decide_workflow_files(Some(&token(&[Scope::CodeWrite, Scope::WorkflowFilesWrite])), [".g1t/workflows/ci.yml"]).is_none());
1729 assert!(decide_workflow_files(Some(&TokenAccess::full()), [".g1t/workflows/ci.yml"]).is_none(), "full access");
1730 assert!(decide_workflow_files(None, [".g1t/workflows/ci.yml"]).is_none(), "a signed-in person");
1731 // A job's token never may, as GITHUB_TOKEN never may.
1732 let job = TokenAccess { job: Some(JobToken::default()), ..TokenAccess::full() };
1733 assert!(decide_workflow_files(Some(&job), [".g1t/workflows/ci.yml"]).unwrap().reason.unwrap().contains("job"));
1734 // Nothing in a preset changes workflow files but full access.
1735 for preset in [Preset::ReadOnly, Preset::Agent, Preset::Ci] {
1736 assert!(!preset.scopes().unwrap().contains(&Scope::WorkflowFilesWrite), "{}", preset.as_str());
1737 }
1738 assert!(!Scope::WorkflowFilesWrite.includes(Scope::WorkflowsWrite) && !Scope::WorkflowsWrite.includes(Scope::WorkflowFilesWrite));
1739 }
1740
1741 #[test]
1742 fn a_narrowed_token_only_reads_outside_its_workspace() {
1743 let reach = TokenReach { workspace: Some("acme".into()), repositories: RepositorySelection::All, repo_ids: Vec::new() };
1744 let fine = TokenAccess { reach: Some(reach), ..token(&[Scope::RepoRead, Scope::IssuesRead, Scope::IssuesWrite]) };
1745 assert!(decide(&fine, "create_issue", &json!({ "repo": "acme/web" })).allowed);
1746 assert!(decide(&fine, "create_issue", &json!({ "repo": "Acme/web" })).allowed);
1747 let elsewhere = decide(&fine, "create_issue", &json!({ "repo": "globex/site" }));
1748 assert_eq!(elsewhere.rule, "token:resource-owner");
1749 assert!(elsewhere.reason.unwrap().contains("acme"));
1750 assert!(decide(&fine, "get_issue", &json!({ "repo": "globex/site" })).allowed, "public repositories elsewhere read");
1751 assert!(!decide(&fine, "create_pull_request", &json!({ "repo": "acme/web" })).allowed, "its scopes still hold");
1752 let mine = TokenAccess { reach: Some(TokenReach::default()), ..token(&[Scope::IssuesWrite]) };
1753 assert!(decide(&mine, "create_issue", &json!({ "repo": "acme/web" })).reason.unwrap().contains("your account"));
1754 assert!(fine.covers_repo("rep_1", "acme") && !fine.covers_repo("rep_1", "globex"));
1755 let selected = TokenReach { workspace: Some("acme".into()), repositories: RepositorySelection::Selected, repo_ids: vec!["rep_1".into()] };
1756 assert!(selected.covers("rep_1", "ACME") && !selected.covers("rep_2", "acme"));
1757 let public = TokenReach { repositories: RepositorySelection::Public, ..selected.clone() };
1758 assert!(!public.covers("rep_1", "acme") && public.owned_by("acme"));
1759 assert!(token(&[]).covers_repo("rep_1", "anything"), "a token for every workspace reaches what its owner can");
1760 assert_eq!(RepositorySelection::parse("public_only"), Some(RepositorySelection::Public));
1761 }
1762
1763 #[test]
1764 fn permissions_are_scopes_read_per_resource() {
1765 let asked: std::collections::BTreeMap<String, String> =
1766 [("issues", "write"), ("repo", "read"), ("code", "none"), ("packages", "delete")].iter().map(|(a, b)| ((*a).to_owned(), (*b).to_owned())).collect();
1767 let scopes = resolve_permissions(&asked, true).unwrap();
1768 assert_eq!(scopes, vec![Scope::RepoRead, Scope::PackagesDelete, Scope::IssuesWrite]);
1769 let back = permissions_of(&scopes);
1770 assert_eq!(back.get("issues").map(String::as_str), Some("write"));
1771 assert_eq!(back.get("packages").map(String::as_str), Some("delete"));
1772 assert!(!back.contains_key("code"));
1773 // Lower levels held beside a higher one say nothing more.
1774 assert_eq!(top_scopes(&[Scope::RepoRead, Scope::RepoAdmin, Scope::RepoWrite]), vec![Scope::RepoAdmin]);
1775 // Every offered resource's top, and nothing a level can lose.
1776 let all = everything();
1777 assert_eq!(all.len(), Resource::ALL.into_iter().filter(|resource| resource.offered()).count());
1778 for scope in offered_scopes() {
1779 assert!(all.iter().any(|held| held.includes(scope)), "{scope:?}");
1780 }
1781 }
1782
1783 #[test]
1784 fn permissions_are_checked_by_name_level_and_owner() {
1785 let one = |name: &str, level: &str| -> std::collections::BTreeMap<String, String> { [(name.to_owned(), level.to_owned())].into() };
1786 assert!(resolve_permissions(&one("wiki", "read"), true).unwrap_err().contains("wiki"));
1787 assert!(resolve_permissions(&one("issues", "admin"), true).unwrap_err().contains("read, write"));
1788 assert!(resolve_permissions(&one("workflow_files", "read"), true).is_err(), "workflow files are written only");
1789 assert!(resolve_permissions(&one("notifications", "read"), false).unwrap_err().contains("account"));
1790 assert_eq!(resolve_permissions(&one("notifications", "read"), true).unwrap(), vec![Scope::NotificationsRead]);
1791 assert!(resolve_permissions(&one("agents", "run"), false).unwrap_err().contains("agents"), "retired");
1792 assert!(resolve_permissions(&one("models", "read"), false).is_err(), "retired");
1793 for resource in Resource::ALL {
1794 assert_eq!(Resource::parse(resource.as_str()), Some(resource));
1795 assert!(!resource.scopes().is_empty());
1796 }
1797 }
1798
1799 #[test]
1800 fn a_legacy_token_can_do_everything() {
1801 let legacy = TokenAccess { legacy: true, ..TokenAccess::full() };
1802 for (operation, _) in OPERATIONS {
1803 assert!(decide(&legacy, operation, &json!({})).allowed, "{operation}");
1804 }
1805 assert_eq!(decide(&legacy, "delete_repo", &json!({})).rule, "token:legacy");
1806 }
1807
1808 #[test]
1809 fn a_missing_scope_is_named() {
1810 let read = token(&[Scope::IssuesRead]);
1811 assert!(decide(&read, "get_issue", &json!({})).allowed);
1812 assert!(decide(&read, "whoami", &json!({})).allowed);
1813 let refused = decide(&read, "create_issue", &json!({}));
1814 assert!(!refused.allowed);
1815 assert_eq!(refused.reason.as_deref(), Some("This access token needs the issues:write scope to use create_issue."));
1816 // An operation the table does not know needs full access.
1817 assert!(!decide(&read, "something_new", &json!({})).allowed);
1818 }
1819
1820 #[test]
1821 fn making_a_repository_public_or_private_needs_repo_admin() {
1822 let maintainer = token(&[Scope::RepoWrite]);
1823 assert!(decide(&maintainer, "update_repo", &json!({ "description": "x" })).allowed);
1824 assert!(!decide(&maintainer, "update_repo", &json!({ "private": true })).allowed);
1825 }
1826
1827 #[test]
1828 fn a_workspaces_base_permission_needs_access_admin_too() {
1829 let admin = token(&[Scope::WorkspaceAdmin]);
1830 assert!(decide(&admin, "update_workspace", &json!({ "name": "Acme" })).allowed);
1831 let refused = decide(&admin, "update_workspace", &json!({ "name": "Acme", "base_permission": "read" }));
1832 assert!(refused.reason.unwrap().contains("access:admin"));
1833 let both = token(&[Scope::WorkspaceAdmin, Scope::AccessAdmin]);
1834 assert!(decide(&both, "update_workspace", &json!({ "base_permission": "read" })).allowed);
1835 assert!(!decide(&token(&[Scope::WorkspaceRead]), "update_workspace", &json!({ "name": "Acme" })).allowed);
1836 }
1837
1838 #[test]
1839 fn git_push_needs_code_write_and_private_reads_need_code_read() {
1840 let reader = token(&[Scope::CodeRead]);
1841 assert!(decide_git(&reader, false, false).allowed);
1842 let refused = decide_git(&reader, true, false);
1843 assert!(!refused.allowed);
1844 assert!(refused.reason.unwrap().contains("code:write"));
1845 let issues = token(&[Scope::IssuesWrite]);
1846 assert!(!decide_git(&issues, false, false).allowed);
1847 assert!(decide_git(&issues, false, true).allowed, "public code needs no scope");
1848 assert!(!decide_git(&issues, true, true).allowed, "pushing to public code still needs code:write");
1849 let writer = token(&[Scope::CodeWrite]);
1850 assert!(decide_git(&writer, true, false).allowed);
1851 assert!(decide_git(&writer, false, false).allowed, "code:write includes code:read");
1852 assert!(decide_git(&TokenAccess::full(), true, false).allowed);
1853 }
1854
1855 #[test]
1856 fn packages_need_their_own_scopes_and_public_pulls_none() {
1857 let reader = token(&[Scope::PackagesRead]);
1858 assert!(decide_packages(&reader, Level::Read, false).allowed);
1859 assert!(!decide_packages(&reader, Level::Write, false).allowed);
1860 let code = token(&[Scope::CodeWrite]);
1861 assert!(!decide_packages(&code, Level::Read, false).allowed, "code scopes are not package scopes");
1862 assert!(decide_packages(&code, Level::Read, true).allowed, "public packages pull with any token");
1863 let writer = token(&[Scope::PackagesWrite]);
1864 assert!(decide_packages(&writer, Level::Write, false).allowed);
1865 assert!(decide_packages(&writer, Level::Read, false).allowed, "packages:write includes packages:read");
1866 let refused = decide_packages(&writer, Level::Delete, false);
1867 assert!(refused.reason.unwrap().contains("packages:delete"));
1868 assert!(decide_packages(&token(&[Scope::PackagesDelete]), Level::Write, false).allowed);
1869 assert!(Scope::PackagesDelete.dangerous());
1870 // Tokens made before these scopes, and full-access ones, keep working.
1871 let legacy = TokenAccess { legacy: true, ..TokenAccess::full() };
1872 assert!(decide_packages(&legacy, Level::Delete, false).allowed);
1873 assert!(decide_packages(&TokenAccess::full(), Level::Write, false).allowed);
1874 }
1875
1876 #[test]
1877 fn token_access_travels_as_json() {
1878 let access = token(&[Scope::IssuesRead]);
1879 let wire = serde_json::to_value(&access).unwrap();
1880 assert_eq!(wire["scopes"], json!(["issues:read"]));
1881 assert!(wire.get("resources").is_none());
1882 let back: TokenAccess = serde_json::from_value(wire).unwrap();
1883 assert_eq!(back, access);
1884 let full: TokenAccess = serde_json::from_value(json!({})).unwrap();
1885 assert!(full.is_full());
1886 // A reach written by an older version is ignored: a token reaches
1887 // whatever its owner can.
1888 let older: TokenAccess = serde_json::from_value(json!({
1889 "token_id": "tok_1",
1890 "scopes": ["issues:read"],
1891 "resources": { "kind": "repositories", "repositories": ["acme/rocket"] },
1892 }))
1893 .unwrap();
1894 assert_eq!(older, access);
1895 // Using the website is off unless set, and said only when on.
1896 assert!(!access.website);
1897 assert!(wire_of(&access).get("website").is_none());
1898 let website = TokenAccess { website: true, ..access };
1899 assert_eq!(wire_of(&website)["website"], json!(true));
1900 // Never part of full access.
1901 assert!(!TokenAccess::full().website);
1902 }
1903
1904 fn wire_of(access: &TokenAccess) -> serde_json::Value {
1905 serde_json::to_value(access).unwrap()
1906 }
1907
1908 /// The site's copy of the table, `packages/contracts/src/scopes.ts`,
1909 /// lists the same scopes in the same order, the same operations with
1910 /// the same scopes, and the same presets.
1911 #[test]
1912 fn the_typescript_mirror_has_the_same_table() {
1913 let ts = include_str!("../../../packages/contracts/src/scopes.ts");
1914 let section = |start: &str| {
1915 ts.split_once(start)
1916 .and_then(|(_, rest)| rest.split_once("] as const"))
1917 .map(|(table, _)| table)
1918 .unwrap_or_else(|| panic!("{start} in scopes.ts"))
1919 };
1920 let names = |table: &str| -> Vec<String> {
1921 section(table)
1922 .lines()
1923 .filter_map(|line| line.split_once("scope: \"").and_then(|(_, rest)| rest.split_once('"')).map(|(scope, _)| scope.to_owned()))
1924 .collect()
1925 };
1926 // Offered scopes in `SCOPES`, retired ones in `RETIRED_SCOPES`, the
1927 // rest in `UPCOMING_SCOPES`.
1928 let listed = |keep: fn(&Scope) -> bool| -> Vec<String> { Scope::ALL.iter().filter(|scope| keep(scope)).map(|scope| scope.as_str().to_owned()).collect() };
1929 assert_eq!(names("export const SCOPES = ["), listed(|scope| scope.offered()));
1930 assert_eq!(names("export const UPCOMING_SCOPES"), listed(|scope| !scope.offered() && !scope.resource().retired()));
1931 assert_eq!(names("export const RETIRED_SCOPES"), listed(|scope| scope.resource().retired()));
1932 let operations: Vec<(String, String)> = section("export const OPERATION_SCOPES = [")
1933 .lines()
1934 .filter_map(|line| {
1935 let mut quoted = line.split('"').skip(1).step_by(2);
1936 Some((quoted.next()?.to_owned(), quoted.next()?.to_owned()))
1937 })
1938 .collect();
1939 let expected: Vec<(String, String)> = OPERATIONS
1940 .iter()
1941 .map(|(name, scope)| ((*name).to_owned(), scope.as_str().to_owned()))
1942 .collect();
1943 assert_eq!(operations, expected);
1944 for preset in Preset::ALL {
1945 let list = section(&format!("{}: [", preset.as_str()));
1946 let mirrored: Vec<&str> = list
1947 .split(',')
1948 .map(|item| item.trim().trim_matches('"'))
1949 .filter(|item| !item.is_empty())
1950 .collect();
1951 let expected: Vec<&str> = preset
1952 .scopes()
1953 .map(|scopes| scopes.iter().map(|scope| scope.as_str()).collect())
1954 .unwrap_or_else(|| vec!["*"]);
1955 assert_eq!(mirrored, expected, "{}", preset.as_str());
1956 }
1957 // Each resource with its group, in the same order: offered ones in
1958 // `SCOPE_RESOURCES`, retired ones in `RETIRED_RESOURCES`, the rest in
1959 // `UPCOMING_RESOURCES`.
1960 let tables: [(&str, fn(Resource) -> bool); 3] = [
1961 ("export const SCOPE_RESOURCES", |resource| resource.offered()),
1962 ("export const UPCOMING_RESOURCES", |resource| !resource.offered() && !resource.retired()),
1963 ("export const RETIRED_RESOURCES", |resource| resource.retired()),
1964 ];
1965 for (table, keep) in tables {
1966 let resources = ts
1967 .split_once(table)
1968 .and_then(|(_, rest)| rest.split_once("
1969];"))
1970 .map(|(table, _)| table)
1971 .unwrap_or_else(|| panic!("{table} in scopes.ts"));
1972 let rows: Vec<&str> = resources.lines().filter(|line| line.trim_start().starts_with("{ resource:")).collect();
1973 let expected: Vec<Resource> = Resource::ALL.into_iter().filter(|resource| keep(*resource)).collect();
1974 assert_eq!(rows.len(), expected.len(), "{table}");
1975 for (row, resource) in rows.iter().zip(expected) {
1976 assert!(row.contains(&format!("resource: \"{}\"", resource.as_str())), "{row}");
1977 assert!(row.contains(&format!("group: \"{}\"", resource.group().as_str())), "{row}");
1978 }
1979 }
1980 }
1981}