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.

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