Skip to content

g1t/crates/contracts/src/credentials.rs

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