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