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,250 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_webhooks",
307 "list_webhook_deliveries",
308 "list_actions_secrets",
309 "list_actions_variables",
310 "list_security_alerts",
311 "list_secret_scanning_alerts",
312 "get_secret_scanning_alert",
313 "list_secret_scanning_locations",
314 "list_bypass_requests",
315 "list_custom_patterns",
316 "list_code_scanning_alerts",
317 "get_code_scanning_alert",
318 "list_code_scanning_analyses",
319 "get_sarif_upload",
320 "list_vulnerability_alerts",
321 "get_vulnerability_alert",
322 "get_dependency_graph",
323 "get_sbom",
324 "compare_dependencies",
325 "get_security_settings",
326 "get_workspace_security_settings",
327 "get_security_overview",
328 "list_security_advisories",
329 "get_security_advisory",
330 "list_vulnerability_reports",
331 "list_notifications",
332 "get_notification_thread",
333 "get_thread_subscription",
334 "get_repo_subscription",
335 "list_watched_repos",
336 "list_pinned_projects",
337];
338
339/// What no run credential may ever do, whatever its scope says:
340/// workspaces, repositories' settings, members, tokens, billing,
341/// integrations, webhooks, secrets, workflows' controls and merging.
342pub const NEVER: &[&str] = &[
343 // Billing is people's: runs never spend or change it.
344 "set_budget",
345 "create_workspace",
346 "delete_workspace",
347 "update_workspace",
348 // So is who belongs to a workspace and who owns it.
349 "list_members",
350 "update_member",
351 "remove_member",
352 "transfer_ownership",
353 "leave_workspace",
354 "transfer_repo",
355 "create_repo",
356 "fork_repo",
357 "sync_fork",
358 "detach_fork",
359 "update_repo",
360 "update_project",
361 "delete_repo",
362 "list_deleted_repos",
363 "restore_repo",
364 "purge_repo",
365 "rename_repo",
366 "archive_repo",
367 "unarchive_repo",
368 "set_repo_visibility",
369 "rename_branch",
370 "delete_branch",
371 "update_repo_settings",
372 "merge_pull_request",
373 // Merging later, as a person asked, is merging; and a merged pull
374 // request's branch is deleted or restored by people.
375 "enable_pull_request_auto_merge",
376 "disable_pull_request_auto_merge",
377 "delete_pull_request_head_branch",
378 "restore_pull_request_head_branch",
379 "import_issue",
380 "list_integrations",
381 "connect_integration",
382 "update_integration",
383 "disconnect_integration",
384 "test_integration",
385 "list_webhooks",
386 "create_webhook",
387 "update_webhook",
388 "delete_webhook",
389 "ping_webhook",
390 "list_webhook_deliveries",
391 "redeliver_webhook",
392 "dispatch_workflow",
393 "cancel_workflow_run",
394 "rerun_workflow_run",
395 "update_workflow",
396 // Nor lets runs or deployments through, or changes what holds them.
397 "approve_workflow_run",
398 "review_pending_deployments",
399 "update_environment",
400 "delete_environment",
401 "set_workflow_permissions",
402 "set_fork_pr_approval",
403 "set_actions_access",
404 "set_actions_permissions",
405 "create_repository_dispatch",
406 "set_workspace_workflow_permissions",
407 // An agent never reports checks on its own work, nor asks for them
408 // to run again: what checks say is the integrations' to say.
409 "create_commit_status",
410 "create_check_run",
411 "update_check_run",
412 "rerequest_check_run",
413 "rerequest_check_suite",
414 "list_actions_secrets",
415 "set_actions_secret",
416 "delete_actions_secret",
417 "list_actions_variables",
418 "set_actions_variable",
419 "delete_actions_variable",
420 "list_collaborators",
421 "get_collaborator_permission",
422 "add_collaborator",
423 "update_collaborator",
424 "remove_collaborator",
425 "list_repo_invitations",
426 "revoke_repo_invitation",
427 "list_my_repo_invitations",
428 "accept_repo_invitation",
429 "decline_repo_invitation",
430 // Nor answers a workspace invitation: only the person it is for does.
431 "accept_invitation",
432 "decline_invitation",
433 "set_base_permission",
434 "list_outside_collaborators",
435 // Deploy keys, which let a machine into a repository.
436 "list_deploy_keys",
437 "get_deploy_key",
438 "create_deploy_key",
439 "delete_deploy_key",
440 // Teams: who is in which, and what they reach, is for people.
441 "create_team",
442 "update_team",
443 "delete_team",
444 "set_team_member",
445 "remove_team_member",
446 "set_team_repo",
447 "remove_team_repo",
448 "set_team_review_assignment",
449 // Dismissing a secret lets it through push protection.
450 "dismiss_security_alert",
451 "reopen_security_alert",
452 // Nor any other decision about security: closing or reopening an
453 // alert, pushing past push protection or deciding who may, or changing
454 // what is looked for or when checks fail.
455 "update_secret_scanning_alert",
456 "bypass_push_protection",
457 "review_bypass_request",
458 "create_custom_pattern",
459 "update_custom_pattern",
460 "delete_custom_pattern",
461 "update_code_scanning_alert",
462 "update_vulnerability_alert",
463 "update_security_settings",
464 "update_workspace_security_settings",
465 // A person's own inbox: a run acts as g1t, which has none.
466 "list_notifications",
467 "get_notification_thread",
468 "mark_notifications_read",
469 "mark_thread_read",
470 "mark_thread_done",
471 "save_thread",
472 "snooze_thread",
473 "get_thread_subscription",
474 "set_thread_subscription",
475 "delete_thread_subscription",
476 "get_repo_subscription",
477 "set_repo_subscription",
478 "delete_repo_subscription",
479 "list_watched_repos",
480 // Pins are a person's own, as the inbox is.
481 "list_pinned_projects",
482 "pin_project",
483 "unpin_project",
484 "reorder_pinned_projects",
485 // Deleting packages and deciding who may use them is for people: an
486 // agent publishes its repository's packages and never deletes them.
487 "update_package",
488 "link_package",
489 "unlink_package",
490 "set_package_access",
491 "remove_package_access",
492 "set_package_actions_access",
493 "remove_package_actions_access",
494 "delete_package",
495 "restore_package",
496 "delete_package_version",
497 "restore_package_version",
498 // Sharing an artifact and deleting one for good are for people.
499 "set_workspace_artifact_access",
500 "purge_workspace_artifact",
501];
502
503pub fn is_read(operation: &str) -> bool {
504 READ_OPERATIONS.contains(&operation)
505}
506
507/// The API and MCP operations a run of `kind` may use with a credential
508/// for `usage`. Git is separate: see [`decide_git`]. None today: every run
509/// still issued works through git alone, and a
510/// [retired](RunCredentialKind::retired) kind grants nothing. A stored
511/// token keeps the operations it was made with until it expires.
512pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
513 let _ = (kind, usage);
514 Vec::new()
515}
516
517/// What a run's credential may do, in the scope vocabulary that access
518/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
519/// for a runner, git's. Its operations, its repository and its run still
520/// bound it more tightly than these scopes say.
521pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
522 use crate::scopes::{Scope, normalize, scope_for};
523 let mut scopes: Vec<Scope> = operations_for(kind, usage)
524 .into_iter()
525 .filter_map(scope_for)
526 .collect();
527 if usage == CredentialUse::Runner && !kind.retired() {
528 scopes.push(Scope::CodeRead);
529 if kind == RunCredentialKind::Bump {
530 scopes.push(Scope::CodeWrite);
531 }
532 }
533 normalize(&mut scopes);
534 scopes
535}
536
537/// Operations that change a pull request, which a runner may do only to
538/// the pull request its run works on.
539const PULL_WRITES: &[&str] = &["record_session", "record_decision", "mark_pull_request_ready"];
540
541/// Whether something was allowed, and the rule that decided it.
542#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
543pub struct Decision {
544 pub allowed: bool,
545 /// A short, stable name: `run:implement/tools`, `never`,
546 /// `scope:repository` and so on. Shown in the audit log.
547 pub rule: String,
548 /// Why it was refused, for the caller.
549 #[serde(default, skip_serializing_if = "Option::is_none")]
550 pub reason: Option<String>,
551}
552
553impl Decision {
554 pub fn allow(rule: impl Into<String>) -> Self {
555 Decision {
556 allowed: true,
557 rule: rule.into(),
558 reason: None,
559 }
560 }
561
562 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
563 Decision {
564 allowed: false,
565 rule: rule.into(),
566 reason: Some(reason.into()),
567 }
568 }
569}
570
571fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
572 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
573}
574
575fn scope_rule(scope: &AgentScope) -> String {
576 match &scope.run {
577 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
578 None => "agent-token".to_owned(),
579 }
580}
581
582/// Whether `user`, resolved from a run credential with `scope`, may use
583/// `operation`. `repo` is the repository the call names, if any, and
584/// `needs_repo` whether the operation is about one; `number` the issue or
585/// pull request it names.
586pub fn decide_operation(
587 user: &User,
588 scope: &AgentScope,
589 operation: &str,
590 repo: Option<&RepoPath>,
591 needs_repo: bool,
592 number: Option<u32>,
593) -> Decision {
594 let who = "A run's token";
595 if NEVER.contains(&operation) {
596 return Decision::deny(
597 "never",
598 format!(
599 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
600 ),
601 );
602 }
603 if !scope.operations.iter().any(|name| name == operation) {
604 return Decision::deny(
605 "scope:operation",
606 format!("{who} for this run cannot use {operation}."),
607 );
608 }
609 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
610 return Decision::deny(
611 "scope:repository",
612 format!(
613 "{who} works in {}/{} only.",
614 scope.repo.namespace, scope.repo.name
615 ),
616 );
617 }
618 // The intersection: the person it acts for must still be able to work
619 // in the repository's workspace, as a member or with a role on its
620 // repositories. What it may do in the repository itself is their
621 // role there, which services check (`access::can`).
622 if !crate::access::has_access_in(user, &scope.repo.namespace) {
623 return Decision::deny(
624 "on-behalf-of:membership",
625 format!(
626 "The person this run works for is no longer a member of {}.",
627 scope.repo.namespace
628 ),
629 );
630 }
631 if let Some(run) = &scope.run
632 && run.usage == CredentialUse::Runner
633 && PULL_WRITES.contains(&operation)
634 && run.number.is_some()
635 && number != run.number
636 {
637 return Decision::deny(
638 "scope:pull",
639 format!(
640 "{who} can change pull request #{} only.",
641 run.number.unwrap_or_default()
642 ),
643 );
644 }
645 Decision::allow(scope_rule(scope))
646}
647
648/// Whether a run credential may clone or fetch (`write` false), or push to
649/// (`write` true), the repository at `repo`.
650pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
651 let Some(run) = scope
652 .run
653 .as_ref()
654 .filter(|run| run.usage == CredentialUse::Runner)
655 else {
656 return Decision::deny(
657 "git:not-a-run",
658 "A tools token cannot be used with git.",
659 );
660 };
661 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
662 if write {
663 return if pushable {
664 Decision::allow(format!("{}:push", scope_rule(scope)))
665 } else {
666 Decision::deny(
667 "git:push",
668 format!(
669 "A {} run cannot push to {}/{}.",
670 run.kind.as_str(),
671 repo.namespace,
672 repo.name
673 ),
674 )
675 };
676 }
677 let readable = pushable
678 || same_repo(&scope.repo, repo)
679 || run.read.iter().any(|path| same_repo(path, repo));
680 if readable {
681 Decision::allow(format!("{}:read", scope_rule(scope)))
682 } else {
683 Decision::deny(
684 "git:read",
685 format!(
686 "A {} run cannot read {}/{}.",
687 run.kind.as_str(),
688 repo.namespace,
689 repo.name
690 ),
691 )
692 }
693}
694
695/// Whether a push to `repo` is limited to certain branches, so that the
696/// refs it moves have to be read and checked with [`decide_refs`].
697pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
698 scope
699 .run
700 .iter()
701 .flat_map(|run| run.push.iter())
702 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
703}
704
705/// Whether a push to `repo` may move `refs` (full refs, such as
706/// `refs/heads/main`). Tags are never a run's to move.
707pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
708 let repo_decision = decide_git(scope, repo, true);
709 if !repo_decision.allowed {
710 return repo_decision;
711 }
712 let grants: Vec<&GitGrant> = scope
713 .run
714 .iter()
715 .flat_map(|run| run.push.iter())
716 .filter(|grant| same_repo(&grant.repo, repo))
717 .collect();
718 for git_ref in refs {
719 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
720 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
721 };
722 let allowed = grants
723 .iter()
724 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
725 if !allowed {
726 return Decision::deny(
727 "git:ref",
728 format!(
729 "A run cannot push to {branch} in {}/{}.",
730 repo.namespace, repo.name
731 ),
732 );
733 }
734 }
735 repo_decision
736}
737
738/// The most an agent may be on a repository, whoever it works for: it
739/// can push, merge and run, never change settings or who has access.
740pub const AGENT_CEILING: RepoRole = RepoRole::Write;
741
742/// The memberships an agent working for `person` has: the run's
743/// workspace, as a member, only if the person is in it now, with the
744/// person's role on its repositories (an owner's Admin included) cut down
745/// to [`AGENT_CEILING`].
746pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
747 let namespace = namespace.to_lowercase();
748 person
749 .iter()
750 .filter(|membership| membership.slug == namespace)
751 .map(|membership| {
752 let base = match membership.role {
753 Role::Owner => BasePermission::Admin,
754 Role::Member => membership.base_permission.unwrap_or_default(),
755 };
756 Membership {
757 role: Role::Member,
758 base_permission: Some(match base {
759 BasePermission::Admin => BasePermission::Write,
760 base => base,
761 }),
762 // Billing and security manager are the person's, never
763 // their agent's.
764 org_roles: Vec::new(),
765 ..membership.clone()
766 }
767 })
768 .collect()
769}
770
771/// The repository grants an agent working for `person` has: those in the
772/// run's workspace, each cut down to [`AGENT_CEILING`].
773pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
774 let namespace = namespace.to_lowercase();
775 person
776 .iter()
777 .filter(|grant| grant.workspace == namespace)
778 .map(|grant| RepoGrant {
779 role: grant.role.min(AGENT_CEILING),
780 ..grant.clone()
781 })
782 .collect()
783}
784
785/// Who a runner's credential acts as downstream: the person, with only the
786/// agent's (already intersected) memberships. `None` for anything else.
787pub fn as_person(user: &User) -> Option<User> {
788 let acting = user.acting.as_ref()?;
789 if user.kind != PrincipalKind::Agent {
790 return None;
791 }
792 let run = acting.run()?;
793 if run.usage != CredentialUse::Runner {
794 return None;
795 }
796 Some(User {
797 id: acting.on_behalf_of.id.clone(),
798 username: acting.on_behalf_of.username.clone(),
799 display_username: None,
800 kind: PrincipalKind::User,
801 verified: user.verified,
802 workspaces: user.workspaces.clone(),
803 avatar: None,
804 acting: None,
805 grants: user.grants.clone(),
806 token: None,
807 held: Vec::new(),
808 })
809}
810
811/// How an actor is described: "g1t on behalf of syntaqx".
812pub fn describe(user: &User) -> String {
813 match &user.acting {
814 Some(acting) => format!(
815 "{} on behalf of {}",
816 acting.agent, acting.on_behalf_of.username
817 ),
818 None => user.username.clone(),
819 }
820}
821
822#[cfg(test)]
823mod tests {
824 use super::*;
825
826 #[test]
827 fn a_run_s_scopes_are_never_admin() {
828 for kind in RunCredentialKind::ALL {
829 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
830 let scopes = run_scopes(kind, usage);
831 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
832 }
833 }
834 use crate::scopes::Scope;
835 let bump = run_scopes(RunCredentialKind::Bump, CredentialUse::Runner);
836 assert!(bump.len() == 2 && bump.contains(&Scope::CodeRead) && bump.contains(&Scope::CodeWrite));
837 assert_eq!(run_scopes(RunCredentialKind::Checks, CredentialUse::Runner), [Scope::CodeRead]);
838 }
839
840 /// The hosted agents' kinds still parse, so stored tokens read, but
841 /// they grant nothing: no operations, no scopes.
842 #[test]
843 fn retired_kinds_parse_and_grant_nothing() {
844 for kind in RunCredentialKind::ALL {
845 let parsed: RunCredentialKind = serde_json::from_value(serde_json::json!(kind.as_str())).unwrap();
846 assert_eq!(parsed, kind);
847 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
848 assert!(operations_for(kind, usage).is_empty(), "{kind:?} {usage:?}");
849 if kind.retired() {
850 assert!(run_scopes(kind, usage).is_empty(), "{kind:?} {usage:?}");
851 }
852 }
853 }
854 let retired: Vec<&str> = RunCredentialKind::ALL.iter().filter(|kind| kind.retired()).map(|kind| kind.as_str()).collect();
855 assert_eq!(retired, ["implement", "revise", "review", "answer", "update", "plan"]);
856 }
857
858 #[test]
859 fn site_wide_search_only_reads() {
860 assert!(is_read("search"));
861 assert!(!NEVER.contains(&"search"));
862 }
863
864 fn path(namespace: &str, name: &str) -> RepoPath {
865 RepoPath {
866 namespace: namespace.to_owned(),
867 name: name.to_owned(),
868 }
869 }
870
871 /// What a token stored before the hosted agents were retired lists:
872 /// the operations it was made with, which it keeps until it expires.
873 fn stored_operations(kind: RunCredentialKind, usage: CredentialUse) -> Vec<String> {
874 use RunCredentialKind as K;
875 let names: Vec<&str> = match usage {
876 CredentialUse::Runner => match kind {
877 K::Implement => vec!["get_repo", "get_pull_request", "record_session", "mark_pull_request_ready"],
878 K::Revise | K::Answer | K::Update => vec!["get_repo", "get_pull_request", "record_session"],
879 _ => vec![],
880 },
881 CredentialUse::Tools => match kind {
882 K::Implement | K::Revise | K::Answer => vec!["get_issue", "get_pull_request", "create_issue", "add_comment", "remember"],
883 K::Review => vec!["get_issue", "get_pull_request", "add_comment", "review_pull_request"],
884 K::Plan => vec!["get_issue", "get_pull_request", "create_issue"],
885 K::Update => vec!["get_issue", "get_pull_request"],
886 _ => vec![],
887 },
888 };
889 names.into_iter().map(str::to_owned).collect()
890 }
891
892 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
893 AgentScope {
894 repo: path("acme", "rocket"),
895 operations: stored_operations(kind, usage),
896 run: Some(RunBinding {
897 kind,
898 usage,
899 run_id: Some("run_1".to_owned()),
900 number: Some(7),
901 agent: "g1t".to_owned(),
902 system: false,
903 read: vec![path("acme", "rocket")],
904 push: match kind {
905 RunCredentialKind::Implement
906 | RunCredentialKind::Revise
907 | RunCredentialKind::Answer => vec![GitGrant {
908 repo: path("pulls", "pul_7"),
909 branch: None,
910 }],
911 RunCredentialKind::Update => vec![GitGrant {
912 repo: path("acme", "rocket"),
913 branch: Some("fix-login".to_owned()),
914 }],
915 _ => vec![],
916 },
917 }),
918 }
919 }
920
921 fn agent(member_of: &[&str], scope: AgentScope) -> User {
922 User {
923 id: "usr_g1t_agent".to_owned(),
924 username: "g1t".to_owned(),
925 display_username: None,
926 kind: PrincipalKind::Agent,
927 verified: true,
928 workspaces: member_of
929 .iter()
930 .map(|slug| Membership::member(*slug))
931 .collect(),
932 avatar: None,
933 grants: Vec::new(),
934 token: None,
935 held: Vec::new(),
936 acting: Some(Box::new(Acting {
937 credential_id: "tok_1".to_owned(),
938 agent: "g1t".to_owned(),
939 on_behalf_of: Principal {
940 id: "usr_1".to_owned(),
941 username: "syntaqx".to_owned(),
942 },
943 scope,
944 })),
945 }
946 }
947
948 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
949 let scope = scope(kind, usage);
950 let user = agent(&["acme"], scope.clone());
951 decide_operation(
952 &user,
953 &scope,
954 operation,
955 Some(&path("acme", "rocket")),
956 true,
957 Some(7),
958 )
959 }
960
961 use CredentialUse::{Runner, Tools};
962 use RunCredentialKind as K;
963
964 /// A stored token may use only what it lists, and never what no run
965 /// may.
966 #[test]
967 fn a_stored_token_uses_only_what_it_lists() {
968 assert!(op(K::Implement, Tools, "create_issue").allowed);
969 assert!(op(K::Review, Tools, "review_pull_request").allowed);
970 assert!(!op(K::Review, Tools, "create_issue").allowed);
971 assert!(!op(K::Plan, Tools, "add_comment").allowed);
972 assert!(!op(K::Checks, Tools, "get_issue").allowed);
973 for operation in ["record_session", "merge_pull_request", "update_repo_settings", "create_webhook", "set_actions_secret"] {
974 for kind in [K::Implement, K::Revise, K::Answer, K::Review, K::Plan, K::Checks] {
975 assert!(!op(kind, Tools, operation).allowed, "{operation} by a {} run's tools", kind.as_str());
976 }
977 }
978 }
979
980 #[test]
981 fn runner_matrix() {
982 assert!(op(K::Implement, Runner, "record_session").allowed);
983 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
984 assert!(op(K::Revise, Runner, "record_session").allowed);
985 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
986 assert!(!op(K::Implement, Runner, "create_issue").allowed);
987 assert!(!op(K::Review, Runner, "record_session").allowed);
988 assert!(!op(K::Checks, Runner, "get_issue").allowed);
989 }
990
991 #[test]
992 fn settings_billing_tokens_and_members_are_never_reachable() {
993 for kind in RunCredentialKind::ALL {
994 for usage in [Runner, Tools] {
995 for operation in NEVER.iter().copied() {
996 let decision = op(kind, usage, operation);
997 assert!(!decision.allowed);
998 assert_eq!(decision.rule, "never");
999 }
1000 }
1001 }
1002 // Even a scope that lists one is refused.
1003 let mut wide = scope(K::Implement, Tools);
1004 wide.operations.push("merge_pull_request".to_owned());
1005 let user = agent(&["acme"], wide.clone());
1006 let decision = decide_operation(
1007 &user,
1008 &wide,
1009 "merge_pull_request",
1010 Some(&path("acme", "rocket")),
1011 true,
1012 Some(7),
1013 );
1014 assert_eq!(decision.rule, "never");
1015 }
1016
1017 #[test]
1018 fn another_repository_is_refused() {
1019 let scope = scope(K::Implement, Tools);
1020 let user = agent(&["acme"], scope.clone());
1021 let decision = decide_operation(
1022 &user,
1023 &scope,
1024 "create_issue",
1025 Some(&path("acme", "other")),
1026 true,
1027 None,
1028 );
1029 assert!(!decision.allowed);
1030 assert_eq!(decision.rule, "scope:repository");
1031 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
1032 assert_eq!(decision.rule, "scope:repository");
1033 // The repository's name is matched without regard to case.
1034 let decision = decide_operation(
1035 &user,
1036 &scope,
1037 "create_issue",
1038 Some(&path("Acme", "Rocket")),
1039 true,
1040 None,
1041 );
1042 assert!(decision.allowed);
1043 assert_eq!(decision.rule, "run:implement/tools");
1044 }
1045
1046 #[test]
1047 fn the_permission_is_the_intersection_with_the_person() {
1048 let scope = scope(K::Implement, Tools);
1049 // The person left the workspace: their agent can do nothing there.
1050 let user = agent(&[], scope.clone());
1051 let decision = decide_operation(
1052 &user,
1053 &scope,
1054 "get_issue",
1055 Some(&path("acme", "rocket")),
1056 true,
1057 Some(1),
1058 );
1059 assert!(!decision.allowed);
1060 assert_eq!(decision.rule, "on-behalf-of:membership");
1061 // And an owner's agent is only ever a member.
1062 let owner = vec![
1063 Membership {
1064 slug: "acme".to_owned(),
1065 role: Role::Owner,
1066 name: None,
1067 avatar: None,
1068 base_permission: Some(BasePermission::None),
1069 team_creation: None,
1070 org_roles: vec![crate::OrgRole::SecurityManager],
1071 privileges: None,
1072 },
1073 Membership::member("elsewhere"),
1074 ];
1075 let memberships = intersect(&owner, "Acme");
1076 assert_eq!(memberships.len(), 1);
1077 assert_eq!(memberships[0].slug, "acme");
1078 assert_eq!(memberships[0].role, Role::Member);
1079 assert!(memberships[0].org_roles.is_empty());
1080 assert!(intersect(&owner, "nowhere").is_empty());
1081 }
1082
1083 /// An agent gets at most the person's role on the repository, and
1084 /// never more than Write; nothing outside the run's workspace.
1085 #[test]
1086 fn an_agent_has_at_most_its_persons_role() {
1087 use crate::access::{Capability, RepoRef, can, permission};
1088 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
1089 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
1090 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
1091 let tools = scope(K::Implement, Tools);
1092 let scope = scope(K::Implement, Runner);
1093 // An owner's agent: Write, never Admin.
1094 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
1095 let mut agent_user = agent(&[], scope.clone());
1096 agent_user.workspaces = intersect(&owner, "acme");
1097 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1098 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
1099 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1100 // A member whose workspace gives Read: Read, so it cannot push.
1101 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
1102 agent_user.workspaces = intersect(&reader, "acme");
1103 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
1104 assert!(!can(Some(&agent_user), rocket, Capability::Push));
1105 // An outside collaborator with Maintain on one repository: Write
1106 // there, nothing elsewhere, and the run is allowed.
1107 let grants = [
1108 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain, team: None },
1109 RepoGrant { repo_id: "rep_3".into(), workspace: "globex".into(), role: RepoRole::Admin, team: None },
1110 ];
1111 agent_user.workspaces = intersect(&[], "acme");
1112 agent_user.grants = intersect_grants(&grants, "Acme");
1113 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1114 assert_eq!(permission(Some(&agent_user), other), None);
1115 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1116 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
1117 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
1118 // The person, downstream of a runner's credential, carries the same.
1119 let person = as_person(&agent_user).expect("a runner acts as the person");
1120 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
1121 }
1122
1123 #[test]
1124 fn a_runner_changes_only_its_own_pull_request() {
1125 let scope = scope(K::Implement, Runner);
1126 let user = agent(&["acme"], scope.clone());
1127 let repo = path("acme", "rocket");
1128 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1129 assert!(!other.allowed);
1130 assert_eq!(other.rule, "scope:pull");
1131 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1132 assert!(own.allowed);
1133 // Reading another is fine.
1134 assert!(
1135 decide_operation(
1136 &user,
1137 &scope,
1138 "get_pull_request",
1139 Some(&repo),
1140 true,
1141 Some(8)
1142 )
1143 .allowed
1144 );
1145 }
1146
1147 #[test]
1148 fn git_matrix() {
1149 let fork = path("pulls", "pul_7");
1150 let upstream = path("acme", "rocket");
1151 let elsewhere = path("acme", "billing");
1152 let implement = scope(K::Implement, Runner);
1153 assert!(decide_git(&implement, &fork, true).allowed);
1154 assert!(decide_git(&implement, &fork, false).allowed);
1155 assert!(decide_git(&implement, &upstream, false).allowed);
1156 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1157 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1158 let review = scope(K::Review, Runner);
1159 assert!(decide_git(&review, &upstream, false).allowed);
1160 assert!(!decide_git(&review, &upstream, true).allowed);
1161 assert!(!decide_git(&review, &fork, true).allowed);
1162 // A tools token made before run credentials never reaches git.
1163 let old = AgentScope {
1164 repo: upstream.clone(),
1165 operations: vec!["get_issue".to_owned()],
1166 run: None,
1167 };
1168 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1169 // Nor does an agent's tools token.
1170 assert_eq!(
1171 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1172 "git:not-a-run"
1173 );
1174 }
1175
1176 #[test]
1177 fn a_push_moves_only_granted_branches() {
1178 let update = scope(K::Update, Runner);
1179 let repo = path("acme", "rocket");
1180 let refs = |names: &[&str]| {
1181 names
1182 .iter()
1183 .map(|name| (*name).to_owned())
1184 .collect::<Vec<_>>()
1185 };
1186 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1187 assert_eq!(
1188 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1189 "git:ref"
1190 );
1191 assert_eq!(
1192 decide_refs(
1193 &update,
1194 &repo,
1195 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1196 )
1197 .rule,
1198 "git:ref"
1199 );
1200 let implement = scope(K::Implement, Runner);
1201 assert!(
1202 decide_refs(
1203 &implement,
1204 &path("pulls", "pul_7"),
1205 &refs(&["refs/heads/main"])
1206 )
1207 .allowed
1208 );
1209 }
1210
1211 #[test]
1212 fn a_runner_acts_downstream_as_the_person() {
1213 let user = agent(&["acme"], scope(K::Implement, Runner));
1214 let person = as_person(&user).unwrap();
1215 assert_eq!(person.id, "usr_1");
1216 assert_eq!(person.username, "syntaqx");
1217 assert_eq!(person.kind, PrincipalKind::User);
1218 assert!(person.is_member("acme"));
1219 assert!(person.acting.is_none());
1220 assert_eq!(describe(&user), "g1t on behalf of syntaqx");
1221 // The tools act as the agent.
1222 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1223 }
1224
1225 #[test]
1226 fn scopes_without_a_run_still_parse() {
1227 let old: AgentScope = serde_json::from_str(
1228 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1229 )
1230 .unwrap();
1231 assert!(old.run.is_none());
1232 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1233 assert!(written.contains(r#""use":"tools""#));
1234 assert!(written.contains(r#""kind":"review""#));
1235 let back: AgentScope = serde_json::from_str(&written).unwrap();
1236 assert_eq!(back.run.unwrap().kind, K::Review);
1237 // Only g1t's own runs say so; every other reads as not.
1238 assert!(!written.contains("system"));
1239 assert!(!back_run(&written).system);
1240 let mut own = scope(K::Bump, Runner);
1241 own.run.as_mut().unwrap().system = true;
1242 let written = serde_json::to_string(&own).unwrap();
1243 assert!(written.contains(r#""system":true"#));
1244 assert!(back_run(&written).system);
1245 }
1246
1247 fn back_run(written: &str) -> RunBinding {
1248 serde_json::from_str::<AgentScope>(written).unwrap().run.unwrap()
1249 }
1250}