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