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