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