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