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