Skip to content

g1t/crates/contracts/src/credentials.rs

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