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