Skip to content

g1t/crates/contracts/src/scopes.rs

1,148 lines49,620 bytesCodeBlame
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 Workspace,
28 Billing,
29 Repo,
30 Code,
31 Security,
32 Packages,
33 Issues,
34 PullRequests,
35 Agents,
36 Workflows,
37 Deployments,
38 Memory,
39 Access,
40 Webhooks,
41 Secrets,
42 Runners,
43 Models,
44}
45
46impl Resource {
47 pub const ALL: [Resource; 19] = [
48 Resource::Repo,
49 Resource::Code,
50 Resource::Security,
51 Resource::Packages,
52 Resource::Issues,
53 Resource::PullRequests,
54 Resource::Agents,
55 Resource::Workflows,
56 Resource::Deployments,
57 Resource::Memory,
58 Resource::Account,
59 Resource::Notifications,
60 Resource::Workspace,
61 Resource::Billing,
62 Resource::Access,
63 Resource::Webhooks,
64 Resource::Secrets,
65 Resource::Runners,
66 Resource::Models,
67 ];
68
69 pub fn as_str(self) -> &'static str {
70 match self {
71 Resource::Account => "account",
72 Resource::Notifications => "notifications",
73 Resource::Workspace => "workspace",
74 Resource::Billing => "billing",
75 Resource::Repo => "repo",
76 Resource::Code => "code",
77 Resource::Security => "security",
78 Resource::Packages => "packages",
79 Resource::Issues => "issues",
80 Resource::PullRequests => "pull_requests",
81 Resource::Agents => "agents",
82 Resource::Workflows => "workflows",
83 Resource::Deployments => "deployments",
84 Resource::Memory => "memory",
85 Resource::Access => "access",
86 Resource::Webhooks => "webhooks",
87 Resource::Secrets => "secrets",
88 Resource::Runners => "runners",
89 Resource::Models => "models",
90 }
91 }
92
93 /// Its name, for people.
94 pub fn label(self) -> &'static str {
95 match self {
96 Resource::Account => "Your account",
97 Resource::Notifications => "Notifications",
98 Resource::Workspace => "Workspaces",
99 Resource::Billing => "Billing",
100 Resource::Repo => "Repositories",
101 Resource::Code => "Code",
102 Resource::Security => "Security",
103 Resource::Packages => "Packages",
104 Resource::Issues => "Issues",
105 Resource::PullRequests => "Pull requests",
106 Resource::Agents => "g1t agents",
107 Resource::Workflows => "Workflows",
108 Resource::Deployments => "Deployments",
109 Resource::Memory => "Memory and context",
110 Resource::Access => "Who has access",
111 Resource::Webhooks => "Webhooks",
112 Resource::Secrets => "Secrets and variables",
113 Resource::Runners => "Self-hosted runners",
114 Resource::Models => "AI Gateway",
115 }
116 }
117}
118
119/// How much of a resource.
120#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
121pub enum Level {
122 Read,
123 Write,
124 /// Starting g1t's agents, which spends the workspace's money.
125 Run,
126 /// Deleting what cannot be brought back, such as a package's versions.
127 Delete,
128 Admin,
129}
130
131impl Level {
132 pub fn as_str(self) -> &'static str {
133 match self {
134 Level::Read => "read",
135 Level::Write => "write",
136 Level::Run => "run",
137 Level::Delete => "delete",
138 Level::Admin => "admin",
139 }
140 }
141}
142
143/// One scope. Its text form, `resource:level`, is what tokens store, OAuth
144/// clients ask for, and errors name.
145#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
146pub enum Scope {
147 RepoRead,
148 RepoWrite,
149 RepoAdmin,
150 CodeRead,
151 CodeWrite,
152 SecurityRead,
153 SecurityWrite,
154 PackagesRead,
155 PackagesWrite,
156 PackagesDelete,
157 IssuesRead,
158 IssuesWrite,
159 PullRequestsRead,
160 PullRequestsWrite,
161 AgentsRun,
162 WorkflowsRead,
163 WorkflowsWrite,
164 DeploymentsRead,
165 DeploymentsWrite,
166 MemoryRead,
167 MemoryWrite,
168 AccountRead,
169 AccountWrite,
170 NotificationsRead,
171 NotificationsWrite,
172 WorkspaceRead,
173 WorkspaceAdmin,
174 BillingRead,
175 BillingWrite,
176 AccessRead,
177 AccessAdmin,
178 WebhooksRead,
179 WebhooksAdmin,
180 SecretsRead,
181 SecretsAdmin,
182 RunnersRead,
183 RunnersAdmin,
184 ModelsRead,
185 ModelsWrite,
186}
187
188impl Scope {
189 /// Every scope, grouped by resource, least first.
190 pub const ALL: [Scope; 39] = [
191 Scope::RepoRead,
192 Scope::RepoWrite,
193 Scope::RepoAdmin,
194 Scope::CodeRead,
195 Scope::CodeWrite,
196 Scope::SecurityRead,
197 Scope::SecurityWrite,
198 Scope::PackagesRead,
199 Scope::PackagesWrite,
200 Scope::PackagesDelete,
201 Scope::IssuesRead,
202 Scope::IssuesWrite,
203 Scope::PullRequestsRead,
204 Scope::PullRequestsWrite,
205 Scope::AgentsRun,
206 Scope::WorkflowsRead,
207 Scope::WorkflowsWrite,
208 Scope::DeploymentsRead,
209 Scope::DeploymentsWrite,
210 Scope::MemoryRead,
211 Scope::MemoryWrite,
212 Scope::AccountRead,
213 Scope::AccountWrite,
214 Scope::NotificationsRead,
215 Scope::NotificationsWrite,
216 Scope::WorkspaceRead,
217 Scope::WorkspaceAdmin,
218 Scope::BillingRead,
219 Scope::BillingWrite,
220 Scope::AccessRead,
221 Scope::AccessAdmin,
222 Scope::WebhooksRead,
223 Scope::WebhooksAdmin,
224 Scope::SecretsRead,
225 Scope::SecretsAdmin,
226 Scope::RunnersRead,
227 Scope::RunnersAdmin,
228 Scope::ModelsRead,
229 Scope::ModelsWrite,
230 ];
231
232 pub fn as_str(self) -> &'static str {
233 match self {
234 Scope::RepoRead => "repo:read",
235 Scope::RepoWrite => "repo:write",
236 Scope::RepoAdmin => "repo:admin",
237 Scope::CodeRead => "code:read",
238 Scope::CodeWrite => "code:write",
239 Scope::SecurityRead => "security:read",
240 Scope::SecurityWrite => "security:write",
241 Scope::PackagesRead => "packages:read",
242 Scope::PackagesWrite => "packages:write",
243 Scope::PackagesDelete => "packages:delete",
244 Scope::IssuesRead => "issues:read",
245 Scope::IssuesWrite => "issues:write",
246 Scope::PullRequestsRead => "pull_requests:read",
247 Scope::PullRequestsWrite => "pull_requests:write",
248 Scope::AgentsRun => "agents:run",
249 Scope::WorkflowsRead => "workflows:read",
250 Scope::WorkflowsWrite => "workflows:write",
251 Scope::DeploymentsRead => "deployments:read",
252 Scope::DeploymentsWrite => "deployments:write",
253 Scope::MemoryRead => "memory:read",
254 Scope::MemoryWrite => "memory:write",
255 Scope::AccountRead => "account:read",
256 Scope::AccountWrite => "account:write",
257 Scope::NotificationsRead => "notifications:read",
258 Scope::NotificationsWrite => "notifications:write",
259 Scope::WorkspaceRead => "workspace:read",
260 Scope::WorkspaceAdmin => "workspace:admin",
261 Scope::BillingRead => "billing:read",
262 Scope::BillingWrite => "billing:write",
263 Scope::AccessRead => "access:read",
264 Scope::AccessAdmin => "access:admin",
265 Scope::WebhooksRead => "webhooks:read",
266 Scope::WebhooksAdmin => "webhooks:admin",
267 Scope::SecretsRead => "secrets:read",
268 Scope::SecretsAdmin => "secrets:admin",
269 Scope::RunnersRead => "runners:read",
270 Scope::RunnersAdmin => "runners:admin",
271 Scope::ModelsRead => "models:read",
272 Scope::ModelsWrite => "models:write",
273 }
274 }
275
276 pub fn parse(text: &str) -> Option<Scope> {
277 let text = text.trim().to_ascii_lowercase();
278 Scope::ALL.into_iter().find(|scope| scope.as_str() == text)
279 }
280
281 pub fn resource(self) -> Resource {
282 let name = self.as_str().split_once(':').map_or("", |(resource, _)| resource);
283 Resource::ALL
284 .into_iter()
285 .find(|resource| resource.as_str() == name)
286 .unwrap_or(Resource::Account)
287 }
288
289 pub fn level(self) -> Level {
290 match self.as_str().rsplit_once(':').map_or("", |(_, level)| level) {
291 "write" => Level::Write,
292 "run" => Level::Run,
293 "delete" => Level::Delete,
294 "admin" => Level::Admin,
295 _ => Level::Read,
296 }
297 }
298
299 /// Whether holding `self` gives `other`: the same resource, at the same
300 /// level or a lower one.
301 pub fn includes(self, other: Scope) -> bool {
302 self.resource() == other.resource() && self.level() >= other.level()
303 }
304
305 /// Changes that are hard or impossible to undo, or that decide who can
306 /// reach what. Shown behind a warning wherever scopes are chosen.
307 pub fn dangerous(self) -> bool {
308 matches!(self.level(), Level::Admin | Level::Delete)
309 }
310
311 /// What it lets a token do, in plain words.
312 pub fn describe(self) -> &'static str {
313 match self {
314 Scope::RepoRead => "See repositories, their settings, labels, timelines, releases, languages, contributors and security alerts, and search",
315 Scope::RepoWrite => "Create repositories, rename branches, change how pull requests merge and publish releases",
316 Scope::RepoAdmin => "Rename, archive, transfer, delete or change who can see a repository, change its rulesets, and dismiss security alerts",
317 Scope::CodeRead => "Clone and fetch private repositories with git",
318 Scope::CodeWrite => "Push commits with git",
319 Scope::SecurityRead => "See secret scanning, code scanning and vulnerability alerts, custom patterns, the dependency graph and SBOM, and security settings",
320 Scope::SecurityWrite => "Dismiss and reopen alerts, bypass push protection, review bypass requests, manage custom patterns, upload SARIF and change security settings",
321 Scope::PackagesRead => "Pull container images and install private packages",
322 Scope::PackagesWrite => "Push container images and publish packages",
323 Scope::PackagesDelete => "Delete packages and their versions",
324 Scope::IssuesRead => "Read issues, comments and plans",
325 Scope::IssuesWrite => "Open, edit, close and comment on issues",
326 Scope::PullRequestsRead => "Read pull requests, their changes, sessions and merge queues",
327 Scope::PullRequestsWrite => "Open, review, close and merge pull requests",
328 Scope::AgentsRun => "Put g1t agents to work and message them, which uses the workspace's money",
329 Scope::WorkflowsRead => "Read workflows, runs and logs",
330 Scope::WorkflowsWrite => "Run, cancel, rerun and turn workflows on or off",
331 Scope::DeploymentsRead => "See deployments, their statuses and environments",
332 Scope::DeploymentsWrite => "Report deployments and their statuses, from any CI",
333 Scope::MemoryRead => "Recall memory and search the workspace's context",
334 Scope::MemoryWrite => "Save memory for the next agent",
335 Scope::AccountRead => "Read your email addresses, invites, invitations, pinned projects and stars",
336 Scope::AccountWrite => "Change your email addresses, make invites, answer invitations, pin projects and star repositories",
337 Scope::NotificationsRead => "See your inbox, its threads, and what you subscribe to and watch",
338 Scope::NotificationsWrite => "Mark notifications read, done, saved or snoozed, subscribe to threads and watch repositories",
339 Scope::WorkspaceRead => "Read workspace settings, invites, integrations, model routes, teams and rulesets",
340 Scope::WorkspaceAdmin => "Create and delete workspaces, invite members, connect integrations, create, change and delete teams, and change the workspace's rulesets",
341 Scope::BillingRead => "See a workspace's usage, budget, AI credit and invoices",
342 Scope::BillingWrite => "Change a workspace's budget and buy AI credit",
343 Scope::AccessRead => "See who has access to repositories",
344 Scope::AccessAdmin => "Give and take away access to repositories, a team's included",
345 Scope::WebhooksRead => "See webhooks and their deliveries",
346 Scope::WebhooksAdmin => "Create, change and delete webhooks",
347 Scope::SecretsRead => "List secrets (never their values) and read variables",
348 Scope::SecretsAdmin => "Set and delete secrets and variables",
349 Scope::RunnersRead => "See self-hosted runners, their groups and where agents run",
350 Scope::RunnersAdmin => "Register and remove self-hosted runners, change their groups and settings",
351 Scope::ModelsRead => "See the workspace's AI Gateway requests: their models, tokens, cost and status",
352 Scope::ModelsWrite => "Send model requests through the AI Gateway, which uses the workspace's AI credit",
353 }
354 }
355}
356
357impl Serialize for Scope {
358 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
359 serializer.serialize_str(self.as_str())
360 }
361}
362
363impl<'de> Deserialize<'de> for Scope {
364 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
365 let text = String::deserialize(deserializer)?;
366 Scope::parse(&text).ok_or_else(|| serde::de::Error::custom(format!("unknown scope {text}")))
367 }
368}
369
370/// Scopes as written in a token's row or an OAuth request: separated by
371/// spaces or commas. Unknown names are left out, so a client asking for a
372/// scope from a newer version gets the rest.
373pub fn parse_scopes(text: &str) -> Vec<Scope> {
374 let mut scopes: Vec<Scope> = text
375 .split(|c: char| c.is_whitespace() || c == ',')
376 .filter_map(Scope::parse)
377 .collect();
378 normalize(&mut scopes);
379 scopes
380}
381
382/// In table order, without repeats.
383pub fn normalize(scopes: &mut Vec<Scope>) {
384 let given = std::mem::take(scopes);
385 scopes.extend(Scope::ALL.into_iter().filter(|scope| given.contains(scope)));
386}
387
388/// Space-separated, as stored and as OAuth writes them.
389pub fn scopes_text(scopes: &[Scope]) -> String {
390 scopes.iter().map(|scope| scope.as_str()).collect::<Vec<_>>().join(" ")
391}
392
393/// What a token stores for full access, which is not a scope a client can
394/// ask for by name.
395pub const FULL_ACCESS: &str = "*";
396
397/// Starting points for choosing scopes.
398#[derive(Clone, Copy, Debug, PartialEq, Eq)]
399pub enum Preset {
400 ReadOnly,
401 Agent,
402 Ci,
403 Full,
404}
405
406impl Preset {
407 pub const ALL: [Preset; 4] = [Preset::ReadOnly, Preset::Agent, Preset::Ci, Preset::Full];
408
409 pub fn as_str(self) -> &'static str {
410 match self {
411 Preset::ReadOnly => "read_only",
412 Preset::Agent => "agent",
413 Preset::Ci => "ci",
414 Preset::Full => "full",
415 }
416 }
417
418 pub fn label(self) -> &'static str {
419 match self {
420 Preset::ReadOnly => "Read only",
421 Preset::Agent => "Agent",
422 Preset::Ci => "CI",
423 Preset::Full => "Full access",
424 }
425 }
426
427 /// Its scopes; `None` for full access.
428 pub fn scopes(self) -> Option<Vec<Scope>> {
429 let reads = || Scope::ALL.into_iter().filter(|scope| scope.level() == Level::Read);
430 match self {
431 Preset::ReadOnly => Some(reads().collect()),
432 Preset::Agent => {
433 // Not the machines work runs on: an agent has no business
434 // knowing a workspace's own runners.
435 let mut scopes: Vec<Scope> = reads().filter(|scope| scope.resource() != Resource::Runners).collect();
436 // And answering what needs the person it works for: marking
437 // it done, subscribing, watching.
438 scopes.extend([
439 Scope::CodeWrite,
440 Scope::IssuesWrite,
441 Scope::PullRequestsWrite,
442 Scope::AgentsRun,
443 Scope::MemoryWrite,
444 Scope::NotificationsWrite,
445 ]);
446 normalize(&mut scopes);
447 Some(scopes)
448 }
449 Preset::Ci => Some(vec![
450 Scope::RepoRead,
451 Scope::CodeRead,
452 Scope::CodeWrite,
453 Scope::PackagesRead,
454 Scope::PackagesWrite,
455 Scope::WorkflowsRead,
456 Scope::WorkflowsWrite,
457 Scope::DeploymentsRead,
458 Scope::DeploymentsWrite,
459 ]),
460 Preset::Full => None,
461 }
462 }
463}
464
465/// What an OAuth client gets when it asks for nothing in particular: the
466/// agent preset. Never an admin scope.
467pub fn oauth_default() -> Vec<Scope> {
468 Preset::Agent.scopes().unwrap_or_default()
469}
470
471/// Set on a [`crate::User`] resolved from an access token: what the token
472/// may do. Absent on a signed-in session, which may do whatever its person
473/// can.
474#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
475pub struct TokenAccess {
476 /// The token's id, as audit entries and errors name it.
477 #[serde(default)]
478 pub token_id: String,
479 /// Its scopes, as `resource:level`. Absent: full access, everything the
480 /// person (or workspace) can do.
481 #[serde(default, skip_serializing_if = "Option::is_none")]
482 pub scopes: Option<Vec<String>>,
483 /// Made before tokens had scopes: full access until someone narrows it.
484 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
485 pub legacy: bool,
486 /// The token's name, as its owner gave it, so a log can say which
487 /// token made a request. Absent where whoever resolved it did not say.
488 #[serde(default, skip_serializing_if = "Option::is_none")]
489 pub name: Option<String>,
490}
491
492impl TokenAccess {
493 /// Full access to everything: the access tokens made before scopes had.
494 pub fn full() -> Self {
495 TokenAccess::default()
496 }
497
498 pub fn is_full(&self) -> bool {
499 self.scopes.is_none()
500 }
501
502 /// The scopes it holds, or `None` for full access.
503 pub fn granted(&self) -> Option<Vec<Scope>> {
504 self.scopes
505 .as_ref()
506 .map(|scopes| scopes.iter().filter_map(|scope| Scope::parse(scope)).collect())
507 }
508
509 pub fn allows(&self, needed: Scope) -> bool {
510 match self.granted() {
511 None => true,
512 Some(granted) => granted.iter().any(|held| held.includes(needed)),
513 }
514 }
515}
516
517/// Every operation of the API and MCP server, with the scope it needs. An
518/// operation in [`NO_SCOPE`] needs none. The API checks that every one of
519/// its operations is in exactly one of the two.
520pub const OPERATIONS: &[(&str, Scope)] = &[
521 // Your account.
522 ("list_emails", Scope::AccountRead),
523 ("add_email", Scope::AccountWrite),
524 ("remove_email", Scope::AccountWrite),
525 ("update_email_settings", Scope::AccountWrite),
526 ("list_invites", Scope::AccountRead),
527 ("create_invite", Scope::AccountWrite),
528 ("revoke_invite", Scope::AccountWrite),
529 ("list_my_repo_invitations", Scope::AccountRead),
530 ("accept_repo_invitation", Scope::AccountWrite),
531 ("decline_repo_invitation", Scope::AccountWrite),
532 // Your pinned projects: a preference of your account.
533 ("list_pinned_projects", Scope::AccountRead),
534 ("pin_project", Scope::AccountWrite),
535 // Your stars: a preference of your account.
536 ("list_starred", Scope::AccountRead),
537 ("check_starred", Scope::AccountRead),
538 ("star_repo", Scope::AccountWrite),
539 ("unstar_repo", Scope::AccountWrite),
540 ("unpin_project", Scope::AccountWrite),
541 ("reorder_pinned_projects", Scope::AccountWrite),
542 // Your inbox: notifications, subscriptions and watching.
543 ("list_notifications", Scope::NotificationsRead),
544 ("get_notification_thread", Scope::NotificationsRead),
545 ("get_thread_subscription", Scope::NotificationsRead),
546 ("get_repo_subscription", Scope::NotificationsRead),
547 ("list_watched_repos", Scope::NotificationsRead),
548 ("mark_notifications_read", Scope::NotificationsWrite),
549 ("mark_thread_read", Scope::NotificationsWrite),
550 ("mark_thread_done", Scope::NotificationsWrite),
551 ("save_thread", Scope::NotificationsWrite),
552 ("snooze_thread", Scope::NotificationsWrite),
553 ("set_thread_subscription", Scope::NotificationsWrite),
554 ("delete_thread_subscription", Scope::NotificationsWrite),
555 ("set_repo_subscription", Scope::NotificationsWrite),
556 ("delete_repo_subscription", Scope::NotificationsWrite),
557 // Workspaces, their invites and integrations.
558 ("create_workspace", Scope::WorkspaceAdmin),
559 ("delete_workspace", Scope::WorkspaceAdmin),
560 ("get_workspace", Scope::WorkspaceRead),
561 ("update_workspace", Scope::WorkspaceAdmin),
562 ("list_workspace_invites", Scope::WorkspaceRead),
563 ("invite_member", Scope::WorkspaceAdmin),
564 ("revoke_workspace_invite", Scope::WorkspaceAdmin),
565 ("list_integrations", Scope::WorkspaceRead),
566 ("connect_integration", Scope::WorkspaceAdmin),
567 ("disconnect_integration", Scope::WorkspaceAdmin),
568 ("test_integration", Scope::WorkspaceAdmin),
569 ("get_model_routes", Scope::WorkspaceRead),
570 ("set_model_routes", Scope::WorkspaceAdmin),
571 // Teams: reading them, and managing them. A team's role on a
572 // repository is who has access.
573 ("list_teams", Scope::WorkspaceRead),
574 ("get_team", Scope::WorkspaceRead),
575 ("list_team_members", Scope::WorkspaceRead),
576 ("list_child_teams", Scope::WorkspaceRead),
577 ("list_team_repos", Scope::WorkspaceRead),
578 ("list_user_teams", Scope::WorkspaceRead),
579 ("create_team", Scope::WorkspaceAdmin),
580 ("list_workspace_rulesets", Scope::WorkspaceRead),
581 ("get_workspace_ruleset", Scope::WorkspaceRead),
582 ("list_workspace_rule_evaluations", Scope::WorkspaceRead),
583 ("create_workspace_ruleset", Scope::WorkspaceAdmin),
584 ("update_workspace_ruleset", Scope::WorkspaceAdmin),
585 ("delete_workspace_ruleset", Scope::WorkspaceAdmin),
586 ("update_team", Scope::WorkspaceAdmin),
587 ("delete_team", Scope::WorkspaceAdmin),
588 ("set_team_member", Scope::WorkspaceAdmin),
589 ("remove_team_member", Scope::WorkspaceAdmin),
590 ("set_team_review_assignment", Scope::WorkspaceAdmin),
591 // A workspace's billing: usage, budget, AI credit and invoices.
592 ("get_usage", Scope::BillingRead),
593 ("get_budget", Scope::BillingRead),
594 ("get_ai_credit", Scope::BillingRead),
595 ("list_invoices", Scope::BillingRead),
596 ("get_billing_details", Scope::BillingRead),
597 ("set_budget", Scope::BillingWrite),
598 ("buy_ai_credit", Scope::BillingWrite),
599 // Repositories.
600 ("list_repos", Scope::RepoRead),
601 ("get_repo", Scope::RepoRead),
602 // Projects follow their repositories.
603 ("list_projects", Scope::RepoRead),
604 ("get_project", Scope::RepoRead),
605 ("search", Scope::RepoRead),
606 ("list_events", Scope::RepoRead),
607 // What the default branch says about a repository, who starred it, and
608 // its releases.
609 ("get_languages", Scope::RepoRead),
610 ("list_contributors", Scope::RepoRead),
611 ("get_license", Scope::RepoRead),
612 ("list_stargazers", Scope::RepoRead),
613 ("list_releases", Scope::RepoRead),
614 ("get_latest_release", Scope::RepoRead),
615 ("get_release_by_tag", Scope::RepoRead),
616 ("get_release", Scope::RepoRead),
617 ("create_release", Scope::RepoWrite),
618 ("update_release", Scope::RepoWrite),
619 ("delete_release", Scope::RepoWrite),
620 ("list_labels", Scope::RepoRead),
621 ("list_milestones", Scope::RepoRead),
622 ("get_milestone", Scope::RepoRead),
623 ("create_label", Scope::IssuesWrite),
624 ("update_label", Scope::IssuesWrite),
625 ("delete_label", Scope::IssuesWrite),
626 ("add_default_labels", Scope::IssuesWrite),
627 ("create_milestone", Scope::IssuesWrite),
628 ("update_milestone", Scope::IssuesWrite),
629 ("delete_milestone", Scope::IssuesWrite),
630 ("get_repo_settings", Scope::RepoRead),
631 ("list_check_names", Scope::RepoRead),
632 ("list_deleted_repos", Scope::RepoRead),
633 ("list_security_alerts", Scope::RepoRead),
634 ("get_codeowners_errors", Scope::RepoRead),
635 ("create_repo", Scope::RepoWrite),
636 ("update_repo", Scope::RepoWrite),
637 ("update_project", Scope::RepoWrite),
638 ("update_repo_settings", Scope::RepoWrite),
639 // Rulesets: reading them is reading the repository; changing them
640 // changes what everyone, agents included, may do, so it is admin.
641 ("list_repo_rulesets", Scope::RepoRead),
642 ("get_repo_ruleset", Scope::RepoRead),
643 ("get_branch_rules", Scope::RepoRead),
644 ("list_rule_evaluations", Scope::RepoRead),
645 ("create_repo_ruleset", Scope::RepoAdmin),
646 ("update_repo_ruleset", Scope::RepoAdmin),
647 ("delete_repo_ruleset", Scope::RepoAdmin),
648 ("rename_branch", Scope::RepoWrite),
649 ("rename_repo", Scope::RepoAdmin),
650 ("transfer_repo", Scope::RepoAdmin),
651 ("archive_repo", Scope::RepoAdmin),
652 ("unarchive_repo", Scope::RepoAdmin),
653 ("set_repo_visibility", Scope::RepoAdmin),
654 ("delete_repo", Scope::RepoAdmin),
655 ("restore_repo", Scope::RepoAdmin),
656 ("purge_repo", Scope::RepoAdmin),
657 // A dismissed secret is let through push protection.
658 ("dismiss_security_alert", Scope::RepoAdmin),
659 ("reopen_security_alert", Scope::RepoAdmin),
660 // The security suite: alerts, push protection, patterns, code
661 // scanning, the supply chain and settings.
662 ("list_secret_scanning_alerts", Scope::SecurityRead),
663 ("get_secret_scanning_alert", Scope::SecurityRead),
664 ("list_secret_scanning_locations", Scope::SecurityRead),
665 ("list_bypass_requests", Scope::SecurityRead),
666 ("list_custom_patterns", Scope::SecurityRead),
667 ("list_code_scanning_alerts", Scope::SecurityRead),
668 ("get_code_scanning_alert", Scope::SecurityRead),
669 ("list_code_scanning_analyses", Scope::SecurityRead),
670 ("get_sarif_upload", Scope::SecurityRead),
671 ("list_vulnerability_alerts", Scope::SecurityRead),
672 ("get_vulnerability_alert", Scope::SecurityRead),
673 ("get_dependency_graph", Scope::SecurityRead),
674 ("get_sbom", Scope::SecurityRead),
675 ("compare_dependencies", Scope::SecurityRead),
676 ("get_security_settings", Scope::SecurityRead),
677 ("get_workspace_security_settings", Scope::SecurityRead),
678 ("get_security_overview", Scope::SecurityRead),
679 ("update_secret_scanning_alert", Scope::SecurityWrite),
680 ("bypass_push_protection", Scope::SecurityWrite),
681 ("check_secret_validity", Scope::SecurityWrite),
682 ("review_bypass_request", Scope::SecurityWrite),
683 ("create_custom_pattern", Scope::SecurityWrite),
684 ("update_custom_pattern", Scope::SecurityWrite),
685 ("delete_custom_pattern", Scope::SecurityWrite),
686 ("dry_run_custom_pattern", Scope::SecurityWrite),
687 ("update_code_scanning_alert", Scope::SecurityWrite),
688 ("upload_sarif", Scope::SecurityWrite),
689 ("update_vulnerability_alert", Scope::SecurityWrite),
690 ("fix_security_alert", Scope::SecurityWrite),
691 ("update_security_settings", Scope::SecurityWrite),
692 ("update_workspace_security_settings", Scope::SecurityWrite),
693 // Issues and plans.
694 ("list_issues", Scope::IssuesRead),
695 ("get_issue", Scope::IssuesRead),
696 ("get_plan", Scope::IssuesRead),
697 ("create_issue", Scope::IssuesWrite),
698 ("update_issue", Scope::IssuesWrite),
699 ("list_issue_labels", Scope::IssuesRead),
700 ("add_issue_labels", Scope::IssuesWrite),
701 ("set_issue_labels", Scope::IssuesWrite),
702 ("remove_issue_labels", Scope::IssuesWrite),
703 ("close_issue", Scope::IssuesWrite),
704 ("reopen_issue", Scope::IssuesWrite),
705 ("add_comment", Scope::IssuesWrite),
706 ("import_issue", Scope::IssuesWrite),
707 ("apply_plan", Scope::IssuesWrite),
708 // Pull requests.
709 ("list_pull_requests", Scope::PullRequestsRead),
710 ("get_pull_request", Scope::PullRequestsRead),
711 ("get_pull_request_changes", Scope::PullRequestsRead),
712 ("read_session", Scope::PullRequestsRead),
713 ("get_merge_queue", Scope::PullRequestsRead),
714 ("create_pull_request", Scope::PullRequestsWrite),
715 ("update_pull_request", Scope::PullRequestsWrite),
716 ("record_session", Scope::PullRequestsWrite),
717 ("mark_pull_request_ready", Scope::PullRequestsWrite),
718 ("close_pull_request", Scope::PullRequestsWrite),
719 ("review_pull_request", Scope::PullRequestsWrite),
720 ("merge_pull_request", Scope::PullRequestsWrite),
721 ("request_reviewers", Scope::PullRequestsWrite),
722 ("remove_requested_reviewers", Scope::PullRequestsWrite),
723 // g1t's agents.
724 ("assign_issue", Scope::AgentsRun),
725 ("delegate", Scope::AgentsRun),
726 ("plan_work", Scope::AgentsRun),
727 ("message_agent", Scope::AgentsRun),
728 ("answer_message", Scope::AgentsRun),
729 ("take_messages", Scope::AgentsRun),
730 // Workflows.
731 ("list_workflows", Scope::WorkflowsRead),
732 ("list_workflow_runs", Scope::WorkflowsRead),
733 ("get_workflow_run", Scope::WorkflowsRead),
734 ("get_job_logs", Scope::WorkflowsRead),
735 ("dispatch_workflow", Scope::WorkflowsWrite),
736 ("cancel_workflow_run", Scope::WorkflowsWrite),
737 ("rerun_workflow_run", Scope::WorkflowsWrite),
738 ("update_workflow", Scope::WorkflowsWrite),
739 // Deployments, wherever they run: reading them, and reporting them.
740 ("list_deployments", Scope::DeploymentsRead),
741 ("get_deployment", Scope::DeploymentsRead),
742 ("list_deployment_statuses", Scope::DeploymentsRead),
743 ("list_environments", Scope::DeploymentsRead),
744 ("get_environment", Scope::DeploymentsRead),
745 ("create_deployment", Scope::DeploymentsWrite),
746 ("create_deployment_status", Scope::DeploymentsWrite),
747 // Memory and the context hub.
748 ("recall", Scope::MemoryRead),
749 ("search_context", Scope::MemoryRead),
750 ("get_entity", Scope::MemoryRead),
751 ("get_context", Scope::MemoryRead),
752 ("remember", Scope::MemoryWrite),
753 // Who has access.
754 ("list_collaborators", Scope::AccessRead),
755 ("get_collaborator_permission", Scope::AccessRead),
756 ("list_repo_invitations", Scope::AccessRead),
757 ("list_outside_collaborators", Scope::AccessRead),
758 ("add_collaborator", Scope::AccessAdmin),
759 ("update_collaborator", Scope::AccessAdmin),
760 ("remove_collaborator", Scope::AccessAdmin),
761 ("revoke_repo_invitation", Scope::AccessAdmin),
762 ("set_base_permission", Scope::AccessAdmin),
763 ("set_team_repo", Scope::AccessAdmin),
764 ("remove_team_repo", Scope::AccessAdmin),
765 // Webhooks.
766 ("list_webhooks", Scope::WebhooksRead),
767 ("list_webhook_deliveries", Scope::WebhooksRead),
768 ("create_webhook", Scope::WebhooksAdmin),
769 ("update_webhook", Scope::WebhooksAdmin),
770 ("delete_webhook", Scope::WebhooksAdmin),
771 ("ping_webhook", Scope::WebhooksAdmin),
772 ("redeliver_webhook", Scope::WebhooksAdmin),
773 // Secrets and variables.
774 ("list_actions_secrets", Scope::SecretsRead),
775 ("list_actions_variables", Scope::SecretsRead),
776 ("set_actions_secret", Scope::SecretsAdmin),
777 ("delete_actions_secret", Scope::SecretsAdmin),
778 ("set_actions_variable", Scope::SecretsAdmin),
779 ("delete_actions_variable", Scope::SecretsAdmin),
780 // Self-hosted runners.
781 ("list_runners", Scope::RunnersRead),
782 ("list_runner_groups", Scope::RunnersRead),
783 ("get_runner_settings", Scope::RunnersRead),
784 ("create_runner_registration_token", Scope::RunnersAdmin),
785 ("remove_runner", Scope::RunnersAdmin),
786 ("create_runner_group", Scope::RunnersAdmin),
787 ("update_runner_group", Scope::RunnersAdmin),
788 ("delete_runner_group", Scope::RunnersAdmin),
789 ("update_runner_settings", Scope::RunnersAdmin),
790 // The AI Gateway. Sending a request to a model needs `models:write`,
791 // checked by the model proxy at models.g1t.sh, not here.
792 ("list_gateway_requests", Scope::ModelsRead),
793];
794
795/// Operations any token may use: saying who it is.
796pub const NO_SCOPE: &[&str] = &["whoami"];
797
798/// The scope `operation` needs. `None` for one in [`NO_SCOPE`]; an
799/// operation in neither list needs full access.
800pub fn scope_for(operation: &str) -> Option<Scope> {
801 OPERATIONS
802 .iter()
803 .find(|(name, _)| *name == operation)
804 .map(|(_, scope)| *scope)
805}
806
807/// What a token needs for `operation` with this input beyond its own
808/// scope: starting agents from an operation that can, and making a
809/// repository public or private.
810pub fn extra_scopes(operation: &str, input: &serde_json::Value) -> Vec<Scope> {
811 let mut extra = Vec::new();
812 let assigns = input["assign"].as_bool() == Some(true)
813 || input["agent"].as_bool() == Some(true)
814 || input["assign_agent"].as_bool() == Some(true);
815 if assigns && matches!(operation, "apply_plan" | "import_issue" | "create_issue") {
816 extra.push(Scope::AgentsRun);
817 }
818 // Fixing an alert opens an issue and puts g1t on it.
819 if operation == "fix_security_alert" {
820 extra.extend([Scope::IssuesWrite, Scope::AgentsRun]);
821 }
822 // Opening the issue an agent is put on.
823 if operation == "delegate" {
824 extra.push(Scope::IssuesWrite);
825 }
826 // A workspace's base permission is who has access.
827 if operation == "update_workspace" && input.get("base_permission").is_some_and(|v| !v.is_null()) {
828 extra.push(Scope::AccessAdmin);
829 }
830 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())) {
831 extra.push(Scope::RepoAdmin);
832 }
833 extra
834}
835
836/// The scopes a call needs, its own first.
837pub fn needed(operation: &str, input: &serde_json::Value) -> Vec<Scope> {
838 scope_for(operation)
839 .into_iter()
840 .chain(extra_scopes(operation, input))
841 .collect()
842}
843
844/// Whether `access` may use `operation` with `input`. The person's (or
845/// workspace's) role is checked after this, by the service that owns what
846/// was asked about.
847pub fn decide(access: &TokenAccess, operation: &str, input: &serde_json::Value) -> Decision {
848 let rule = if access.legacy { "token:legacy" } else { "token:scope" };
849 if access.scopes.is_some() {
850 let known = NO_SCOPE.contains(&operation) || scope_for(operation).is_some();
851 if !known {
852 return Decision::deny("token:scope", format!("This access token cannot use {operation}: it needs full access."));
853 }
854 if let Some(missing) = needed(operation, input).into_iter().find(|scope| !access.allows(*scope)) {
855 return Decision::deny(
856 "token:scope",
857 format!("This access token needs the {} scope to use {operation}.", missing.as_str()),
858 );
859 }
860 }
861 Decision::allow(rule)
862}
863
864/// Whether a token may clone or fetch (`write` false), or push to (`write`
865/// true), a repository with git. `public` is whether anyone may read it,
866/// which needs no scope.
867pub fn decide_git(access: &TokenAccess, write: bool, public: bool) -> Decision {
868 let needed = if write { Scope::CodeWrite } else { Scope::CodeRead };
869 if !access.allows(needed) && (write || !public) {
870 return Decision::deny(
871 "token:scope",
872 format!("This access token needs the {} scope to {} with git.", needed.as_str(), if write { "push" } else { "clone or fetch a private repository" }),
873 );
874 }
875 Decision::allow(if access.legacy { "token:legacy" } else { "token:scope" })
876}
877
878/// Whether a token may pull (`Level::Read`), push or publish
879/// (`Level::Write`), or delete (`Level::Delete`) packages. `public` is
880/// whether anyone may pull the package, which needs no scope.
881pub fn decide_packages(access: &TokenAccess, level: Level, public: bool) -> Decision {
882 let (needed, doing) = match level {
883 Level::Read => (Scope::PackagesRead, "pull a private package"),
884 Level::Delete | Level::Admin => (Scope::PackagesDelete, "delete packages"),
885 Level::Write | Level::Run => (Scope::PackagesWrite, "push or publish packages"),
886 };
887 if !access.allows(needed) && !(level == Level::Read && public) {
888 return Decision::deny(
889 "token:scope",
890 format!("This access token needs the {} scope to {doing}.", needed.as_str()),
891 );
892 }
893 Decision::allow(if access.legacy { "token:legacy" } else { "token:scope" })
894}
895
896#[cfg(test)]
897mod tests {
898 use super::*;
899 use serde_json::json;
900
901 fn token(scopes: &[Scope]) -> TokenAccess {
902 TokenAccess {
903 token_id: "tok_1".to_owned(),
904 scopes: Some(scopes.iter().map(|scope| scope.as_str().to_owned()).collect()),
905 legacy: false,
906 name: None,
907 }
908 }
909
910 #[test]
911 fn every_scope_reads_back_and_belongs_to_a_resource() {
912 for scope in Scope::ALL {
913 assert_eq!(Scope::parse(scope.as_str()), Some(scope));
914 assert!(scope.as_str().starts_with(scope.resource().as_str()));
915 assert!(scope.includes(scope));
916 }
917 assert_eq!(Scope::parse(" Issues:Write "), Some(Scope::IssuesWrite));
918 assert_eq!(Scope::parse("issues"), None);
919 }
920
921 #[test]
922 fn a_higher_level_includes_the_lower_ones_of_its_resource_only() {
923 assert!(Scope::RepoAdmin.includes(Scope::RepoRead));
924 assert!(Scope::RepoAdmin.includes(Scope::RepoWrite));
925 assert!(Scope::IssuesWrite.includes(Scope::IssuesRead));
926 assert!(!Scope::IssuesRead.includes(Scope::IssuesWrite));
927 assert!(!Scope::RepoAdmin.includes(Scope::CodeWrite));
928 assert!(!Scope::PullRequestsWrite.includes(Scope::IssuesWrite));
929 }
930
931 #[test]
932 fn operations_are_listed_once_and_never_also_free() {
933 let mut seen = std::collections::HashSet::new();
934 for (name, _) in OPERATIONS {
935 assert!(seen.insert(*name), "{name} twice");
936 assert!(!NO_SCOPE.contains(name), "{name}");
937 }
938 }
939
940 #[test]
941 fn scopes_are_parsed_from_oauth_text_leaving_out_unknown_ones() {
942 assert_eq!(
943 parse_scopes("issues:write repo:read,bogus:thing issues:write"),
944 vec![Scope::RepoRead, Scope::IssuesWrite]
945 );
946 assert_eq!(scopes_text(&[Scope::RepoRead, Scope::IssuesWrite]), "repo:read issues:write");
947 }
948
949 #[test]
950 fn the_oauth_default_is_the_agent_preset_and_never_admin() {
951 let scopes = oauth_default();
952 assert!(scopes.contains(&Scope::IssuesWrite));
953 assert!(scopes.contains(&Scope::PullRequestsWrite));
954 assert!(scopes.contains(&Scope::AgentsRun));
955 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{scopes:?}");
956 for read in Scope::ALL.into_iter().filter(|scope| scope.level() == Level::Read) {
957 // Every read but the machines work runs on.
958 assert_eq!(scopes.contains(&read), read != Scope::RunnersRead, "{read:?}");
959 }
960 assert!(Preset::ReadOnly.scopes().unwrap().iter().all(|scope| scope.level() == Level::Read));
961 assert_eq!(Preset::Full.scopes(), None);
962 }
963
964 #[test]
965 fn billing_is_read_by_presets_and_changed_by_none_but_full_access() {
966 assert!(Preset::ReadOnly.scopes().unwrap().contains(&Scope::BillingRead));
967 for preset in [Preset::ReadOnly, Preset::Agent, Preset::Ci] {
968 assert!(!preset.scopes().unwrap().contains(&Scope::BillingWrite), "{}", preset.as_str());
969 }
970 assert_eq!(scope_for("set_budget"), Some(Scope::BillingWrite));
971 assert_eq!(scope_for("buy_ai_credit"), Some(Scope::BillingWrite));
972 assert_eq!(scope_for("get_usage"), Some(Scope::BillingRead));
973 let reader = token(&[Scope::BillingRead]);
974 assert!(decide(&reader, "list_invoices", &json!({})).allowed);
975 assert!(decide(&reader, "set_budget", &json!({})).reason.unwrap().contains("billing:write"));
976 }
977
978 #[test]
979 fn the_ai_gateway_spends_only_with_models_write_which_no_preset_gives() {
980 // Reading the log is a read like any other.
981 assert_eq!(scope_for("list_gateway_requests"), Some(Scope::ModelsRead));
982 assert!(Preset::ReadOnly.scopes().unwrap().contains(&Scope::ModelsRead));
983 // Sending requests spends the workspace's AI credit: chosen on purpose.
984 for preset in [Preset::ReadOnly, Preset::Agent, Preset::Ci] {
985 assert!(!preset.scopes().unwrap().contains(&Scope::ModelsWrite), "{}", preset.as_str());
986 }
987 assert!(Scope::ModelsWrite.includes(Scope::ModelsRead));
988 assert!(!Scope::ModelsWrite.dangerous());
989 assert!(token(&[Scope::ModelsWrite]).allows(Scope::ModelsWrite));
990 assert!(!token(&[Scope::BillingWrite]).allows(Scope::ModelsWrite));
991 assert!(TokenAccess::full().allows(Scope::ModelsWrite));
992 }
993
994 #[test]
995 fn a_legacy_token_can_do_everything() {
996 let legacy = TokenAccess { legacy: true, ..TokenAccess::full() };
997 for (operation, _) in OPERATIONS {
998 assert!(decide(&legacy, operation, &json!({})).allowed, "{operation}");
999 }
1000 assert_eq!(decide(&legacy, "delete_repo", &json!({})).rule, "token:legacy");
1001 }
1002
1003 #[test]
1004 fn a_missing_scope_is_named() {
1005 let read = token(&[Scope::IssuesRead]);
1006 assert!(decide(&read, "get_issue", &json!({})).allowed);
1007 assert!(decide(&read, "whoami", &json!({})).allowed);
1008 let refused = decide(&read, "create_issue", &json!({}));
1009 assert!(!refused.allowed);
1010 assert_eq!(refused.reason.as_deref(), Some("This access token needs the issues:write scope to use create_issue."));
1011 // An operation the table does not know needs full access.
1012 assert!(!decide(&read, "something_new", &json!({})).allowed);
1013 }
1014
1015 #[test]
1016 fn starting_agents_from_another_operation_needs_agents_run() {
1017 let writer = token(&[Scope::IssuesWrite]);
1018 assert!(decide(&writer, "apply_plan", &json!({})).allowed);
1019 let refused = decide(&writer, "apply_plan", &json!({ "assign": true }));
1020 assert!(refused.reason.unwrap().contains("agents:run"));
1021 let maintainer = token(&[Scope::RepoWrite]);
1022 assert!(decide(&maintainer, "update_repo", &json!({ "description": "x" })).allowed);
1023 assert!(!decide(&maintainer, "update_repo", &json!({ "private": true })).allowed);
1024 }
1025
1026 #[test]
1027 fn a_workspaces_base_permission_needs_access_admin_too() {
1028 let admin = token(&[Scope::WorkspaceAdmin]);
1029 assert!(decide(&admin, "update_workspace", &json!({ "name": "Acme" })).allowed);
1030 let refused = decide(&admin, "update_workspace", &json!({ "name": "Acme", "base_permission": "read" }));
1031 assert!(refused.reason.unwrap().contains("access:admin"));
1032 let both = token(&[Scope::WorkspaceAdmin, Scope::AccessAdmin]);
1033 assert!(decide(&both, "update_workspace", &json!({ "base_permission": "read" })).allowed);
1034 assert!(!decide(&token(&[Scope::WorkspaceRead]), "update_workspace", &json!({ "name": "Acme" })).allowed);
1035 }
1036
1037 #[test]
1038 fn delegating_needs_both_agents_and_issues() {
1039 let agents = token(&[Scope::AgentsRun]);
1040 assert!(decide(&agents, "delegate", &json!({})).reason.unwrap().contains("issues:write"));
1041 let both = token(&[Scope::AgentsRun, Scope::IssuesWrite]);
1042 assert!(decide(&both, "delegate", &json!({})).allowed);
1043 }
1044
1045 #[test]
1046 fn git_push_needs_code_write_and_private_reads_need_code_read() {
1047 let reader = token(&[Scope::CodeRead]);
1048 assert!(decide_git(&reader, false, false).allowed);
1049 let refused = decide_git(&reader, true, false);
1050 assert!(!refused.allowed);
1051 assert!(refused.reason.unwrap().contains("code:write"));
1052 let issues = token(&[Scope::IssuesWrite]);
1053 assert!(!decide_git(&issues, false, false).allowed);
1054 assert!(decide_git(&issues, false, true).allowed, "public code needs no scope");
1055 assert!(!decide_git(&issues, true, true).allowed, "pushing to public code still needs code:write");
1056 let writer = token(&[Scope::CodeWrite]);
1057 assert!(decide_git(&writer, true, false).allowed);
1058 assert!(decide_git(&writer, false, false).allowed, "code:write includes code:read");
1059 assert!(decide_git(&TokenAccess::full(), true, false).allowed);
1060 }
1061
1062 #[test]
1063 fn packages_need_their_own_scopes_and_public_pulls_none() {
1064 let reader = token(&[Scope::PackagesRead]);
1065 assert!(decide_packages(&reader, Level::Read, false).allowed);
1066 assert!(!decide_packages(&reader, Level::Write, false).allowed);
1067 let code = token(&[Scope::CodeWrite]);
1068 assert!(!decide_packages(&code, Level::Read, false).allowed, "code scopes are not package scopes");
1069 assert!(decide_packages(&code, Level::Read, true).allowed, "public packages pull with any token");
1070 let writer = token(&[Scope::PackagesWrite]);
1071 assert!(decide_packages(&writer, Level::Write, false).allowed);
1072 assert!(decide_packages(&writer, Level::Read, false).allowed, "packages:write includes packages:read");
1073 let refused = decide_packages(&writer, Level::Delete, false);
1074 assert!(refused.reason.unwrap().contains("packages:delete"));
1075 assert!(decide_packages(&token(&[Scope::PackagesDelete]), Level::Write, false).allowed);
1076 assert!(Scope::PackagesDelete.dangerous());
1077 // Tokens made before these scopes, and full-access ones, keep working.
1078 let legacy = TokenAccess { legacy: true, ..TokenAccess::full() };
1079 assert!(decide_packages(&legacy, Level::Delete, false).allowed);
1080 assert!(decide_packages(&TokenAccess::full(), Level::Write, false).allowed);
1081 }
1082
1083 #[test]
1084 fn token_access_travels_as_json() {
1085 let access = token(&[Scope::IssuesRead]);
1086 let wire = serde_json::to_value(&access).unwrap();
1087 assert_eq!(wire["scopes"], json!(["issues:read"]));
1088 assert!(wire.get("resources").is_none());
1089 let back: TokenAccess = serde_json::from_value(wire).unwrap();
1090 assert_eq!(back, access);
1091 let full: TokenAccess = serde_json::from_value(json!({})).unwrap();
1092 assert!(full.is_full());
1093 // A reach written by an older version is ignored: a token reaches
1094 // whatever its owner can.
1095 let older: TokenAccess = serde_json::from_value(json!({
1096 "token_id": "tok_1",
1097 "scopes": ["issues:read"],
1098 "resources": { "kind": "repositories", "repositories": ["acme/rocket"] },
1099 }))
1100 .unwrap();
1101 assert_eq!(older, access);
1102 }
1103
1104 /// The site's copy of the table, `packages/contracts/src/scopes.ts`,
1105 /// lists the same scopes in the same order, the same operations with
1106 /// the same scopes, and the same presets.
1107 #[test]
1108 fn the_typescript_mirror_has_the_same_table() {
1109 let ts = include_str!("../../../packages/contracts/src/scopes.ts");
1110 let section = |start: &str| {
1111 ts.split_once(start)
1112 .and_then(|(_, rest)| rest.split_once("] as const"))
1113 .map(|(table, _)| table)
1114 .unwrap_or_else(|| panic!("{start} in scopes.ts"))
1115 };
1116 let scopes: Vec<&str> = section("export const SCOPES = [")
1117 .lines()
1118 .filter_map(|line| line.split_once("scope: \"").and_then(|(_, rest)| rest.split_once('"')).map(|(scope, _)| scope))
1119 .collect();
1120 let expected: Vec<&str> = Scope::ALL.iter().map(|scope| scope.as_str()).collect();
1121 assert_eq!(scopes, expected);
1122 let operations: Vec<(String, String)> = section("export const OPERATION_SCOPES = [")
1123 .lines()
1124 .filter_map(|line| {
1125 let mut quoted = line.split('"').skip(1).step_by(2);
1126 Some((quoted.next()?.to_owned(), quoted.next()?.to_owned()))
1127 })
1128 .collect();
1129 let expected: Vec<(String, String)> = OPERATIONS
1130 .iter()
1131 .map(|(name, scope)| ((*name).to_owned(), scope.as_str().to_owned()))
1132 .collect();
1133 assert_eq!(operations, expected);
1134 for preset in Preset::ALL {
1135 let list = section(&format!("{}: [", preset.as_str()));
1136 let mirrored: Vec<&str> = list
1137 .split(',')
1138 .map(|item| item.trim().trim_matches('"'))
1139 .filter(|item| !item.is_empty())
1140 .collect();
1141 let expected: Vec<&str> = preset
1142 .scopes()
1143 .map(|scopes| scopes.iter().map(|scope| scope.as_str()).collect())
1144 .unwrap_or_else(|| vec!["*"]);
1145 assert_eq!(mirrored, expected, "{}", preset.as_str());
1146 }
1147 }
1148}