flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/crates/contracts/src/credentials.rs

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