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