g1t/crates/contracts/src/credentials.rs

1,111 lines39,136 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}
37
38impl RunCredentialKind {
39 pub const ALL: [RunCredentialKind; 10] = [
40 RunCredentialKind::Implement,
41 RunCredentialKind::Revise,
42 RunCredentialKind::Review,
43 RunCredentialKind::Answer,
44 RunCredentialKind::Update,
45 RunCredentialKind::Plan,
46 RunCredentialKind::Checks,
47 RunCredentialKind::Queue,
48 RunCredentialKind::Mergecheck,
49 RunCredentialKind::Deploy,
50 ];
51
52 pub fn as_str(self) -> &'static str {
53 match self {
54 RunCredentialKind::Implement => "implement",
55 RunCredentialKind::Revise => "revise",
56 RunCredentialKind::Review => "review",
57 RunCredentialKind::Answer => "answer",
58 RunCredentialKind::Update => "update",
59 RunCredentialKind::Plan => "plan",
60 RunCredentialKind::Checks => "checks",
61 RunCredentialKind::Queue => "queue",
62 RunCredentialKind::Mergecheck => "mergecheck",
63 RunCredentialKind::Deploy => "deploy",
64 }
65 }
66
67 /// Whether the run works on one pull request, whose session and
68 /// readiness it reports.
69 fn works_on_a_pull(self) -> bool {
70 matches!(
71 self,
72 RunCredentialKind::Implement
73 | RunCredentialKind::Revise
74 | RunCredentialKind::Answer
75 | RunCredentialKind::Update
76 )
77 }
78}
79
80/// Which part of a sandbox a credential is for.
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub enum CredentialUse {
84 /// g1t's runner: cloning, pushing the result, recording the session.
85 /// It acts as the person downstream, so that what it pushes and records
86 /// is theirs, within the run's scope.
87 Runner,
88 /// The agent's own tools, over MCP. It acts as the agent.
89 Tools,
90}
91
92impl CredentialUse {
93 pub fn as_str(self) -> &'static str {
94 match self {
95 CredentialUse::Runner => "runner",
96 CredentialUse::Tools => "tools",
97 }
98 }
99}
100
101/// A repository a run may push to, and the one branch, if only one.
102#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
103pub struct GitGrant {
104 pub repo: RepoPath,
105 /// Null: any branch. A pull request's fork is its own repository, so
106 /// the whole of it is the pull request's.
107 #[serde(default)]
108 pub branch: Option<String>,
109}
110
111/// What binds an agent's token to one run. Absent on agent tokens made
112/// before run credentials, which keep working for the API only.
113#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "camelCase")]
115pub struct RunBinding {
116 pub kind: RunCredentialKind,
117 #[serde(rename = "use")]
118 pub usage: CredentialUse,
119 /// The agent run, once the sandbox has recorded it.
120 #[serde(default)]
121 pub run_id: Option<String>,
122 /// The pull request the run works on, for the kinds that work on one.
123 #[serde(default)]
124 pub number: Option<u32>,
125 /// The agent's name, such as `g1t-agent`.
126 pub agent: String,
127 /// Repositories it may clone and fetch, besides those it may push to.
128 #[serde(default)]
129 pub read: Vec<RepoPath>,
130 /// Where it may push.
131 #[serde(default)]
132 pub push: Vec<GitGrant>,
133}
134
135/// A person, by id and name.
136#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
137pub struct Principal {
138 pub id: String,
139 pub username: String,
140}
141
142/// Set on a [`User`] resolved from an agent's token: the composite
143/// identity, "g1t-agent on behalf of syntaqx", and what it may do.
144#[derive(Clone, Debug, Serialize, Deserialize)]
145#[serde(rename_all = "camelCase")]
146pub struct Acting {
147 /// The token's id, as audit entries name it.
148 pub credential_id: String,
149 pub agent: String,
150 pub on_behalf_of: Principal,
151 pub scope: AgentScope,
152}
153
154impl Acting {
155 pub fn run(&self) -> Option<&RunBinding> {
156 self.scope.run.as_ref()
157 }
158}
159
160/// `create_run_credential`: a token for one sandbox run. It acts as
161/// `agent` on behalf of `on_behalf_of`, can do only what `kind` and `usage`
162/// allow in `repo`, and expires after `ttl_seconds`, which should be the
163/// run's timeout. Returns `CreatedAccessToken`.
164#[derive(Clone, Debug, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166pub struct CreateRunCredentialArgs {
167 pub on_behalf_of: User,
168 pub repo: RepoPath,
169 pub kind: RunCredentialKind,
170 #[serde(rename = "use")]
171 pub usage: CredentialUse,
172 #[serde(default)]
173 pub number: Option<u32>,
174 #[serde(default)]
175 pub read: Vec<RepoPath>,
176 #[serde(default)]
177 pub push: Vec<GitGrant>,
178 pub ttl_seconds: u64,
179 /// Defaults to `g1t-agent`.
180 #[serde(default)]
181 pub agent: Option<String>,
182}
183
184/// `bind_run_credentials`: ties tokens, named by the SHA-256 of their
185/// text in hex, to the agent run their sandbox recorded. Returns how many.
186#[derive(Clone, Debug, Serialize, Deserialize)]
187#[serde(rename_all = "camelCase")]
188pub struct BindRunCredentialsArgs {
189 pub token_hashes: Vec<String>,
190 pub run_id: String,
191}
192
193/// `revoke_run_credentials`: ends tokens when their sandbox stops, by hash
194/// or by run. Only run credentials are touched, never a token a person
195/// made. Returns how many.
196#[derive(Clone, Debug, Default, Serialize, Deserialize)]
197#[serde(rename_all = "camelCase")]
198pub struct RevokeRunCredentialsArgs {
199 #[serde(default)]
200 pub token_hashes: Vec<String>,
201 #[serde(default)]
202 pub run_id: Option<String>,
203}
204
205// --- Policy --------------------------------------------------------------
206
207/// Operations that only read.
208pub const READ_OPERATIONS: &[&str] = &[
209 "whoami",
210 "list_repos",
211 "get_repo",
212 "list_deleted_repos",
213 "list_collaborators",
214 "get_collaborator_permission",
215 "list_repo_invitations",
216 "list_my_repo_invitations",
217 "list_outside_collaborators",
218 "get_repo_settings",
219 "get_merge_queue",
220 "recall",
221 "list_issues",
222 "get_issue",
223 "get_plan",
224 "list_labels",
225 "list_pull_requests",
226 "get_pull_request",
227 "read_session",
228 "get_pull_request_changes",
229 "list_events",
230 "get_context",
231 "search_context",
232 "get_entity",
233 "search",
234 "list_workflows",
235 "list_workflow_runs",
236 "get_workflow_run",
237 "get_job_logs",
238 "list_integrations",
239 "get_model_routes",
240 "list_webhooks",
241 "list_webhook_deliveries",
242 "list_actions_secrets",
243 "list_actions_variables",
244];
245
246/// What no agent's token may ever do, whatever its scope says: workspaces,
247/// repositories' settings, members, tokens, billing, integrations,
248/// webhooks, secrets, workflows' controls, merging, and putting more agents
249/// to work.
250pub const NEVER: &[&str] = &[
251 "create_workspace",
252 "delete_workspace",
253 "transfer_repo",
254 "create_repo",
255 "update_repo",
256 "delete_repo",
257 "list_deleted_repos",
258 "restore_repo",
259 "purge_repo",
260 "rename_repo",
261 "archive_repo",
262 "unarchive_repo",
263 "set_repo_visibility",
264 "rename_branch",
265 "update_repo_settings",
266 "merge_pull_request",
267 "assign_issue",
268 "plan_work",
269 "apply_plan",
270 "import_issue",
271 "list_integrations",
272 "connect_integration",
273 "disconnect_integration",
274 "test_integration",
275 "get_model_routes",
276 "set_model_routes",
277 "list_webhooks",
278 "create_webhook",
279 "update_webhook",
280 "delete_webhook",
281 "ping_webhook",
282 "list_webhook_deliveries",
283 "redeliver_webhook",
284 "dispatch_workflow",
285 "cancel_workflow_run",
286 "rerun_workflow_run",
287 "update_workflow",
288 "list_actions_secrets",
289 "set_actions_secret",
290 "delete_actions_secret",
291 "list_actions_variables",
292 "set_actions_variable",
293 "delete_actions_variable",
294 "list_collaborators",
295 "get_collaborator_permission",
296 "add_collaborator",
297 "update_collaborator",
298 "remove_collaborator",
299 "list_repo_invitations",
300 "revoke_repo_invitation",
301 "list_my_repo_invitations",
302 "accept_repo_invitation",
303 "decline_repo_invitation",
304 "set_base_permission",
305 "list_outside_collaborators",
306];
307
308/// Reading what an agent needs to know about its repository.
309const TOOLS_READ: &[&str] = &[
310 "get_repo",
311 "list_issues",
312 "get_issue",
313 "list_labels",
314 "list_pull_requests",
315 "get_pull_request",
316 "get_pull_request_changes",
317 "read_session",
318 "get_merge_queue",
319 "list_events",
320 "recall",
321 "search_context",
322 "get_entity",
323 "search",
324 "list_workflows",
325 "list_workflow_runs",
326 "get_workflow_run",
327 "get_job_logs",
328];
329
330pub fn is_read(operation: &str) -> bool {
331 READ_OPERATIONS.contains(&operation)
332}
333
334/// The API and MCP operations a run of `kind` may use with a credential
335/// for `usage`. Git is separate: see [`decide_git`].
336pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
337 use RunCredentialKind as K;
338 let mut operations: Vec<&'static str> = Vec::new();
339 match usage {
340 CredentialUse::Runner => {
341 if kind.works_on_a_pull() {
342 operations.extend(["get_repo", "get_pull_request", "record_session"]);
343 }
344 if kind == K::Implement {
345 operations.push("mark_pull_request_ready");
346 }
347 }
348 CredentialUse::Tools => match kind {
349 K::Implement | K::Revise | K::Answer => {
350 operations.extend(TOOLS_READ.iter().copied());
351 operations.extend([
352 "create_issue",
353 "add_comment",
354 "take_messages",
355 "remember",
356 "message_agent",
357 "answer_message",
358 "get_context",
359 ]);
360 }
361 K::Review => {
362 operations.extend(TOOLS_READ.iter().copied());
363 operations.extend(["add_comment", "review_pull_request", "get_context"]);
364 }
365 K::Plan => {
366 operations.extend(TOOLS_READ.iter().copied());
367 operations.extend(["create_issue", "get_context"]);
368 }
369 K::Update => operations.extend(TOOLS_READ.iter().copied()),
370 K::Checks | K::Queue | K::Mergecheck | K::Deploy => {}
371 },
372 }
373 operations
374}
375
376/// What a run's credential may do, in the scope vocabulary that access
377/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
378/// for a runner, git's. Its operations, its repository and its run still
379/// bound it more tightly than these scopes say.
380pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
381 use crate::scopes::{Scope, normalize, scope_for};
382 let mut scopes: Vec<Scope> = operations_for(kind, usage)
383 .into_iter()
384 .filter_map(scope_for)
385 .collect();
386 if usage == CredentialUse::Runner {
387 scopes.push(Scope::CodeRead);
388 if matches!(kind, RunCredentialKind::Implement | RunCredentialKind::Revise | RunCredentialKind::Answer | RunCredentialKind::Update) {
389 scopes.push(Scope::CodeWrite);
390 }
391 }
392 normalize(&mut scopes);
393 scopes
394}
395
396/// Operations that change a pull request, which a runner may do only to
397/// the pull request its run works on.
398const PULL_WRITES: &[&str] = &["record_session", "mark_pull_request_ready"];
399
400/// Whether something was allowed, and the rule that decided it.
401#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
402pub struct Decision {
403 pub allowed: bool,
404 /// A short, stable name: `run:implement/tools`, `never`,
405 /// `scope:repository` and so on. Shown in the audit log.
406 pub rule: String,
407 /// Why it was refused, for the caller.
408 #[serde(default, skip_serializing_if = "Option::is_none")]
409 pub reason: Option<String>,
410}
411
412impl Decision {
413 pub fn allow(rule: impl Into<String>) -> Self {
414 Decision {
415 allowed: true,
416 rule: rule.into(),
417 reason: None,
418 }
419 }
420
421 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
422 Decision {
423 allowed: false,
424 rule: rule.into(),
425 reason: Some(reason.into()),
426 }
427 }
428}
429
430fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
431 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
432}
433
434fn scope_rule(scope: &AgentScope) -> String {
435 match &scope.run {
436 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
437 None => "agent-token".to_owned(),
438 }
439}
440
441/// Whether `user`, resolved from an agent's token with `scope`, may use
442/// `operation`. `repo` is the repository the call names, if any, and
443/// `needs_repo` whether the operation is about one; `number` the issue or
444/// pull request it names.
445pub fn decide_operation(
446 user: &User,
447 scope: &AgentScope,
448 operation: &str,
449 repo: Option<&RepoPath>,
450 needs_repo: bool,
451 number: Option<u32>,
452) -> Decision {
453 let who = "A g1t agent's token";
454 if NEVER.contains(&operation) {
455 return Decision::deny(
456 "never",
457 format!(
458 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
459 ),
460 );
461 }
462 if !scope.operations.iter().any(|name| name == operation) {
463 return Decision::deny(
464 "scope:operation",
465 format!("{who} for this run cannot use {operation}."),
466 );
467 }
468 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
469 return Decision::deny(
470 "scope:repository",
471 format!(
472 "{who} works in {}/{} only.",
473 scope.repo.namespace, scope.repo.name
474 ),
475 );
476 }
477 // The intersection: the person it acts for must still be able to work
478 // in the repository's workspace, as a member or with a role on its
479 // repositories. What it may do in the repository itself is their
480 // role there, which services check (`access::can`).
481 if !crate::access::has_access_in(user, &scope.repo.namespace) {
482 return Decision::deny(
483 "on-behalf-of:membership",
484 format!(
485 "The person this agent works for is no longer a member of {}.",
486 scope.repo.namespace
487 ),
488 );
489 }
490 if let Some(run) = &scope.run
491 && run.usage == CredentialUse::Runner
492 && PULL_WRITES.contains(&operation)
493 && run.number.is_some()
494 && number != run.number
495 {
496 return Decision::deny(
497 "scope:pull",
498 format!(
499 "{who} can change pull request #{} only.",
500 run.number.unwrap_or_default()
501 ),
502 );
503 }
504 Decision::allow(scope_rule(scope))
505}
506
507/// Whether a run credential may clone or fetch (`write` false), or push to
508/// (`write` true), the repository at `repo`.
509pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
510 let Some(run) = scope
511 .run
512 .as_ref()
513 .filter(|run| run.usage == CredentialUse::Runner)
514 else {
515 return Decision::deny(
516 "git:not-a-run",
517 "A g1t agent's tools token cannot be used with git.",
518 );
519 };
520 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
521 if write {
522 return if pushable {
523 Decision::allow(format!("{}:push", scope_rule(scope)))
524 } else {
525 Decision::deny(
526 "git:push",
527 format!(
528 "A {} run cannot push to {}/{}.",
529 run.kind.as_str(),
530 repo.namespace,
531 repo.name
532 ),
533 )
534 };
535 }
536 let readable = pushable
537 || same_repo(&scope.repo, repo)
538 || run.read.iter().any(|path| same_repo(path, repo));
539 if readable {
540 Decision::allow(format!("{}:read", scope_rule(scope)))
541 } else {
542 Decision::deny(
543 "git:read",
544 format!(
545 "A {} run cannot read {}/{}.",
546 run.kind.as_str(),
547 repo.namespace,
548 repo.name
549 ),
550 )
551 }
552}
553
554/// Whether a push to `repo` is limited to certain branches, so that the
555/// refs it moves have to be read and checked with [`decide_refs`].
556pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
557 scope
558 .run
559 .iter()
560 .flat_map(|run| run.push.iter())
561 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
562}
563
564/// Whether a push to `repo` may move `refs` (full refs, such as
565/// `refs/heads/main`). Tags are never a run's to move.
566pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
567 let repo_decision = decide_git(scope, repo, true);
568 if !repo_decision.allowed {
569 return repo_decision;
570 }
571 let grants: Vec<&GitGrant> = scope
572 .run
573 .iter()
574 .flat_map(|run| run.push.iter())
575 .filter(|grant| same_repo(&grant.repo, repo))
576 .collect();
577 for git_ref in refs {
578 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
579 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
580 };
581 let allowed = grants
582 .iter()
583 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
584 if !allowed {
585 return Decision::deny(
586 "git:ref",
587 format!(
588 "A run cannot push to {branch} in {}/{}.",
589 repo.namespace, repo.name
590 ),
591 );
592 }
593 }
594 repo_decision
595}
596
597/// The most an agent may be on a repository, whoever it works for: it
598/// can push, merge and run, never change settings or who has access.
599pub const AGENT_CEILING: RepoRole = RepoRole::Write;
600
601/// The memberships an agent working for `person` has: the run's
602/// workspace, as a member, only if the person is in it now, with the
603/// person's role on its repositories (an owner's Admin included) cut down
604/// to [`AGENT_CEILING`].
605pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
606 let namespace = namespace.to_lowercase();
607 person
608 .iter()
609 .filter(|membership| membership.slug == namespace)
610 .map(|membership| {
611 let base = match membership.role {
612 Role::Owner => BasePermission::Admin,
613 Role::Member => membership.base_permission.unwrap_or_default(),
614 };
615 Membership {
616 role: Role::Member,
617 base_permission: Some(match base {
618 BasePermission::Admin => BasePermission::Write,
619 base => base,
620 }),
621 ..membership.clone()
622 }
623 })
624 .collect()
625}
626
627/// The repository grants an agent working for `person` has: those in the
628/// run's workspace, each cut down to [`AGENT_CEILING`].
629pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
630 let namespace = namespace.to_lowercase();
631 person
632 .iter()
633 .filter(|grant| grant.workspace == namespace)
634 .map(|grant| RepoGrant {
635 role: grant.role.min(AGENT_CEILING),
636 ..grant.clone()
637 })
638 .collect()
639}
640
641/// Who a runner's credential acts as downstream: the person, with only the
642/// agent's (already intersected) memberships. `None` for anything else.
643pub fn as_person(user: &User) -> Option<User> {
644 let acting = user.acting.as_ref()?;
645 if user.kind != PrincipalKind::Agent {
646 return None;
647 }
648 let run = acting.run()?;
649 if run.usage != CredentialUse::Runner {
650 return None;
651 }
652 Some(User {
653 id: acting.on_behalf_of.id.clone(),
654 username: acting.on_behalf_of.username.clone(),
655 kind: PrincipalKind::User,
656 verified: user.verified,
657 workspaces: user.workspaces.clone(),
658 avatar: None,
659 acting: None,
660 grants: user.grants.clone(),
661 token: None,
662 })
663}
664
665/// How an actor is described: "g1t-agent on behalf of syntaqx".
666pub fn describe(user: &User) -> String {
667 match &user.acting {
668 Some(acting) => format!(
669 "{} on behalf of {}",
670 acting.agent, acting.on_behalf_of.username
671 ),
672 None => user.username.clone(),
673 }
674}
675
676#[cfg(test)]
677mod tests {
678 use super::*;
679
680 #[test]
681 fn a_run_s_scopes_are_never_admin() {
682 for kind in RunCredentialKind::ALL {
683 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
684 let scopes = run_scopes(kind, usage);
685 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
686 }
687 }
688 let review = run_scopes(RunCredentialKind::Review, CredentialUse::Tools);
689 assert!(review.contains(&crate::scopes::Scope::PullRequestsWrite));
690 assert!(!review.contains(&crate::scopes::Scope::CodeWrite));
691 }
692
693 #[test]
694 fn agents_can_search_the_context_hub() {
695 for kind in [RunCredentialKind::Implement, RunCredentialKind::Review, RunCredentialKind::Plan] {
696 let tools = operations_for(kind, CredentialUse::Tools);
697 assert!(tools.contains(&"search_context") && tools.contains(&"get_entity"));
698 }
699 assert!(is_read("search_context") && is_read("get_entity"));
700 }
701
702 #[test]
703 fn agents_can_search_all_of_g1t() {
704 // Site-wide search only reads: every run that reads its repository
705 // may use it, and nothing that never reads gets it.
706 assert!(is_read("search"));
707 assert!(!NEVER.contains(&"search"));
708 for kind in [
709 RunCredentialKind::Implement,
710 RunCredentialKind::Revise,
711 RunCredentialKind::Answer,
712 RunCredentialKind::Review,
713 RunCredentialKind::Plan,
714 RunCredentialKind::Update,
715 ] {
716 let tools = operations_for(kind, CredentialUse::Tools);
717 assert!(tools.contains(&"search"), "{kind:?} should search");
718 // The context hub's search stays its own tool beside it.
719 assert!(tools.contains(&"search_context"), "{kind:?} keeps search_context");
720 }
721 for kind in [RunCredentialKind::Checks, RunCredentialKind::Queue, RunCredentialKind::Mergecheck, RunCredentialKind::Deploy] {
722 assert!(!operations_for(kind, CredentialUse::Tools).contains(&"search"));
723 }
724 assert!(!operations_for(RunCredentialKind::Implement, CredentialUse::Runner).contains(&"search"));
725 }
726
727 fn path(namespace: &str, name: &str) -> RepoPath {
728 RepoPath {
729 namespace: namespace.to_owned(),
730 name: name.to_owned(),
731 }
732 }
733
734 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
735 AgentScope {
736 repo: path("acme", "rocket"),
737 operations: operations_for(kind, usage)
738 .into_iter()
739 .map(str::to_owned)
740 .collect(),
741 run: Some(RunBinding {
742 kind,
743 usage,
744 run_id: Some("run_1".to_owned()),
745 number: Some(7),
746 agent: "g1t-agent".to_owned(),
747 read: vec![path("acme", "rocket")],
748 push: match kind {
749 RunCredentialKind::Implement
750 | RunCredentialKind::Revise
751 | RunCredentialKind::Answer => vec![GitGrant {
752 repo: path("pulls", "pul_7"),
753 branch: None,
754 }],
755 RunCredentialKind::Update => vec![GitGrant {
756 repo: path("acme", "rocket"),
757 branch: Some("fix-login".to_owned()),
758 }],
759 _ => vec![],
760 },
761 }),
762 }
763 }
764
765 fn agent(member_of: &[&str], scope: AgentScope) -> User {
766 User {
767 id: "usr_g1t_agent".to_owned(),
768 username: "g1t-agent".to_owned(),
769 kind: PrincipalKind::Agent,
770 verified: true,
771 workspaces: member_of
772 .iter()
773 .map(|slug| Membership::member(*slug))
774 .collect(),
775 avatar: None,
776 grants: Vec::new(),
777 token: None,
778 acting: Some(Box::new(Acting {
779 credential_id: "tok_1".to_owned(),
780 agent: "g1t-agent".to_owned(),
781 on_behalf_of: Principal {
782 id: "usr_1".to_owned(),
783 username: "syntaqx".to_owned(),
784 },
785 scope,
786 })),
787 }
788 }
789
790 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
791 let scope = scope(kind, usage);
792 let user = agent(&["acme"], scope.clone());
793 decide_operation(
794 &user,
795 &scope,
796 operation,
797 Some(&path("acme", "rocket")),
798 true,
799 Some(7),
800 )
801 }
802
803 use CredentialUse::{Runner, Tools};
804 use RunCredentialKind as K;
805
806 /// Which operations each kind of run may use through its tools: the
807 /// allowed and denied matrix.
808 #[test]
809 fn tools_matrix() {
810 let cases: [(&str, [bool; 6]); 12] = [
811 // implement revise answer review plan checks
812 ("get_issue", [true, true, true, true, true, false]),
813 ("create_issue", [true, true, true, false, true, false]),
814 ("add_comment", [true, true, true, true, false, false]),
815 (
816 "review_pull_request",
817 [false, false, false, true, false, false],
818 ),
819 ("remember", [true, true, true, false, false, false]),
820 ("take_messages", [true, true, true, false, false, false]),
821 ("record_session", [false, false, false, false, false, false]),
822 (
823 "merge_pull_request",
824 [false, false, false, false, false, false],
825 ),
826 (
827 "update_repo_settings",
828 [false, false, false, false, false, false],
829 ),
830 ("create_webhook", [false, false, false, false, false, false]),
831 (
832 "set_actions_secret",
833 [false, false, false, false, false, false],
834 ),
835 ("assign_issue", [false, false, false, false, false, false]),
836 ];
837 let kinds = [
838 K::Implement,
839 K::Revise,
840 K::Answer,
841 K::Review,
842 K::Plan,
843 K::Checks,
844 ];
845 for (operation, expected) in cases {
846 for (kind, allowed) in kinds.into_iter().zip(expected) {
847 assert_eq!(
848 op(kind, Tools, operation).allowed,
849 allowed,
850 "{operation} by a {} run's tools",
851 kind.as_str()
852 );
853 }
854 }
855 }
856
857 #[test]
858 fn runner_matrix() {
859 assert!(op(K::Implement, Runner, "record_session").allowed);
860 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
861 assert!(op(K::Revise, Runner, "record_session").allowed);
862 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
863 assert!(!op(K::Implement, Runner, "create_issue").allowed);
864 assert!(!op(K::Review, Runner, "record_session").allowed);
865 assert!(!op(K::Checks, Runner, "get_issue").allowed);
866 }
867
868 #[test]
869 fn settings_billing_tokens_and_members_are_never_reachable() {
870 for kind in RunCredentialKind::ALL {
871 for usage in [Runner, Tools] {
872 for operation in NEVER.iter().copied() {
873 let decision = op(kind, usage, operation);
874 assert!(!decision.allowed);
875 assert_eq!(decision.rule, "never");
876 }
877 }
878 }
879 // Even a scope that lists one is refused.
880 let mut wide = scope(K::Implement, Tools);
881 wide.operations.push("merge_pull_request".to_owned());
882 let user = agent(&["acme"], wide.clone());
883 let decision = decide_operation(
884 &user,
885 &wide,
886 "merge_pull_request",
887 Some(&path("acme", "rocket")),
888 true,
889 Some(7),
890 );
891 assert_eq!(decision.rule, "never");
892 }
893
894 #[test]
895 fn another_repository_is_refused() {
896 let scope = scope(K::Implement, Tools);
897 let user = agent(&["acme"], scope.clone());
898 let decision = decide_operation(
899 &user,
900 &scope,
901 "create_issue",
902 Some(&path("acme", "other")),
903 true,
904 None,
905 );
906 assert!(!decision.allowed);
907 assert_eq!(decision.rule, "scope:repository");
908 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
909 assert_eq!(decision.rule, "scope:repository");
910 // The repository's name is matched without regard to case.
911 let decision = decide_operation(
912 &user,
913 &scope,
914 "create_issue",
915 Some(&path("Acme", "Rocket")),
916 true,
917 None,
918 );
919 assert!(decision.allowed);
920 assert_eq!(decision.rule, "run:implement/tools");
921 }
922
923 #[test]
924 fn the_permission_is_the_intersection_with_the_person() {
925 let scope = scope(K::Implement, Tools);
926 // The person left the workspace: their agent can do nothing there.
927 let user = agent(&[], scope.clone());
928 let decision = decide_operation(
929 &user,
930 &scope,
931 "get_issue",
932 Some(&path("acme", "rocket")),
933 true,
934 Some(1),
935 );
936 assert!(!decision.allowed);
937 assert_eq!(decision.rule, "on-behalf-of:membership");
938 // And an owner's agent is only ever a member.
939 let owner = vec![
940 Membership {
941 slug: "acme".to_owned(),
942 role: Role::Owner,
943 name: None,
944 avatar: None,
945 base_permission: Some(BasePermission::None),
946 },
947 Membership::member("elsewhere"),
948 ];
949 let memberships = intersect(&owner, "Acme");
950 assert_eq!(memberships.len(), 1);
951 assert_eq!(memberships[0].slug, "acme");
952 assert_eq!(memberships[0].role, Role::Member);
953 assert!(intersect(&owner, "nowhere").is_empty());
954 }
955
956 /// An agent gets at most the person's role on the repository, and
957 /// never more than Write; nothing outside the run's workspace.
958 #[test]
959 fn an_agent_has_at_most_its_persons_role() {
960 use crate::access::{Capability, RepoRef, can, permission};
961 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
962 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
963 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
964 let tools = scope(K::Implement, Tools);
965 let scope = scope(K::Implement, Runner);
966 // An owner's agent: Write, never Admin.
967 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
968 let mut agent_user = agent(&[], scope.clone());
969 agent_user.workspaces = intersect(&owner, "acme");
970 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
971 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
972 assert_eq!(permission(Some(&agent_user), elsewhere), None);
973 // A member whose workspace gives Read: Read, so it cannot push.
974 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
975 agent_user.workspaces = intersect(&reader, "acme");
976 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
977 assert!(!can(Some(&agent_user), rocket, Capability::Push));
978 // An outside collaborator with Maintain on one repository: Write
979 // there, nothing elsewhere, and the run is allowed.
980 let grants = [
981 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain },
982 RepoGrant { repo_id: "rep_3".into(), workspace: "globex".into(), role: RepoRole::Admin },
983 ];
984 agent_user.workspaces = intersect(&[], "acme");
985 agent_user.grants = intersect_grants(&grants, "Acme");
986 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
987 assert_eq!(permission(Some(&agent_user), other), None);
988 assert_eq!(permission(Some(&agent_user), elsewhere), None);
989 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
990 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
991 // The person, downstream of a runner's credential, carries the same.
992 let person = as_person(&agent_user).expect("a runner acts as the person");
993 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
994 }
995
996 #[test]
997 fn a_runner_changes_only_its_own_pull_request() {
998 let scope = scope(K::Implement, Runner);
999 let user = agent(&["acme"], scope.clone());
1000 let repo = path("acme", "rocket");
1001 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1002 assert!(!other.allowed);
1003 assert_eq!(other.rule, "scope:pull");
1004 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1005 assert!(own.allowed);
1006 // Reading another is fine.
1007 assert!(
1008 decide_operation(
1009 &user,
1010 &scope,
1011 "get_pull_request",
1012 Some(&repo),
1013 true,
1014 Some(8)
1015 )
1016 .allowed
1017 );
1018 }
1019
1020 #[test]
1021 fn git_matrix() {
1022 let fork = path("pulls", "pul_7");
1023 let upstream = path("acme", "rocket");
1024 let elsewhere = path("acme", "billing");
1025 let implement = scope(K::Implement, Runner);
1026 assert!(decide_git(&implement, &fork, true).allowed);
1027 assert!(decide_git(&implement, &fork, false).allowed);
1028 assert!(decide_git(&implement, &upstream, false).allowed);
1029 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1030 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1031 let review = scope(K::Review, Runner);
1032 assert!(decide_git(&review, &upstream, false).allowed);
1033 assert!(!decide_git(&review, &upstream, true).allowed);
1034 assert!(!decide_git(&review, &fork, true).allowed);
1035 // A tools token made before run credentials never reaches git.
1036 let old = AgentScope {
1037 repo: upstream.clone(),
1038 operations: vec!["get_issue".to_owned()],
1039 run: None,
1040 };
1041 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1042 // Nor does an agent's tools token.
1043 assert_eq!(
1044 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1045 "git:not-a-run"
1046 );
1047 }
1048
1049 #[test]
1050 fn a_push_moves_only_granted_branches() {
1051 let update = scope(K::Update, Runner);
1052 let repo = path("acme", "rocket");
1053 let refs = |names: &[&str]| {
1054 names
1055 .iter()
1056 .map(|name| (*name).to_owned())
1057 .collect::<Vec<_>>()
1058 };
1059 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1060 assert_eq!(
1061 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1062 "git:ref"
1063 );
1064 assert_eq!(
1065 decide_refs(
1066 &update,
1067 &repo,
1068 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1069 )
1070 .rule,
1071 "git:ref"
1072 );
1073 let implement = scope(K::Implement, Runner);
1074 assert!(
1075 decide_refs(
1076 &implement,
1077 &path("pulls", "pul_7"),
1078 &refs(&["refs/heads/main"])
1079 )
1080 .allowed
1081 );
1082 }
1083
1084 #[test]
1085 fn a_runner_acts_downstream_as_the_person() {
1086 let user = agent(&["acme"], scope(K::Implement, Runner));
1087 let person = as_person(&user).unwrap();
1088 assert_eq!(person.id, "usr_1");
1089 assert_eq!(person.username, "syntaqx");
1090 assert_eq!(person.kind, PrincipalKind::User);
1091 assert!(person.is_member("acme"));
1092 assert!(person.acting.is_none());
1093 assert_eq!(describe(&user), "g1t-agent on behalf of syntaqx");
1094 // The tools act as the agent.
1095 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1096 }
1097
1098 #[test]
1099 fn scopes_without_a_run_still_parse() {
1100 let old: AgentScope = serde_json::from_str(
1101 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1102 )
1103 .unwrap();
1104 assert!(old.run.is_none());
1105 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1106 assert!(written.contains(r#""use":"tools""#));
1107 assert!(written.contains(r#""kind":"review""#));
1108 let back: AgentScope = serde_json::from_str(&written).unwrap();
1109 assert_eq!(back.run.unwrap().kind, K::Review);
1110 }
1111}