Skip to content

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

1,260 linesCodeBlameRaw
1//! Run credentials: the least-privilege tokens a sandbox works with.
2//!
3//! Every sandbox run (checks, the merge queue, a merge check, a deployment,
4//! a security update's bump) gets its own tokens, bound to the run, its
5//! repository, what that kind of run needs to do, and an expiry no later
6//! than the run's timeout. Each carries a composite identity: g1t acting on
7//! behalf of the person who started the work. What it may do is the
8//! intersection of the two: the run's scope, and what that person may do
9//! right now.
10//!
11//! g1t's retired hosted agents had run credentials too (`implement`,
12//! `revise`, `review`, `answer`, `update`, `plan`). Those kinds still parse,
13//! so stored tokens and the history they wrote read as before, but no
14//! credential is made for them and they grant nothing
15//! ([`RunCredentialKind::retired`]).
16//!
17//! The policy lives here, as pure functions, so that identity (which mints
18//! the tokens), the API (which serves REST and MCP) and repos (which serves
19//! git) all enforce the same rules, and so the rules can be tested.
20
21use serde::{Deserialize, Serialize};
22
23use crate::identity::AgentScope;
24use crate::repos::RepoPath;
25use crate::access::{BasePermission, RepoGrant, RepoRole};
26use crate::{Membership, PrincipalKind, Role, User};
27
28/// What a run does, as far as its credentials are concerned.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31pub enum RunCredentialKind {
32 /// Retired with g1t's hosted agents, as are `revise`, `review`,
33 /// `answer`, `update` and `plan`: kept so stored tokens parse; never
34 /// issued, and they grant nothing.
35 Implement,
36 /// Retired: see [`RunCredentialKind::Implement`].
37 Revise,
38 /// Retired: see [`RunCredentialKind::Implement`].
39 Review,
40 /// Retired: see [`RunCredentialKind::Implement`].
41 Answer,
42 /// Retired: see [`RunCredentialKind::Implement`].
43 Update,
44 /// Retired: see [`RunCredentialKind::Implement`].
45 Plan,
46 Checks,
47 Queue,
48 Mergecheck,
49 Deploy,
50 /// A security update: raising one package's version in its lockfiles
51 /// and pushing that to a branch of its own. Not an agent.
52 Bump,
53}
54
55impl RunCredentialKind {
56 pub const ALL: [RunCredentialKind; 11] = [
57 RunCredentialKind::Implement,
58 RunCredentialKind::Revise,
59 RunCredentialKind::Review,
60 RunCredentialKind::Answer,
61 RunCredentialKind::Update,
62 RunCredentialKind::Plan,
63 RunCredentialKind::Checks,
64 RunCredentialKind::Queue,
65 RunCredentialKind::Mergecheck,
66 RunCredentialKind::Deploy,
67 RunCredentialKind::Bump,
68 ];
69
70 pub fn as_str(self) -> &'static str {
71 match self {
72 RunCredentialKind::Implement => "implement",
73 RunCredentialKind::Revise => "revise",
74 RunCredentialKind::Review => "review",
75 RunCredentialKind::Answer => "answer",
76 RunCredentialKind::Update => "update",
77 RunCredentialKind::Plan => "plan",
78 RunCredentialKind::Checks => "checks",
79 RunCredentialKind::Queue => "queue",
80 RunCredentialKind::Mergecheck => "mergecheck",
81 RunCredentialKind::Deploy => "deploy",
82 RunCredentialKind::Bump => "bump",
83 }
84 }
85
86 /// Whether this kind was one of g1t's retired hosted agents' runs: it
87 /// still parses, but no credential is made for it and it grants
88 /// nothing.
89 pub fn retired(self) -> bool {
90 matches!(
91 self,
92 RunCredentialKind::Implement
93 | RunCredentialKind::Revise
94 | RunCredentialKind::Review
95 | RunCredentialKind::Answer
96 | RunCredentialKind::Update
97 | RunCredentialKind::Plan
98 )
99 }
100}
101
102/// Which part of a sandbox a credential is for.
103#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(rename_all = "snake_case")]
105pub enum CredentialUse {
106 /// g1t's runner: cloning, fetching and pushing what the run needs. It
107 /// acts as the person downstream, so that what it pushes is theirs,
108 /// within the run's scope.
109 Runner,
110 /// A retired hosted agent's own tools, over MCP. Kept so stored tokens
111 /// parse; never issued.
112 Tools,
113}
114
115impl CredentialUse {
116 pub fn as_str(self) -> &'static str {
117 match self {
118 CredentialUse::Runner => "runner",
119 CredentialUse::Tools => "tools",
120 }
121 }
122}
123
124/// A repository a run may push to, and the one branch, if only one.
125#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
126pub struct GitGrant {
127 pub repo: RepoPath,
128 /// Null: any branch. A pull request's fork is its own repository, so
129 /// the whole of it is the pull request's.
130 #[serde(default)]
131 pub branch: Option<String>,
132}
133
134/// What binds a token to one run. Absent on tokens g1t's retired hosted
135/// agents were issued before run credentials.
136#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138pub struct RunBinding {
139 pub kind: RunCredentialKind,
140 #[serde(rename = "use")]
141 pub usage: CredentialUse,
142 /// The run, once the sandbox has recorded it.
143 #[serde(default)]
144 pub run_id: Option<String>,
145 /// The pull request the run works on, for the kinds that work on one.
146 #[serde(default)]
147 pub number: Option<u32>,
148 /// Who acts, as the audit log names it: `g1t`.
149 pub agent: String,
150 /// Repositories it may clone and fetch, besides those it may push to.
151 #[serde(default)]
152 pub read: Vec<RepoPath>,
153 /// Where it may push.
154 #[serde(default)]
155 pub push: Vec<GitGrant>,
156 /// g1t's own run (a security update): the
157 /// credential belongs to the workspace, and acts on behalf of g1t
158 /// (`system::ID`), so what it does is g1t's, and the pull request g1t
159 /// opened, and its working copy, are its own.
160 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
161 pub system: bool,
162}
163
164/// A person, by id and name.
165#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
166pub struct Principal {
167 pub id: String,
168 pub username: String,
169}
170
171impl From<&User> for Principal {
172 fn from(user: &User) -> Self {
173 Principal {
174 id: user.id.clone(),
175 username: user.username.clone(),
176 }
177 }
178}
179
180/// Set on a [`User`] resolved from a run credential: the composite
181/// identity, "g1t on behalf of syntaqx", and what it may do.
182#[derive(Clone, Debug, Serialize, Deserialize)]
183#[serde(rename_all = "camelCase")]
184pub struct Acting {
185 /// The token's id, as audit entries name it.
186 pub credential_id: String,
187 pub agent: String,
188 pub on_behalf_of: Principal,
189 pub scope: AgentScope,
190}
191
192impl Acting {
193 pub fn run(&self) -> Option<&RunBinding> {
194 self.scope.run.as_ref()
195 }
196}
197
198/// `create_run_credential`: a token for one sandbox run. It acts as g1t on
199/// behalf of `on_behalf_of`, can do only what `kind` and `usage` allow in
200/// `repo`, and expires after `ttl_seconds`, which should be the run's
201/// timeout. A [retired](RunCredentialKind::retired) kind is refused.
202/// Returns `CreatedAccessToken`.
203#[derive(Clone, Debug, Serialize, Deserialize)]
204#[serde(rename_all = "camelCase")]
205pub struct CreateRunCredentialArgs {
206 pub on_behalf_of: User,
207 pub repo: RepoPath,
208 pub kind: RunCredentialKind,
209 #[serde(rename = "use")]
210 pub usage: CredentialUse,
211 #[serde(default)]
212 pub number: Option<u32>,
213 #[serde(default)]
214 pub read: Vec<RepoPath>,
215 #[serde(default)]
216 pub push: Vec<GitGrant>,
217 pub ttl_seconds: u64,
218}
219
220/// `bind_run_credentials`: ties tokens, named by the SHA-256 of their
221/// text in hex, to the run their sandbox recorded. Returns how many.
222#[derive(Clone, Debug, Serialize, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct BindRunCredentialsArgs {
225 pub token_hashes: Vec<String>,
226 pub run_id: String,
227}
228
229/// `revoke_run_credentials`: ends tokens when their sandbox stops, by hash
230/// or by run. Only run credentials are touched, never a token a person
231/// made. Returns how many.
232#[derive(Clone, Debug, Default, Serialize, Deserialize)]
233#[serde(rename_all = "camelCase")]
234pub struct RevokeRunCredentialsArgs {
235 #[serde(default)]
236 pub token_hashes: Vec<String>,
237 #[serde(default)]
238 pub run_id: Option<String>,
239}
240
241// --- Policy --------------------------------------------------------------
242
243/// Operations that only read.
244pub const READ_OPERATIONS: &[&str] = &[
245 "whoami",
246 "get_usage",
247 "get_budget",
248 "list_invoices",
249 "get_billing_details",
250 "list_repos",
251 "get_repo",
252 "list_forks",
253 "list_repo_commit_comments",
254 "list_commit_comments",
255 "list_projects",
256 "get_project",
257 "list_deleted_repos",
258 "list_collaborators",
259 "get_collaborator_permission",
260 "list_repo_invitations",
261 "list_my_repo_invitations",
262 "list_outside_collaborators",
263 "list_teams",
264 "get_team",
265 "list_team_members",
266 "list_child_teams",
267 "list_team_repos",
268 "list_user_teams",
269 "get_codeowners_errors",
270 "get_repo_settings",
271 "list_check_names",
272 "get_merge_queue",
273 "get_pull_request_merge_options",
274 "list_issues",
275 "get_issue",
276 "list_labels",
277 "list_issue_labels",
278 "list_milestones",
279 "get_milestone",
280 "list_pull_requests",
281 "get_pull_request",
282 "read_session",
283 "list_decisions",
284 "why",
285 "get_pull_request_changes",
286 "list_events",
287 "get_context",
288 "search",
289 "list_workflows",
290 "get_workflow",
291 "list_workflow_runs",
292 "get_workflow_run",
293 "get_job_logs",
294 "get_pending_deployments",
295 "get_workflow_permissions",
296 "get_fork_pr_approval",
297 "get_actions_permissions",
298 "list_commit_statuses",
299 "get_combined_status",
300 "list_check_runs_for_ref",
301 "get_check_run",
302 "list_check_run_annotations",
303 "list_check_suites_for_ref",
304 "get_check_suite",
305 "list_integrations",
306 "list_ai_providers",
307 "get_ask_settings",
308 "list_webhooks",
309 "list_webhook_deliveries",
310 "list_actions_secrets",
311 "list_actions_variables",
312 "list_security_alerts",
313 "list_secret_scanning_alerts",
314 "get_secret_scanning_alert",
315 "list_secret_scanning_locations",
316 "list_bypass_requests",
317 "list_custom_patterns",
318 "list_code_scanning_alerts",
319 "get_code_scanning_alert",
320 "list_code_scanning_analyses",
321 "get_sarif_upload",
322 "list_vulnerability_alerts",
323 "get_vulnerability_alert",
324 "get_dependency_graph",
325 "get_sbom",
326 "compare_dependencies",
327 "get_security_settings",
328 "get_workspace_security_settings",
329 "get_security_overview",
330 "list_security_advisories",
331 "get_security_advisory",
332 "list_vulnerability_reports",
333 "list_notifications",
334 "get_notification_thread",
335 "get_thread_subscription",
336 "get_repo_subscription",
337 "list_watched_repos",
338 "list_pinned_projects",
339];
340
341/// What no run credential may ever do, whatever its scope says:
342/// workspaces, repositories' settings, members, tokens, billing,
343/// integrations, AI providers, webhooks, secrets, workflows' controls and merging.
344pub const NEVER: &[&str] = &[
345 // Billing is people's: runs never spend or change it.
346 "set_budget",
347 "create_workspace",
348 "delete_workspace",
349 "update_workspace",
350 // So is who belongs to a workspace and who owns it.
351 "list_members",
352 "update_member",
353 "remove_member",
354 "transfer_ownership",
355 "leave_workspace",
356 "transfer_repo",
357 "create_repo",
358 "fork_repo",
359 "sync_fork",
360 "detach_fork",
361 "update_repo",
362 "update_project",
363 "delete_repo",
364 "list_deleted_repos",
365 "restore_repo",
366 "purge_repo",
367 "rename_repo",
368 "archive_repo",
369 "unarchive_repo",
370 "set_repo_visibility",
371 "rename_branch",
372 "delete_branch",
373 "update_repo_settings",
374 "merge_pull_request",
375 // Merging later, as a person asked, is merging; and a merged pull
376 // request's branch is deleted or restored by people.
377 "enable_pull_request_auto_merge",
378 "disable_pull_request_auto_merge",
379 "delete_pull_request_head_branch",
380 "restore_pull_request_head_branch",
381 "import_issue",
382 "list_integrations",
383 "connect_integration",
384 "update_integration",
385 "disconnect_integration",
386 "test_integration",
387 // A workspace's AI: its providers' keys, and what Ask answers with.
388 "list_ai_providers",
389 "add_ai_provider",
390 "update_ai_provider",
391 "remove_ai_provider",
392 "test_ai_provider",
393 "get_ask_settings",
394 "set_ask_settings",
395 "list_webhooks",
396 "create_webhook",
397 "update_webhook",
398 "delete_webhook",
399 "ping_webhook",
400 "list_webhook_deliveries",
401 "redeliver_webhook",
402 "dispatch_workflow",
403 "cancel_workflow_run",
404 "rerun_workflow_run",
405 "update_workflow",
406 // Nor lets runs or deployments through, or changes what holds them.
407 "approve_workflow_run",
408 "review_pending_deployments",
409 "update_environment",
410 "delete_environment",
411 "set_workflow_permissions",
412 "set_fork_pr_approval",
413 "set_actions_access",
414 "set_actions_permissions",
415 "create_repository_dispatch",
416 "set_workspace_workflow_permissions",
417 // An agent never reports checks on its own work, nor asks for them
418 // to run again: what checks say is the integrations' to say.
419 "create_commit_status",
420 "create_check_run",
421 "update_check_run",
422 "rerequest_check_run",
423 "rerequest_check_suite",
424 "list_actions_secrets",
425 "set_actions_secret",
426 "delete_actions_secret",
427 "list_actions_variables",
428 "set_actions_variable",
429 "delete_actions_variable",
430 "list_collaborators",
431 "get_collaborator_permission",
432 "add_collaborator",
433 "update_collaborator",
434 "remove_collaborator",
435 "list_repo_invitations",
436 "revoke_repo_invitation",
437 "list_my_repo_invitations",
438 "accept_repo_invitation",
439 "decline_repo_invitation",
440 // Nor answers a workspace invitation: only the person it is for does.
441 "accept_invitation",
442 "decline_invitation",
443 "set_base_permission",
444 "list_outside_collaborators",
445 // Deploy keys, which let a machine into a repository.
446 "list_deploy_keys",
447 "get_deploy_key",
448 "create_deploy_key",
449 "delete_deploy_key",
450 // Teams: who is in which, and what they reach, is for people.
451 "create_team",
452 "update_team",
453 "delete_team",
454 "set_team_member",
455 "remove_team_member",
456 "set_team_repo",
457 "remove_team_repo",
458 "set_team_review_assignment",
459 // Dismissing a secret lets it through push protection.
460 "dismiss_security_alert",
461 "reopen_security_alert",
462 // Nor any other decision about security: closing or reopening an
463 // alert, pushing past push protection or deciding who may, or changing
464 // what is looked for or when checks fail.
465 "update_secret_scanning_alert",
466 "bypass_push_protection",
467 "review_bypass_request",
468 "create_custom_pattern",
469 "update_custom_pattern",
470 "delete_custom_pattern",
471 "update_code_scanning_alert",
472 "update_vulnerability_alert",
473 "update_security_settings",
474 "update_workspace_security_settings",
475 // A person's own inbox: a run acts as g1t, which has none.
476 "list_notifications",
477 "get_notification_thread",
478 "mark_notifications_read",
479 "mark_thread_read",
480 "mark_thread_done",
481 "save_thread",
482 "snooze_thread",
483 "get_thread_subscription",
484 "set_thread_subscription",
485 "delete_thread_subscription",
486 "get_repo_subscription",
487 "set_repo_subscription",
488 "delete_repo_subscription",
489 "list_watched_repos",
490 // Pins are a person's own, as the inbox is.
491 "list_pinned_projects",
492 "pin_project",
493 "unpin_project",
494 "reorder_pinned_projects",
495 // Deleting packages and deciding who may use them is for people: an
496 // agent publishes its repository's packages and never deletes them.
497 "update_package",
498 "link_package",
499 "unlink_package",
500 "set_package_access",
501 "remove_package_access",
502 "set_package_actions_access",
503 "remove_package_actions_access",
504 "delete_package",
505 "restore_package",
506 "delete_package_version",
507 "restore_package_version",
508 // Sharing an artifact and deleting one for good are for people.
509 "set_workspace_artifact_access",
510 "purge_workspace_artifact",
511];
512
513pub fn is_read(operation: &str) -> bool {
514 READ_OPERATIONS.contains(&operation)
515}
516
517/// The API and MCP operations a run of `kind` may use with a credential
518/// for `usage`. Git is separate: see [`decide_git`]. None today: every run
519/// still issued works through git alone, and a
520/// [retired](RunCredentialKind::retired) kind grants nothing. A stored
521/// token keeps the operations it was made with until it expires.
522pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
523 let _ = (kind, usage);
524 Vec::new()
525}
526
527/// What a run's credential may do, in the scope vocabulary that access
528/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
529/// for a runner, git's. Its operations, its repository and its run still
530/// bound it more tightly than these scopes say.
531pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
532 use crate::scopes::{Scope, normalize, scope_for};
533 let mut scopes: Vec<Scope> = operations_for(kind, usage)
534 .into_iter()
535 .filter_map(scope_for)
536 .collect();
537 if usage == CredentialUse::Runner && !kind.retired() {
538 scopes.push(Scope::CodeRead);
539 if kind == RunCredentialKind::Bump {
540 scopes.push(Scope::CodeWrite);
541 }
542 }
543 normalize(&mut scopes);
544 scopes
545}
546
547/// Operations that change a pull request, which a runner may do only to
548/// the pull request its run works on.
549const PULL_WRITES: &[&str] = &["record_session", "record_decision", "mark_pull_request_ready"];
550
551/// Whether something was allowed, and the rule that decided it.
552#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
553pub struct Decision {
554 pub allowed: bool,
555 /// A short, stable name: `run:implement/tools`, `never`,
556 /// `scope:repository` and so on. Shown in the audit log.
557 pub rule: String,
558 /// Why it was refused, for the caller.
559 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub reason: Option<String>,
561}
562
563impl Decision {
564 pub fn allow(rule: impl Into<String>) -> Self {
565 Decision {
566 allowed: true,
567 rule: rule.into(),
568 reason: None,
569 }
570 }
571
572 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
573 Decision {
574 allowed: false,
575 rule: rule.into(),
576 reason: Some(reason.into()),
577 }
578 }
579}
580
581fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
582 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
583}
584
585fn scope_rule(scope: &AgentScope) -> String {
586 match &scope.run {
587 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
588 None => "agent-token".to_owned(),
589 }
590}
591
592/// Whether `user`, resolved from a run credential with `scope`, may use
593/// `operation`. `repo` is the repository the call names, if any, and
594/// `needs_repo` whether the operation is about one; `number` the issue or
595/// pull request it names.
596pub fn decide_operation(
597 user: &User,
598 scope: &AgentScope,
599 operation: &str,
600 repo: Option<&RepoPath>,
601 needs_repo: bool,
602 number: Option<u32>,
603) -> Decision {
604 let who = "A run's token";
605 if NEVER.contains(&operation) {
606 return Decision::deny(
607 "never",
608 format!(
609 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
610 ),
611 );
612 }
613 if !scope.operations.iter().any(|name| name == operation) {
614 return Decision::deny(
615 "scope:operation",
616 format!("{who} for this run cannot use {operation}."),
617 );
618 }
619 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
620 return Decision::deny(
621 "scope:repository",
622 format!(
623 "{who} works in {}/{} only.",
624 scope.repo.namespace, scope.repo.name
625 ),
626 );
627 }
628 // The intersection: the person it acts for must still be able to work
629 // in the repository's workspace, as a member or with a role on its
630 // repositories. What it may do in the repository itself is their
631 // role there, which services check (`access::can`).
632 if !crate::access::has_access_in(user, &scope.repo.namespace) {
633 return Decision::deny(
634 "on-behalf-of:membership",
635 format!(
636 "The person this run works for is no longer a member of {}.",
637 scope.repo.namespace
638 ),
639 );
640 }
641 if let Some(run) = &scope.run
642 && run.usage == CredentialUse::Runner
643 && PULL_WRITES.contains(&operation)
644 && run.number.is_some()
645 && number != run.number
646 {
647 return Decision::deny(
648 "scope:pull",
649 format!(
650 "{who} can change pull request #{} only.",
651 run.number.unwrap_or_default()
652 ),
653 );
654 }
655 Decision::allow(scope_rule(scope))
656}
657
658/// Whether a run credential may clone or fetch (`write` false), or push to
659/// (`write` true), the repository at `repo`.
660pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
661 let Some(run) = scope
662 .run
663 .as_ref()
664 .filter(|run| run.usage == CredentialUse::Runner)
665 else {
666 return Decision::deny(
667 "git:not-a-run",
668 "A tools token cannot be used with git.",
669 );
670 };
671 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
672 if write {
673 return if pushable {
674 Decision::allow(format!("{}:push", scope_rule(scope)))
675 } else {
676 Decision::deny(
677 "git:push",
678 format!(
679 "A {} run cannot push to {}/{}.",
680 run.kind.as_str(),
681 repo.namespace,
682 repo.name
683 ),
684 )
685 };
686 }
687 let readable = pushable
688 || same_repo(&scope.repo, repo)
689 || run.read.iter().any(|path| same_repo(path, repo));
690 if readable {
691 Decision::allow(format!("{}:read", scope_rule(scope)))
692 } else {
693 Decision::deny(
694 "git:read",
695 format!(
696 "A {} run cannot read {}/{}.",
697 run.kind.as_str(),
698 repo.namespace,
699 repo.name
700 ),
701 )
702 }
703}
704
705/// Whether a push to `repo` is limited to certain branches, so that the
706/// refs it moves have to be read and checked with [`decide_refs`].
707pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
708 scope
709 .run
710 .iter()
711 .flat_map(|run| run.push.iter())
712 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
713}
714
715/// Whether a push to `repo` may move `refs` (full refs, such as
716/// `refs/heads/main`). Tags are never a run's to move.
717pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
718 let repo_decision = decide_git(scope, repo, true);
719 if !repo_decision.allowed {
720 return repo_decision;
721 }
722 let grants: Vec<&GitGrant> = scope
723 .run
724 .iter()
725 .flat_map(|run| run.push.iter())
726 .filter(|grant| same_repo(&grant.repo, repo))
727 .collect();
728 for git_ref in refs {
729 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
730 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
731 };
732 let allowed = grants
733 .iter()
734 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
735 if !allowed {
736 return Decision::deny(
737 "git:ref",
738 format!(
739 "A run cannot push to {branch} in {}/{}.",
740 repo.namespace, repo.name
741 ),
742 );
743 }
744 }
745 repo_decision
746}
747
748/// The most an agent may be on a repository, whoever it works for: it
749/// can push, merge and run, never change settings or who has access.
750pub const AGENT_CEILING: RepoRole = RepoRole::Write;
751
752/// The memberships an agent working for `person` has: the run's
753/// workspace, as a member, only if the person is in it now, with the
754/// person's role on its repositories (an owner's Admin included) cut down
755/// to [`AGENT_CEILING`].
756pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
757 let namespace = namespace.to_lowercase();
758 person
759 .iter()
760 .filter(|membership| membership.slug == namespace)
761 .map(|membership| {
762 let base = match membership.role {
763 Role::Owner => BasePermission::Admin,
764 Role::Member => membership.base_permission.unwrap_or_default(),
765 };
766 Membership {
767 role: Role::Member,
768 base_permission: Some(match base {
769 BasePermission::Admin => BasePermission::Write,
770 base => base,
771 }),
772 // Billing and security manager are the person's, never
773 // their agent's.
774 org_roles: Vec::new(),
775 ..membership.clone()
776 }
777 })
778 .collect()
779}
780
781/// The repository grants an agent working for `person` has: those in the
782/// run's workspace, each cut down to [`AGENT_CEILING`].
783pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
784 let namespace = namespace.to_lowercase();
785 person
786 .iter()
787 .filter(|grant| grant.workspace == namespace)
788 .map(|grant| RepoGrant {
789 role: grant.role.min(AGENT_CEILING),
790 ..grant.clone()
791 })
792 .collect()
793}
794
795/// Who a runner's credential acts as downstream: the person, with only the
796/// agent's (already intersected) memberships. `None` for anything else.
797pub fn as_person(user: &User) -> Option<User> {
798 let acting = user.acting.as_ref()?;
799 if user.kind != PrincipalKind::Agent {
800 return None;
801 }
802 let run = acting.run()?;
803 if run.usage != CredentialUse::Runner {
804 return None;
805 }
806 Some(User {
807 id: acting.on_behalf_of.id.clone(),
808 username: acting.on_behalf_of.username.clone(),
809 display_username: None,
810 kind: PrincipalKind::User,
811 verified: user.verified,
812 workspaces: user.workspaces.clone(),
813 avatar: None,
814 acting: None,
815 grants: user.grants.clone(),
816 token: None,
817 held: Vec::new(),
818 })
819}
820
821/// How an actor is described: "g1t on behalf of syntaqx".
822pub fn describe(user: &User) -> String {
823 match &user.acting {
824 Some(acting) => format!(
825 "{} on behalf of {}",
826 acting.agent, acting.on_behalf_of.username
827 ),
828 None => user.username.clone(),
829 }
830}
831
832#[cfg(test)]
833mod tests {
834 use super::*;
835
836 #[test]
837 fn a_run_s_scopes_are_never_admin() {
838 for kind in RunCredentialKind::ALL {
839 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
840 let scopes = run_scopes(kind, usage);
841 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
842 }
843 }
844 use crate::scopes::Scope;
845 let bump = run_scopes(RunCredentialKind::Bump, CredentialUse::Runner);
846 assert!(bump.len() == 2 && bump.contains(&Scope::CodeRead) && bump.contains(&Scope::CodeWrite));
847 assert_eq!(run_scopes(RunCredentialKind::Checks, CredentialUse::Runner), [Scope::CodeRead]);
848 }
849
850 /// The hosted agents' kinds still parse, so stored tokens read, but
851 /// they grant nothing: no operations, no scopes.
852 #[test]
853 fn retired_kinds_parse_and_grant_nothing() {
854 for kind in RunCredentialKind::ALL {
855 let parsed: RunCredentialKind = serde_json::from_value(serde_json::json!(kind.as_str())).unwrap();
856 assert_eq!(parsed, kind);
857 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
858 assert!(operations_for(kind, usage).is_empty(), "{kind:?} {usage:?}");
859 if kind.retired() {
860 assert!(run_scopes(kind, usage).is_empty(), "{kind:?} {usage:?}");
861 }
862 }
863 }
864 let retired: Vec<&str> = RunCredentialKind::ALL.iter().filter(|kind| kind.retired()).map(|kind| kind.as_str()).collect();
865 assert_eq!(retired, ["implement", "revise", "review", "answer", "update", "plan"]);
866 }
867
868 #[test]
869 fn site_wide_search_only_reads() {
870 assert!(is_read("search"));
871 assert!(!NEVER.contains(&"search"));
872 }
873
874 fn path(namespace: &str, name: &str) -> RepoPath {
875 RepoPath {
876 namespace: namespace.to_owned(),
877 name: name.to_owned(),
878 }
879 }
880
881 /// What a token stored before the hosted agents were retired lists:
882 /// the operations it was made with, which it keeps until it expires.
883 fn stored_operations(kind: RunCredentialKind, usage: CredentialUse) -> Vec<String> {
884 use RunCredentialKind as K;
885 let names: Vec<&str> = match usage {
886 CredentialUse::Runner => match kind {
887 K::Implement => vec!["get_repo", "get_pull_request", "record_session", "mark_pull_request_ready"],
888 K::Revise | K::Answer | K::Update => vec!["get_repo", "get_pull_request", "record_session"],
889 _ => vec![],
890 },
891 CredentialUse::Tools => match kind {
892 K::Implement | K::Revise | K::Answer => vec!["get_issue", "get_pull_request", "create_issue", "add_comment", "remember"],
893 K::Review => vec!["get_issue", "get_pull_request", "add_comment", "review_pull_request"],
894 K::Plan => vec!["get_issue", "get_pull_request", "create_issue"],
895 K::Update => vec!["get_issue", "get_pull_request"],
896 _ => vec![],
897 },
898 };
899 names.into_iter().map(str::to_owned).collect()
900 }
901
902 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
903 AgentScope {
904 repo: path("acme", "rocket"),
905 operations: stored_operations(kind, usage),
906 run: Some(RunBinding {
907 kind,
908 usage,
909 run_id: Some("run_1".to_owned()),
910 number: Some(7),
911 agent: "g1t".to_owned(),
912 system: false,
913 read: vec![path("acme", "rocket")],
914 push: match kind {
915 RunCredentialKind::Implement
916 | RunCredentialKind::Revise
917 | RunCredentialKind::Answer => vec![GitGrant {
918 repo: path("pulls", "pul_7"),
919 branch: None,
920 }],
921 RunCredentialKind::Update => vec![GitGrant {
922 repo: path("acme", "rocket"),
923 branch: Some("fix-login".to_owned()),
924 }],
925 _ => vec![],
926 },
927 }),
928 }
929 }
930
931 fn agent(member_of: &[&str], scope: AgentScope) -> User {
932 User {
933 id: "usr_g1t_agent".to_owned(),
934 username: "g1t".to_owned(),
935 display_username: None,
936 kind: PrincipalKind::Agent,
937 verified: true,
938 workspaces: member_of
939 .iter()
940 .map(|slug| Membership::member(*slug))
941 .collect(),
942 avatar: None,
943 grants: Vec::new(),
944 token: None,
945 held: Vec::new(),
946 acting: Some(Box::new(Acting {
947 credential_id: "tok_1".to_owned(),
948 agent: "g1t".to_owned(),
949 on_behalf_of: Principal {
950 id: "usr_1".to_owned(),
951 username: "syntaqx".to_owned(),
952 },
953 scope,
954 })),
955 }
956 }
957
958 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
959 let scope = scope(kind, usage);
960 let user = agent(&["acme"], scope.clone());
961 decide_operation(
962 &user,
963 &scope,
964 operation,
965 Some(&path("acme", "rocket")),
966 true,
967 Some(7),
968 )
969 }
970
971 use CredentialUse::{Runner, Tools};
972 use RunCredentialKind as K;
973
974 /// A stored token may use only what it lists, and never what no run
975 /// may.
976 #[test]
977 fn a_stored_token_uses_only_what_it_lists() {
978 assert!(op(K::Implement, Tools, "create_issue").allowed);
979 assert!(op(K::Review, Tools, "review_pull_request").allowed);
980 assert!(!op(K::Review, Tools, "create_issue").allowed);
981 assert!(!op(K::Plan, Tools, "add_comment").allowed);
982 assert!(!op(K::Checks, Tools, "get_issue").allowed);
983 for operation in ["record_session", "merge_pull_request", "update_repo_settings", "create_webhook", "set_actions_secret"] {
984 for kind in [K::Implement, K::Revise, K::Answer, K::Review, K::Plan, K::Checks] {
985 assert!(!op(kind, Tools, operation).allowed, "{operation} by a {} run's tools", kind.as_str());
986 }
987 }
988 }
989
990 #[test]
991 fn runner_matrix() {
992 assert!(op(K::Implement, Runner, "record_session").allowed);
993 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
994 assert!(op(K::Revise, Runner, "record_session").allowed);
995 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
996 assert!(!op(K::Implement, Runner, "create_issue").allowed);
997 assert!(!op(K::Review, Runner, "record_session").allowed);
998 assert!(!op(K::Checks, Runner, "get_issue").allowed);
999 }
1000
1001 #[test]
1002 fn settings_billing_tokens_and_members_are_never_reachable() {
1003 for kind in RunCredentialKind::ALL {
1004 for usage in [Runner, Tools] {
1005 for operation in NEVER.iter().copied() {
1006 let decision = op(kind, usage, operation);
1007 assert!(!decision.allowed);
1008 assert_eq!(decision.rule, "never");
1009 }
1010 }
1011 }
1012 // Even a scope that lists one is refused.
1013 let mut wide = scope(K::Implement, Tools);
1014 wide.operations.push("merge_pull_request".to_owned());
1015 let user = agent(&["acme"], wide.clone());
1016 let decision = decide_operation(
1017 &user,
1018 &wide,
1019 "merge_pull_request",
1020 Some(&path("acme", "rocket")),
1021 true,
1022 Some(7),
1023 );
1024 assert_eq!(decision.rule, "never");
1025 }
1026
1027 #[test]
1028 fn another_repository_is_refused() {
1029 let scope = scope(K::Implement, Tools);
1030 let user = agent(&["acme"], scope.clone());
1031 let decision = decide_operation(
1032 &user,
1033 &scope,
1034 "create_issue",
1035 Some(&path("acme", "other")),
1036 true,
1037 None,
1038 );
1039 assert!(!decision.allowed);
1040 assert_eq!(decision.rule, "scope:repository");
1041 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
1042 assert_eq!(decision.rule, "scope:repository");
1043 // The repository's name is matched without regard to case.
1044 let decision = decide_operation(
1045 &user,
1046 &scope,
1047 "create_issue",
1048 Some(&path("Acme", "Rocket")),
1049 true,
1050 None,
1051 );
1052 assert!(decision.allowed);
1053 assert_eq!(decision.rule, "run:implement/tools");
1054 }
1055
1056 #[test]
1057 fn the_permission_is_the_intersection_with_the_person() {
1058 let scope = scope(K::Implement, Tools);
1059 // The person left the workspace: their agent can do nothing there.
1060 let user = agent(&[], scope.clone());
1061 let decision = decide_operation(
1062 &user,
1063 &scope,
1064 "get_issue",
1065 Some(&path("acme", "rocket")),
1066 true,
1067 Some(1),
1068 );
1069 assert!(!decision.allowed);
1070 assert_eq!(decision.rule, "on-behalf-of:membership");
1071 // And an owner's agent is only ever a member.
1072 let owner = vec![
1073 Membership {
1074 slug: "acme".to_owned(),
1075 role: Role::Owner,
1076 name: None,
1077 avatar: None,
1078 base_permission: Some(BasePermission::None),
1079 team_creation: None,
1080 org_roles: vec![crate::OrgRole::SecurityManager],
1081 privileges: None,
1082 },
1083 Membership::member("elsewhere"),
1084 ];
1085 let memberships = intersect(&owner, "Acme");
1086 assert_eq!(memberships.len(), 1);
1087 assert_eq!(memberships[0].slug, "acme");
1088 assert_eq!(memberships[0].role, Role::Member);
1089 assert!(memberships[0].org_roles.is_empty());
1090 assert!(intersect(&owner, "nowhere").is_empty());
1091 }
1092
1093 /// An agent gets at most the person's role on the repository, and
1094 /// never more than Write; nothing outside the run's workspace.
1095 #[test]
1096 fn an_agent_has_at_most_its_persons_role() {
1097 use crate::access::{Capability, RepoRef, can, permission};
1098 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
1099 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
1100 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
1101 let tools = scope(K::Implement, Tools);
1102 let scope = scope(K::Implement, Runner);
1103 // An owner's agent: Write, never Admin.
1104 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
1105 let mut agent_user = agent(&[], scope.clone());
1106 agent_user.workspaces = intersect(&owner, "acme");
1107 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1108 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
1109 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1110 // A member whose workspace gives Read: Read, so it cannot push.
1111 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
1112 agent_user.workspaces = intersect(&reader, "acme");
1113 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
1114 assert!(!can(Some(&agent_user), rocket, Capability::Push));
1115 // An outside collaborator with Maintain on one repository: Write
1116 // there, nothing elsewhere, and the run is allowed.
1117 let grants = [
1118 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain, team: None },
1119 RepoGrant { repo_id: "rep_3".into(), workspace: "globex".into(), role: RepoRole::Admin, team: None },
1120 ];
1121 agent_user.workspaces = intersect(&[], "acme");
1122 agent_user.grants = intersect_grants(&grants, "Acme");
1123 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1124 assert_eq!(permission(Some(&agent_user), other), None);
1125 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1126 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
1127 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
1128 // The person, downstream of a runner's credential, carries the same.
1129 let person = as_person(&agent_user).expect("a runner acts as the person");
1130 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
1131 }
1132
1133 #[test]
1134 fn a_runner_changes_only_its_own_pull_request() {
1135 let scope = scope(K::Implement, Runner);
1136 let user = agent(&["acme"], scope.clone());
1137 let repo = path("acme", "rocket");
1138 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1139 assert!(!other.allowed);
1140 assert_eq!(other.rule, "scope:pull");
1141 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1142 assert!(own.allowed);
1143 // Reading another is fine.
1144 assert!(
1145 decide_operation(
1146 &user,
1147 &scope,
1148 "get_pull_request",
1149 Some(&repo),
1150 true,
1151 Some(8)
1152 )
1153 .allowed
1154 );
1155 }
1156
1157 #[test]
1158 fn git_matrix() {
1159 let fork = path("pulls", "pul_7");
1160 let upstream = path("acme", "rocket");
1161 let elsewhere = path("acme", "billing");
1162 let implement = scope(K::Implement, Runner);
1163 assert!(decide_git(&implement, &fork, true).allowed);
1164 assert!(decide_git(&implement, &fork, false).allowed);
1165 assert!(decide_git(&implement, &upstream, false).allowed);
1166 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1167 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1168 let review = scope(K::Review, Runner);
1169 assert!(decide_git(&review, &upstream, false).allowed);
1170 assert!(!decide_git(&review, &upstream, true).allowed);
1171 assert!(!decide_git(&review, &fork, true).allowed);
1172 // A tools token made before run credentials never reaches git.
1173 let old = AgentScope {
1174 repo: upstream.clone(),
1175 operations: vec!["get_issue".to_owned()],
1176 run: None,
1177 };
1178 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1179 // Nor does an agent's tools token.
1180 assert_eq!(
1181 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1182 "git:not-a-run"
1183 );
1184 }
1185
1186 #[test]
1187 fn a_push_moves_only_granted_branches() {
1188 let update = scope(K::Update, Runner);
1189 let repo = path("acme", "rocket");
1190 let refs = |names: &[&str]| {
1191 names
1192 .iter()
1193 .map(|name| (*name).to_owned())
1194 .collect::<Vec<_>>()
1195 };
1196 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1197 assert_eq!(
1198 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1199 "git:ref"
1200 );
1201 assert_eq!(
1202 decide_refs(
1203 &update,
1204 &repo,
1205 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1206 )
1207 .rule,
1208 "git:ref"
1209 );
1210 let implement = scope(K::Implement, Runner);
1211 assert!(
1212 decide_refs(
1213 &implement,
1214 &path("pulls", "pul_7"),
1215 &refs(&["refs/heads/main"])
1216 )
1217 .allowed
1218 );
1219 }
1220
1221 #[test]
1222 fn a_runner_acts_downstream_as_the_person() {
1223 let user = agent(&["acme"], scope(K::Implement, Runner));
1224 let person = as_person(&user).unwrap();
1225 assert_eq!(person.id, "usr_1");
1226 assert_eq!(person.username, "syntaqx");
1227 assert_eq!(person.kind, PrincipalKind::User);
1228 assert!(person.is_member("acme"));
1229 assert!(person.acting.is_none());
1230 assert_eq!(describe(&user), "g1t on behalf of syntaqx");
1231 // The tools act as the agent.
1232 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1233 }
1234
1235 #[test]
1236 fn scopes_without_a_run_still_parse() {
1237 let old: AgentScope = serde_json::from_str(
1238 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1239 )
1240 .unwrap();
1241 assert!(old.run.is_none());
1242 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1243 assert!(written.contains(r#""use":"tools""#));
1244 assert!(written.contains(r#""kind":"review""#));
1245 let back: AgentScope = serde_json::from_str(&written).unwrap();
1246 assert_eq!(back.run.unwrap().kind, K::Review);
1247 // Only g1t's own runs say so; every other reads as not.
1248 assert!(!written.contains("system"));
1249 assert!(!back_run(&written).system);
1250 let mut own = scope(K::Bump, Runner);
1251 own.run.as_mut().unwrap().system = true;
1252 let written = serde_json::to_string(&own).unwrap();
1253 assert!(written.contains(r#""system":true"#));
1254 assert!(back_run(&written).system);
1255 }
1256
1257 fn back_run(written: &str) -> RunBinding {
1258 serde_json::from_str::<AgentScope>(written).unwrap().run.unwrap()
1259 }
1260}