Skip to content
1,335 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 // Nor answers a workspace invitation: only the person it is for does.
406 "accept_invitation",
407 "decline_invitation",
408 "set_base_permission",
409 "list_outside_collaborators",
410 // Deploy keys, which let a machine into a repository.
411 "list_deploy_keys",
412 "get_deploy_key",
413 "create_deploy_key",
414 "delete_deploy_key",
415 // Moving a repository to g1t for good, and a remote's token and
416 // levers, are a person's to decide.
417 "move_mirror_to_g1t",
418 "add_mirror_remote",
419 "update_mirror_remote",
420 "remove_mirror_remote",
421 // Teams: who is in which, and what they reach, is for people.
422 "create_team",
423 "update_team",
424 "delete_team",
425 "set_team_member",
426 "remove_team_member",
427 "set_team_repo",
428 "remove_team_repo",
429 "set_team_review_assignment",
430 // Dismissing a secret lets it through push protection.
431 "dismiss_security_alert",
432 "reopen_security_alert",
433 // Nor any other decision about security: closing or reopening an
434 // alert, pushing past push protection or deciding who may, changing
435 // what is looked for or when checks fail, or putting more agents to
436 // work. An agent fixes what it finds in its own pull request.
437 "update_secret_scanning_alert",
438 "bypass_push_protection",
439 "review_bypass_request",
440 "create_custom_pattern",
441 "update_custom_pattern",
442 "delete_custom_pattern",
443 "update_code_scanning_alert",
444 "update_vulnerability_alert",
445 "fix_security_alert",
446 "update_security_settings",
447 "update_workspace_security_settings",
448 // A person's own inbox: g1t's agents act as g1t, which has none.
449 "list_notifications",
450 "get_notification_thread",
451 "mark_notifications_read",
452 "mark_thread_read",
453 "mark_thread_done",
454 "save_thread",
455 "snooze_thread",
456 "get_thread_subscription",
457 "set_thread_subscription",
458 "delete_thread_subscription",
459 "get_repo_subscription",
460 "set_repo_subscription",
461 "delete_repo_subscription",
462 "list_watched_repos",
463 // Pins are a person's own, as the inbox is.
464 "list_pinned_projects",
465 "pin_project",
466 "unpin_project",
467 "reorder_pinned_projects",
468 // Deleting packages and deciding who may use them is for people: an
469 // agent publishes its repository's packages and never deletes them.
470 "update_package",
471 "link_package",
472 "unlink_package",
473 "set_package_access",
474 "remove_package_access",
475 "set_package_actions_access",
476 "remove_package_actions_access",
477 "delete_package",
478 "restore_package",
479 "delete_package_version",
480 "restore_package_version",
481 // Sharing an artifact and deleting one for good are for people: an
482 // agent shares only through the agents service, with the people
483 // already in its conversation.
484 "set_workspace_artifact_access",
485 "purge_workspace_artifact",
486];
487
488/// Reading what an agent needs to know about its repository.
489const TOOLS_READ: &[&str] = &[
490 "get_repo",
491 "list_issues",
492 "get_issue",
493 "list_labels",
494 "list_issue_labels",
495 "list_milestones",
496 "get_milestone",
497 "list_pull_requests",
498 "get_pull_request",
499 "get_pull_request_changes",
500 "read_session",
501 "get_merge_queue",
502 "list_events",
503 "recall",
504 "search_context",
505 "get_entity",
506 "search",
507 "list_workflows",
508 "list_workflow_runs",
509 "get_workflow_run",
510 "get_job_logs",
511 "get_pending_deployments",
512 "get_workflow_permissions",
513 "get_fork_pr_approval",
514 "list_commit_statuses",
515 "get_combined_status",
516 "list_check_runs_for_ref",
517 "get_check_run",
518 "list_check_run_annotations",
519 "list_check_suites_for_ref",
520 "get_check_suite",
521];
522
523pub fn is_read(operation: &str) -> bool {
524 READ_OPERATIONS.contains(&operation)
525}
526
527/// The API and MCP operations a run of `kind` may use with a credential
528/// for `usage`. Git is separate: see [`decide_git`].
529pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
530 use RunCredentialKind as K;
531 let mut operations: Vec<&'static str> = Vec::new();
532 match usage {
533 CredentialUse::Runner => {
534 if kind.works_on_a_pull() {
535 operations.extend(["get_repo", "get_pull_request", "record_session"]);
536 }
537 if kind == K::Implement {
538 operations.push("mark_pull_request_ready");
539 }
540 }
541 CredentialUse::Tools => match kind {
542 K::Implement | K::Revise | K::Answer => {
543 operations.extend(TOOLS_READ.iter().copied());
544 operations.extend([
545 "create_issue",
546 "add_comment",
547 "take_messages",
548 "remember",
549 "message_agent",
550 "answer_message",
551 "get_context",
552 ]);
553 }
554 K::Review => {
555 operations.extend(TOOLS_READ.iter().copied());
556 operations.extend(["add_comment", "review_pull_request", "get_context"]);
557 }
558 K::Plan => {
559 operations.extend(TOOLS_READ.iter().copied());
560 operations.extend(["create_issue", "get_context"]);
561 }
562 K::Update => operations.extend(TOOLS_READ.iter().copied()),
563 K::Checks | K::Queue | K::Mergecheck | K::Deploy | K::Bump => {}
564 },
565 }
566 operations
567}
568
569/// What a run's credential may do, in the scope vocabulary that access
570/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
571/// for a runner, git's. Its operations, its repository and its run still
572/// bound it more tightly than these scopes say.
573pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
574 use crate::scopes::{Scope, normalize, scope_for};
575 let mut scopes: Vec<Scope> = operations_for(kind, usage)
576 .into_iter()
577 .filter_map(scope_for)
578 .collect();
579 if usage == CredentialUse::Runner {
580 scopes.push(Scope::CodeRead);
581 if matches!(
582 kind,
583 RunCredentialKind::Implement
584 | RunCredentialKind::Revise
585 | RunCredentialKind::Answer
586 | RunCredentialKind::Update
587 | RunCredentialKind::Bump
588 ) {
589 scopes.push(Scope::CodeWrite);
590 }
591 }
592 normalize(&mut scopes);
593 scopes
594}
595
596/// Operations that change a pull request, which a runner may do only to
597/// the pull request its run works on.
598const PULL_WRITES: &[&str] = &["record_session", "mark_pull_request_ready"];
599
600/// Whether something was allowed, and the rule that decided it.
601#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
602pub struct Decision {
603 pub allowed: bool,
604 /// A short, stable name: `run:implement/tools`, `never`,
605 /// `scope:repository` and so on. Shown in the audit log.
606 pub rule: String,
607 /// Why it was refused, for the caller.
608 #[serde(default, skip_serializing_if = "Option::is_none")]
609 pub reason: Option<String>,
610}
611
612impl Decision {
613 pub fn allow(rule: impl Into<String>) -> Self {
614 Decision {
615 allowed: true,
616 rule: rule.into(),
617 reason: None,
618 }
619 }
620
621 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
622 Decision {
623 allowed: false,
624 rule: rule.into(),
625 reason: Some(reason.into()),
626 }
627 }
628}
629
630fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
631 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
632}
633
634fn scope_rule(scope: &AgentScope) -> String {
635 match &scope.run {
636 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
637 None => "agent-token".to_owned(),
638 }
639}
640
641/// Whether `user`, resolved from an agent's token with `scope`, may use
642/// `operation`. `repo` is the repository the call names, if any, and
643/// `needs_repo` whether the operation is about one; `number` the issue or
644/// pull request it names.
645pub fn decide_operation(
646 user: &User,
647 scope: &AgentScope,
648 operation: &str,
649 repo: Option<&RepoPath>,
650 needs_repo: bool,
651 number: Option<u32>,
652) -> Decision {
653 let who = "A g1t agent's token";
654 if NEVER.contains(&operation) {
655 return Decision::deny(
656 "never",
657 format!(
658 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
659 ),
660 );
661 }
662 if !scope.operations.iter().any(|name| name == operation) {
663 return Decision::deny(
664 "scope:operation",
665 format!("{who} for this run cannot use {operation}."),
666 );
667 }
668 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
669 return Decision::deny(
670 "scope:repository",
671 format!(
672 "{who} works in {}/{} only.",
673 scope.repo.namespace, scope.repo.name
674 ),
675 );
676 }
677 // The intersection: the person it acts for must still be able to work
678 // in the repository's workspace, as a member or with a role on its
679 // repositories. What it may do in the repository itself is their
680 // role there, which services check (`access::can`).
681 if !crate::access::has_access_in(user, &scope.repo.namespace) {
682 return Decision::deny(
683 "on-behalf-of:membership",
684 format!(
685 "The person this agent works for is no longer a member of {}.",
686 scope.repo.namespace
687 ),
688 );
689 }
690 if let Some(run) = &scope.run
691 && run.usage == CredentialUse::Runner
692 && PULL_WRITES.contains(&operation)
693 && run.number.is_some()
694 && number != run.number
695 {
696 return Decision::deny(
697 "scope:pull",
698 format!(
699 "{who} can change pull request #{} only.",
700 run.number.unwrap_or_default()
701 ),
702 );
703 }
704 Decision::allow(scope_rule(scope))
705}
706
707/// Whether a run credential may clone or fetch (`write` false), or push to
708/// (`write` true), the repository at `repo`.
709pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
710 let Some(run) = scope
711 .run
712 .as_ref()
713 .filter(|run| run.usage == CredentialUse::Runner)
714 else {
715 return Decision::deny(
716 "git:not-a-run",
717 "A g1t agent's tools token cannot be used with git.",
718 );
719 };
720 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
721 if write {
722 return if pushable {
723 Decision::allow(format!("{}:push", scope_rule(scope)))
724 } else {
725 Decision::deny(
726 "git:push",
727 format!(
728 "A {} run cannot push to {}/{}.",
729 run.kind.as_str(),
730 repo.namespace,
731 repo.name
732 ),
733 )
734 };
735 }
736 let readable = pushable
737 || same_repo(&scope.repo, repo)
738 || run.read.iter().any(|path| same_repo(path, repo));
739 if readable {
740 Decision::allow(format!("{}:read", scope_rule(scope)))
741 } else {
742 Decision::deny(
743 "git:read",
744 format!(
745 "A {} run cannot read {}/{}.",
746 run.kind.as_str(),
747 repo.namespace,
748 repo.name
749 ),
750 )
751 }
752}
753
754/// Whether a push to `repo` is limited to certain branches, so that the
755/// refs it moves have to be read and checked with [`decide_refs`].
756pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
757 scope
758 .run
759 .iter()
760 .flat_map(|run| run.push.iter())
761 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
762}
763
764/// Whether a push to `repo` may move `refs` (full refs, such as
765/// `refs/heads/main`). Tags are never a run's to move.
766pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
767 let repo_decision = decide_git(scope, repo, true);
768 if !repo_decision.allowed {
769 return repo_decision;
770 }
771 let grants: Vec<&GitGrant> = scope
772 .run
773 .iter()
774 .flat_map(|run| run.push.iter())
775 .filter(|grant| same_repo(&grant.repo, repo))
776 .collect();
777 for git_ref in refs {
778 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
779 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
780 };
781 let allowed = grants
782 .iter()
783 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
784 if !allowed {
785 return Decision::deny(
786 "git:ref",
787 format!(
788 "A run cannot push to {branch} in {}/{}.",
789 repo.namespace, repo.name
790 ),
791 );
792 }
793 }
794 repo_decision
795}
796
797/// The most an agent may be on a repository, whoever it works for: it
798/// can push, merge and run, never change settings or who has access.
799pub const AGENT_CEILING: RepoRole = RepoRole::Write;
800
801/// The memberships an agent working for `person` has: the run's
802/// workspace, as a member, only if the person is in it now, with the
803/// person's role on its repositories (an owner's Admin included) cut down
804/// to [`AGENT_CEILING`].
805pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
806 let namespace = namespace.to_lowercase();
807 person
808 .iter()
809 .filter(|membership| membership.slug == namespace)
810 .map(|membership| {
811 let base = match membership.role {
812 Role::Owner => BasePermission::Admin,
813 Role::Member => membership.base_permission.unwrap_or_default(),
814 };
815 Membership {
816 role: Role::Member,
817 base_permission: Some(match base {
818 BasePermission::Admin => BasePermission::Write,
819 base => base,
820 }),
821 // Billing and security manager are the person's, never
822 // their agent's.
823 org_roles: Vec::new(),
824 ..membership.clone()
825 }
826 })
827 .collect()
828}
829
830/// The repository grants an agent working for `person` has: those in the
831/// run's workspace, each cut down to [`AGENT_CEILING`].
832pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
833 let namespace = namespace.to_lowercase();
834 person
835 .iter()
836 .filter(|grant| grant.workspace == namespace)
837 .map(|grant| RepoGrant {
838 role: grant.role.min(AGENT_CEILING),
839 ..grant.clone()
840 })
841 .collect()
842}
843
844/// Who a runner's credential acts as downstream: the person, with only the
845/// agent's (already intersected) memberships. `None` for anything else.
846pub fn as_person(user: &User) -> Option<User> {
847 let acting = user.acting.as_ref()?;
848 if user.kind != PrincipalKind::Agent {
849 return None;
850 }
851 let run = acting.run()?;
852 if run.usage != CredentialUse::Runner {
853 return None;
854 }
855 Some(User {
856 id: acting.on_behalf_of.id.clone(),
857 username: acting.on_behalf_of.username.clone(),
858 display_username: None,
859 kind: PrincipalKind::User,
860 verified: user.verified,
861 workspaces: user.workspaces.clone(),
862 avatar: None,
863 acting: None,
864 grants: user.grants.clone(),
865 token: None,
866 held: Vec::new(),
867 })
868}
869
870/// How an actor is described: "g1t on behalf of syntaqx".
871pub fn describe(user: &User) -> String {
872 match &user.acting {
873 Some(acting) => format!(
874 "{} on behalf of {}",
875 acting.agent, acting.on_behalf_of.username
876 ),
877 None => user.username.clone(),
878 }
879}
880
881#[cfg(test)]
882mod tests {
883 use super::*;
884
885 #[test]
886 fn a_run_s_scopes_are_never_admin() {
887 for kind in RunCredentialKind::ALL {
888 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
889 let scopes = run_scopes(kind, usage);
890 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
891 }
892 }
893 let review = run_scopes(RunCredentialKind::Review, CredentialUse::Tools);
894 assert!(review.contains(&crate::scopes::Scope::PullRequestsWrite));
895 assert!(!review.contains(&crate::scopes::Scope::CodeWrite));
896 }
897
898 #[test]
899 fn agents_can_search_the_context_hub() {
900 for kind in [RunCredentialKind::Implement, RunCredentialKind::Review, RunCredentialKind::Plan] {
901 let tools = operations_for(kind, CredentialUse::Tools);
902 assert!(tools.contains(&"search_context") && tools.contains(&"get_entity"));
903 }
904 assert!(is_read("search_context") && is_read("get_entity"));
905 }
906
907 #[test]
908 fn agents_can_search_all_of_g1t() {
909 // Site-wide search only reads: every run that reads its repository
910 // may use it, and nothing that never reads gets it.
911 assert!(is_read("search"));
912 assert!(!NEVER.contains(&"search"));
913 for kind in [
914 RunCredentialKind::Implement,
915 RunCredentialKind::Revise,
916 RunCredentialKind::Answer,
917 RunCredentialKind::Review,
918 RunCredentialKind::Plan,
919 RunCredentialKind::Update,
920 ] {
921 let tools = operations_for(kind, CredentialUse::Tools);
922 assert!(tools.contains(&"search"), "{kind:?} should search");
923 // The context hub's search stays its own tool beside it.
924 assert!(tools.contains(&"search_context"), "{kind:?} keeps search_context");
925 }
926 for kind in [RunCredentialKind::Checks, RunCredentialKind::Queue, RunCredentialKind::Mergecheck, RunCredentialKind::Deploy, RunCredentialKind::Bump] {
927 assert!(!operations_for(kind, CredentialUse::Tools).contains(&"search"));
928 }
929 assert!(!operations_for(RunCredentialKind::Implement, CredentialUse::Runner).contains(&"search"));
930 }
931
932 fn path(namespace: &str, name: &str) -> RepoPath {
933 RepoPath {
934 namespace: namespace.to_owned(),
935 name: name.to_owned(),
936 }
937 }
938
939 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
940 AgentScope {
941 repo: path("acme", "rocket"),
942 operations: operations_for(kind, usage)
943 .into_iter()
944 .map(str::to_owned)
945 .collect(),
946 run: Some(RunBinding {
947 kind,
948 usage,
949 run_id: Some("run_1".to_owned()),
950 number: Some(7),
951 agent: "g1t".to_owned(),
952 system: false,
953 read: vec![path("acme", "rocket")],
954 push: match kind {
955 RunCredentialKind::Implement
956 | RunCredentialKind::Revise
957 | RunCredentialKind::Answer => vec![GitGrant {
958 repo: path("pulls", "pul_7"),
959 branch: None,
960 }],
961 RunCredentialKind::Update => vec![GitGrant {
962 repo: path("acme", "rocket"),
963 branch: Some("fix-login".to_owned()),
964 }],
965 _ => vec![],
966 },
967 }),
968 }
969 }
970
971 fn agent(member_of: &[&str], scope: AgentScope) -> User {
972 User {
973 id: "usr_g1t_agent".to_owned(),
974 username: "g1t".to_owned(),
975 display_username: None,
976 kind: PrincipalKind::Agent,
977 verified: true,
978 workspaces: member_of
979 .iter()
980 .map(|slug| Membership::member(*slug))
981 .collect(),
982 avatar: None,
983 grants: Vec::new(),
984 token: None,
985 held: Vec::new(),
986 acting: Some(Box::new(Acting {
987 credential_id: "tok_1".to_owned(),
988 agent: "g1t".to_owned(),
989 on_behalf_of: Principal {
990 id: "usr_1".to_owned(),
991 username: "syntaqx".to_owned(),
992 },
993 scope,
994 })),
995 }
996 }
997
998 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
999 let scope = scope(kind, usage);
1000 let user = agent(&["acme"], scope.clone());
1001 decide_operation(
1002 &user,
1003 &scope,
1004 operation,
1005 Some(&path("acme", "rocket")),
1006 true,
1007 Some(7),
1008 )
1009 }
1010
1011 use CredentialUse::{Runner, Tools};
1012 use RunCredentialKind as K;
1013
1014 /// Which operations each kind of run may use through its tools: the
1015 /// allowed and denied matrix.
1016 #[test]
1017 fn tools_matrix() {
1018 let cases: [(&str, [bool; 6]); 12] = [
1019 // implement revise answer review plan checks
1020 ("get_issue", [true, true, true, true, true, false]),
1021 ("create_issue", [true, true, true, false, true, false]),
1022 ("add_comment", [true, true, true, true, false, false]),
1023 (
1024 "review_pull_request",
1025 [false, false, false, true, false, false],
1026 ),
1027 ("remember", [true, true, true, false, false, false]),
1028 ("take_messages", [true, true, true, false, false, false]),
1029 ("record_session", [false, false, false, false, false, false]),
1030 (
1031 "merge_pull_request",
1032 [false, false, false, false, false, false],
1033 ),
1034 (
1035 "update_repo_settings",
1036 [false, false, false, false, false, false],
1037 ),
1038 ("create_webhook", [false, false, false, false, false, false]),
1039 (
1040 "set_actions_secret",
1041 [false, false, false, false, false, false],
1042 ),
1043 ("assign_issue", [false, false, false, false, false, false]),
1044 ];
1045 let kinds = [
1046 K::Implement,
1047 K::Revise,
1048 K::Answer,
1049 K::Review,
1050 K::Plan,
1051 K::Checks,
1052 ];
1053 for (operation, expected) in cases {
1054 for (kind, allowed) in kinds.into_iter().zip(expected) {
1055 assert_eq!(
1056 op(kind, Tools, operation).allowed,
1057 allowed,
1058 "{operation} by a {} run's tools",
1059 kind.as_str()
1060 );
1061 }
1062 }
1063 }
1064
1065 #[test]
1066 fn runner_matrix() {
1067 assert!(op(K::Implement, Runner, "record_session").allowed);
1068 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
1069 assert!(op(K::Revise, Runner, "record_session").allowed);
1070 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
1071 assert!(!op(K::Implement, Runner, "create_issue").allowed);
1072 assert!(!op(K::Review, Runner, "record_session").allowed);
1073 assert!(!op(K::Checks, Runner, "get_issue").allowed);
1074 }
1075
1076 #[test]
1077 fn settings_billing_tokens_and_members_are_never_reachable() {
1078 for kind in RunCredentialKind::ALL {
1079 for usage in [Runner, Tools] {
1080 for operation in NEVER.iter().copied() {
1081 let decision = op(kind, usage, operation);
1082 assert!(!decision.allowed);
1083 assert_eq!(decision.rule, "never");
1084 }
1085 }
1086 }
1087 // Even a scope that lists one is refused.
1088 let mut wide = scope(K::Implement, Tools);
1089 wide.operations.push("merge_pull_request".to_owned());
1090 let user = agent(&["acme"], wide.clone());
1091 let decision = decide_operation(
1092 &user,
1093 &wide,
1094 "merge_pull_request",
1095 Some(&path("acme", "rocket")),
1096 true,
1097 Some(7),
1098 );
1099 assert_eq!(decision.rule, "never");
1100 }
1101
1102 #[test]
1103 fn another_repository_is_refused() {
1104 let scope = scope(K::Implement, Tools);
1105 let user = agent(&["acme"], scope.clone());
1106 let decision = decide_operation(
1107 &user,
1108 &scope,
1109 "create_issue",
1110 Some(&path("acme", "other")),
1111 true,
1112 None,
1113 );
1114 assert!(!decision.allowed);
1115 assert_eq!(decision.rule, "scope:repository");
1116 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
1117 assert_eq!(decision.rule, "scope:repository");
1118 // The repository's name is matched without regard to case.
1119 let decision = decide_operation(
1120 &user,
1121 &scope,
1122 "create_issue",
1123 Some(&path("Acme", "Rocket")),
1124 true,
1125 None,
1126 );
1127 assert!(decision.allowed);
1128 assert_eq!(decision.rule, "run:implement/tools");
1129 }
1130
1131 #[test]
1132 fn the_permission_is_the_intersection_with_the_person() {
1133 let scope = scope(K::Implement, Tools);
1134 // The person left the workspace: their agent can do nothing there.
1135 let user = agent(&[], scope.clone());
1136 let decision = decide_operation(
1137 &user,
1138 &scope,
1139 "get_issue",
1140 Some(&path("acme", "rocket")),
1141 true,
1142 Some(1),
1143 );
1144 assert!(!decision.allowed);
1145 assert_eq!(decision.rule, "on-behalf-of:membership");
1146 // And an owner's agent is only ever a member.
1147 let owner = vec![
1148 Membership {
1149 slug: "acme".to_owned(),
1150 role: Role::Owner,
1151 name: None,
1152 avatar: None,
1153 base_permission: Some(BasePermission::None),
1154 team_creation: None,
1155 org_roles: vec![crate::OrgRole::SecurityManager],
1156 privileges: None,
1157 },
1158 Membership::member("elsewhere"),
1159 ];
1160 let memberships = intersect(&owner, "Acme");
1161 assert_eq!(memberships.len(), 1);
1162 assert_eq!(memberships[0].slug, "acme");
1163 assert_eq!(memberships[0].role, Role::Member);
1164 assert!(memberships[0].org_roles.is_empty());
1165 assert!(intersect(&owner, "nowhere").is_empty());
1166 }
1167
1168 /// An agent gets at most the person's role on the repository, and
1169 /// never more than Write; nothing outside the run's workspace.
1170 #[test]
1171 fn an_agent_has_at_most_its_persons_role() {
1172 use crate::access::{Capability, RepoRef, can, permission};
1173 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
1174 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
1175 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
1176 let tools = scope(K::Implement, Tools);
1177 let scope = scope(K::Implement, Runner);
1178 // An owner's agent: Write, never Admin.
1179 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
1180 let mut agent_user = agent(&[], scope.clone());
1181 agent_user.workspaces = intersect(&owner, "acme");
1182 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1183 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
1184 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1185 // A member whose workspace gives Read: Read, so it cannot push.
1186 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
1187 agent_user.workspaces = intersect(&reader, "acme");
1188 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
1189 assert!(!can(Some(&agent_user), rocket, Capability::Push));
1190 // An outside collaborator with Maintain on one repository: Write
1191 // there, nothing elsewhere, and the run is allowed.
1192 let grants = [
1193 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain, team: None },
1194 RepoGrant { repo_id: "rep_3".into(), workspace: "globex".into(), role: RepoRole::Admin, team: None },
1195 ];
1196 agent_user.workspaces = intersect(&[], "acme");
1197 agent_user.grants = intersect_grants(&grants, "Acme");
1198 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1199 assert_eq!(permission(Some(&agent_user), other), None);
1200 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1201 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
1202 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
1203 // The person, downstream of a runner's credential, carries the same.
1204 let person = as_person(&agent_user).expect("a runner acts as the person");
1205 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
1206 }
1207
1208 #[test]
1209 fn a_runner_changes_only_its_own_pull_request() {
1210 let scope = scope(K::Implement, Runner);
1211 let user = agent(&["acme"], scope.clone());
1212 let repo = path("acme", "rocket");
1213 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1214 assert!(!other.allowed);
1215 assert_eq!(other.rule, "scope:pull");
1216 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1217 assert!(own.allowed);
1218 // Reading another is fine.
1219 assert!(
1220 decide_operation(
1221 &user,
1222 &scope,
1223 "get_pull_request",
1224 Some(&repo),
1225 true,
1226 Some(8)
1227 )
1228 .allowed
1229 );
1230 }
1231
1232 #[test]
1233 fn git_matrix() {
1234 let fork = path("pulls", "pul_7");
1235 let upstream = path("acme", "rocket");
1236 let elsewhere = path("acme", "billing");
1237 let implement = scope(K::Implement, Runner);
1238 assert!(decide_git(&implement, &fork, true).allowed);
1239 assert!(decide_git(&implement, &fork, false).allowed);
1240 assert!(decide_git(&implement, &upstream, false).allowed);
1241 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1242 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1243 let review = scope(K::Review, Runner);
1244 assert!(decide_git(&review, &upstream, false).allowed);
1245 assert!(!decide_git(&review, &upstream, true).allowed);
1246 assert!(!decide_git(&review, &fork, true).allowed);
1247 // A tools token made before run credentials never reaches git.
1248 let old = AgentScope {
1249 repo: upstream.clone(),
1250 operations: vec!["get_issue".to_owned()],
1251 run: None,
1252 };
1253 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1254 // Nor does an agent's tools token.
1255 assert_eq!(
1256 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1257 "git:not-a-run"
1258 );
1259 }
1260
1261 #[test]
1262 fn a_push_moves_only_granted_branches() {
1263 let update = scope(K::Update, Runner);
1264 let repo = path("acme", "rocket");
1265 let refs = |names: &[&str]| {
1266 names
1267 .iter()
1268 .map(|name| (*name).to_owned())
1269 .collect::<Vec<_>>()
1270 };
1271 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1272 assert_eq!(
1273 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1274 "git:ref"
1275 );
1276 assert_eq!(
1277 decide_refs(
1278 &update,
1279 &repo,
1280 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1281 )
1282 .rule,
1283 "git:ref"
1284 );
1285 let implement = scope(K::Implement, Runner);
1286 assert!(
1287 decide_refs(
1288 &implement,
1289 &path("pulls", "pul_7"),
1290 &refs(&["refs/heads/main"])
1291 )
1292 .allowed
1293 );
1294 }
1295
1296 #[test]
1297 fn a_runner_acts_downstream_as_the_person() {
1298 let user = agent(&["acme"], scope(K::Implement, Runner));
1299 let person = as_person(&user).unwrap();
1300 assert_eq!(person.id, "usr_1");
1301 assert_eq!(person.username, "syntaqx");
1302 assert_eq!(person.kind, PrincipalKind::User);
1303 assert!(person.is_member("acme"));
1304 assert!(person.acting.is_none());
1305 assert_eq!(describe(&user), "g1t on behalf of syntaqx");
1306 // The tools act as the agent.
1307 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1308 }
1309
1310 #[test]
1311 fn scopes_without_a_run_still_parse() {
1312 let old: AgentScope = serde_json::from_str(
1313 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1314 )
1315 .unwrap();
1316 assert!(old.run.is_none());
1317 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1318 assert!(written.contains(r#""use":"tools""#));
1319 assert!(written.contains(r#""kind":"review""#));
1320 let back: AgentScope = serde_json::from_str(&written).unwrap();
1321 assert_eq!(back.run.unwrap().kind, K::Review);
1322 // Only g1t's own runs say so; every other reads as not.
1323 assert!(!written.contains("system"));
1324 assert!(!back_run(&written).system);
1325 let mut own = scope(K::Bump, Runner);
1326 own.run.as_mut().unwrap().system = true;
1327 let written = serde_json::to_string(&own).unwrap();
1328 assert!(written.contains(r#""system":true"#));
1329 assert!(back_run(&written).system);
1330 }
1331
1332 fn back_run(written: &str) -> RunBinding {
1333 serde_json::from_str::<AgentScope>(written).unwrap().run.unwrap()
1334 }
1335}