| 1 | //! Keeping workflow runs safe, over REST and MCP: environments' protection |
| 2 | //! rules, the reviews of the jobs they hold, approving a pull request's |
| 3 | //! run from outside, what a job's token gets when its workflow names no |
| 4 | //! `permissions:`, which pull requests' runs wait for approval, and |
| 5 | //! `repository_dispatch`. The actions service decides and keeps all of it |
| 6 | //! (services/actions/src/protection.rs); these shape requests and answers |
| 7 | //! as the standard Actions REST API does. |
| 8 | |
| 9 | use g1t_contracts::{FailureCode, Outcome, Viewer}; |
| 10 | use serde_json::{Map, Value, json}; |
| 11 | use worker::Result; |
| 12 | |
| 13 | use crate::operations::{Services, repo_path}; |
| 14 | |
| 15 | /// One operation. |
| 16 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 17 | pub enum ProtectionOp { |
| 18 | UpdateEnvironment, |
| 19 | DeleteEnvironment, |
| 20 | GetPendingDeployments, |
| 21 | ReviewPendingDeployments, |
| 22 | ApproveWorkflowRun, |
| 23 | GetWorkflowPermissions, |
| 24 | SetWorkflowPermissions, |
| 25 | GetForkPrApproval, |
| 26 | SetForkPrApproval, |
| 27 | GetActionsAccess, |
| 28 | SetActionsAccess, |
| 29 | CreateRepositoryDispatch, |
| 30 | GetWorkspaceWorkflowPermissions, |
| 31 | SetWorkspaceWorkflowPermissions, |
| 32 | } |
| 33 | |
| 34 | impl ProtectionOp { |
| 35 | /// Every one: `Op::ALL` lists each as `Op::Protection(…)`, which a test |
| 36 | /// checks against this. |
| 37 | #[cfg(test)] |
| 38 | pub const ALL: [ProtectionOp; 14] = [ |
| 39 | ProtectionOp::UpdateEnvironment, |
| 40 | ProtectionOp::DeleteEnvironment, |
| 41 | ProtectionOp::GetPendingDeployments, |
| 42 | ProtectionOp::ReviewPendingDeployments, |
| 43 | ProtectionOp::ApproveWorkflowRun, |
| 44 | ProtectionOp::GetWorkflowPermissions, |
| 45 | ProtectionOp::SetWorkflowPermissions, |
| 46 | ProtectionOp::GetForkPrApproval, |
| 47 | ProtectionOp::SetForkPrApproval, |
| 48 | ProtectionOp::GetActionsAccess, |
| 49 | ProtectionOp::SetActionsAccess, |
| 50 | ProtectionOp::CreateRepositoryDispatch, |
| 51 | ProtectionOp::GetWorkspaceWorkflowPermissions, |
| 52 | ProtectionOp::SetWorkspaceWorkflowPermissions, |
| 53 | ]; |
| 54 | |
| 55 | pub fn name(self) -> &'static str { |
| 56 | match self { |
| 57 | ProtectionOp::UpdateEnvironment => "update_environment", |
| 58 | ProtectionOp::DeleteEnvironment => "delete_environment", |
| 59 | ProtectionOp::GetPendingDeployments => "get_pending_deployments", |
| 60 | ProtectionOp::ReviewPendingDeployments => "review_pending_deployments", |
| 61 | ProtectionOp::ApproveWorkflowRun => "approve_workflow_run", |
| 62 | ProtectionOp::GetWorkflowPermissions => "get_workflow_permissions", |
| 63 | ProtectionOp::SetWorkflowPermissions => "set_workflow_permissions", |
| 64 | ProtectionOp::GetForkPrApproval => "get_fork_pr_approval", |
| 65 | ProtectionOp::SetForkPrApproval => "set_fork_pr_approval", |
| 66 | ProtectionOp::GetActionsAccess => "get_actions_access", |
| 67 | ProtectionOp::SetActionsAccess => "set_actions_access", |
| 68 | ProtectionOp::CreateRepositoryDispatch => "create_repository_dispatch", |
| 69 | ProtectionOp::GetWorkspaceWorkflowPermissions => "get_workspace_workflow_permissions", |
| 70 | ProtectionOp::SetWorkspaceWorkflowPermissions => "set_workspace_workflow_permissions", |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// Whether it is about one repository, named by `repo`; the rest are a |
| 75 | /// workspace's. |
| 76 | pub fn needs_repo(self) -> bool { |
| 77 | !matches!(self, ProtectionOp::GetWorkspaceWorkflowPermissions | ProtectionOp::SetWorkspaceWorkflowPermissions) |
| 78 | } |
| 79 | |
| 80 | pub fn title(self) -> &'static str { |
| 81 | match self { |
| 82 | ProtectionOp::UpdateEnvironment => "Create or update an environment's protection rules", |
| 83 | ProtectionOp::DeleteEnvironment => "Delete an environment's protection rules", |
| 84 | ProtectionOp::GetPendingDeployments => "Get a run's pending deployments", |
| 85 | ProtectionOp::ReviewPendingDeployments => "Review a run's pending deployments", |
| 86 | ProtectionOp::ApproveWorkflowRun => "Approve a workflow run", |
| 87 | ProtectionOp::GetWorkflowPermissions => "Get the default workflow permissions", |
| 88 | ProtectionOp::SetWorkflowPermissions => "Set the default workflow permissions", |
| 89 | ProtectionOp::GetForkPrApproval => "Get the approval policy for outside pull requests", |
| 90 | ProtectionOp::SetForkPrApproval => "Set the approval policy for outside pull requests", |
| 91 | ProtectionOp::GetActionsAccess => "Get who may use a repository's actions and workflows", |
| 92 | ProtectionOp::SetActionsAccess => "Set who may use a repository's actions and workflows", |
| 93 | ProtectionOp::CreateRepositoryDispatch => "Create a repository dispatch event", |
| 94 | ProtectionOp::GetWorkspaceWorkflowPermissions => "Get a workspace's default workflow permissions", |
| 95 | ProtectionOp::SetWorkspaceWorkflowPermissions => "Set a workspace's default workflow permissions", |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | pub fn description(self) -> &'static str { |
| 100 | match self { |
| 101 | ProtectionOp::UpdateEnvironment => "Create an environment's protection rules, or change them; fields left out stay as they are. A job that names the environment with `environment:` waits, once its needs are done, until the rules let it through, and only then gets the environment's secrets. reviewers: up to 6, each {\"type\": \"User\" or \"Team\", \"name\": a username or a team's slug} (id is read as the name too); a job waits until one of them approves it. prevent_self_review: whoever started the run may not approve it. wait_timer: minutes each job waits, 0 to 43200. deployment_branch_policy: null lets every branch deploy; {\"protected_branches\": true} only branches the repository's rules protect (the default branch included); {\"custom_branch_policies\": true} only the branches and tags in branch_policies, each {\"name\": a pattern such as release/*, \"type\": \"branch\" or \"tag\"}. can_admins_bypass (true unless you say): admins may approve without being reviewers, which also skips the wait. The environment's name is up to 40 letters, digits, - and _, matched without regard to case. Needs the Admin role. Returns the environment with its protection_rules.", |
| 102 | ProtectionOp::DeleteEnvironment => "Delete an environment's protection rules: its jobs run without waiting from then on. Its secrets, variables and deployments stay. Needs the Admin role.", |
| 103 | ProtectionOp::GetPendingDeployments => "The environments whose protection rules hold a run's jobs, this attempt: each with the environment's name, state (waiting, approved or rejected), wait_timer and wait_until (when its timer lets its jobs start), its reviewers, the jobs it holds, who reviewed it and their comment, and current_user_can_approve. Needs the Read role.", |
| 104 | ProtectionOp::ReviewPendingDeployments => "Approve or reject the jobs a run's environments hold. environment_names names them (every waiting one if left out; environment_ids is read as names too); state is approved or rejected; comment is kept with the review. Only one of the environment's reviewers may, or an admin when can_admins_bypass is on, which also skips the wait timer; with prevent_self_review, not whoever started the run. A rejected environment's jobs fail. A workflow job's own token cannot review. Returns the pending deployments as they stand.", |
| 105 | ProtectionOp::ApproveWorkflowRun => "Let a run of a pull request from outside start: it waits as action_required, by the repository's approval policy (get_fork_pr_approval), until someone with the Write role approves it. A workflow job's own token cannot approve. Returns the run.", |
| 106 | ProtectionOp::GetWorkflowPermissions => "What a job's G1T_TOKEN (GITHUB_TOKEN) may do when its workflow and job write no `permissions:`: default_workflow_permissions is read (contents and packages read) or write (every permission). Unless the repository chose (default_chosen), a repository made before restricted tokens has write and a newer one its workspace's default; it is never more than the workspace's max_workflow_permissions. can_approve_pull_request_reviews says whether its jobs may open and approve pull requests (off unless chosen, and only where the workspace allows it). Needs the Read role.", |
| 107 | ProtectionOp::SetWorkflowPermissions => "Set default_workflow_permissions to read, write (refused where the workspace's maximum is read) or inherit (back to the workspace's default, or write for a repository made before restricted tokens), and can_approve_pull_request_reviews, \"Allow g1t Actions to create and approve pull requests\" (refused where the workspace does not allow it). Workflows that write `permissions:` get what they write either way, and a pull request's run from outside gets read-only. Needs the Admin role.", |
| 108 | ProtectionOp::GetForkPrApproval => "Which pull requests' runs wait for someone with the Write role to approve them before anything runs (approve_workflow_run): approval_policy is first_time_contributors (a pull request from someone outside the workspace who has not had one merged here), outside_contributors (the default: also everyone outside who cannot push here) or all_external_contributors (everyone outside the workspace, outside collaborators included). Members never wait, nor does g1t's own work. Needs the Read role.", |
| 109 | ProtectionOp::SetForkPrApproval => "Set approval_policy: first_time_contributors, outside_contributors or all_external_contributors. Needs the Admin role.", |
| 110 | ProtectionOp::GetActionsAccess => "Which other repositories' workflows may use this private repository's actions (uses: owner/repo@ref) and reusable workflows (jobs.<id>.uses: owner/repo/.g1t/workflows/build.yml@ref): access_level is none (the default: only this repository) or organization (private repositories in the same workspace). A public repository's actions and workflows are anyone's, whatever this says, and a public repository's workflows never use a private one's. Needs the Read role.", |
| 111 | ProtectionOp::SetActionsAccess => "Set access_level: none, or organization to let the workspace's other private repositories use this repository's actions and reusable workflows (user is read as organization). Needs the Admin role.", |
| 112 | ProtectionOp::GetWorkspaceWorkflowPermissions => "A workspace's policy for its repositories' job tokens: default_workflow_permissions (read, the default, or write) is what a repository made from now on gets until it chooses; max_workflow_permissions (write, the default, or read) is the most any repository's default may be, so read holds every repository to read-only; can_approve_pull_request_reviews (off by default) lets its repositories allow jobs to open and approve pull requests. Members only.", |
| 113 | ProtectionOp::SetWorkspaceWorkflowPermissions => "Change a workspace's default_workflow_permissions, max_workflow_permissions and can_approve_pull_request_reviews; fields left out stay as they are. A maximum of read makes the default read too. Owners only.", |
| 114 | ProtectionOp::CreateRepositoryDispatch => "Start the default branch's workflows that run `on: repository_dispatch` for event_type (those listing it under types, or with none). client_payload, a JSON object of at most 10 properties and 64 KB, is github.event.client_payload; github.event.action is event_type. A workflow job's own token may send one: with workflow_dispatch, it is how one workflow starts another. Needs the Write role (code:write). Returns how many runs started.", |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Whether it changes anything (the caller is its actor). |
| 119 | pub fn writes(self) -> bool { |
| 120 | !matches!( |
| 121 | self, |
| 122 | ProtectionOp::GetPendingDeployments |
| 123 | | ProtectionOp::GetWorkflowPermissions |
| 124 | | ProtectionOp::GetForkPrApproval |
| 125 | | ProtectionOp::GetActionsAccess |
| 126 | | ProtectionOp::GetWorkspaceWorkflowPermissions |
| 127 | ) |
| 128 | } |
| 129 | |
| 130 | pub fn input(self) -> Value { |
| 131 | let repo = json!({ "type": "string", "description": "Repository as \"owner/name\", e.g. \"flagon-io/hello\"." }); |
| 132 | let run = json!({ "type": "string", "description": "The run's id, run_…." }); |
| 133 | let workspace = json!({ "type": "string", "description": "The workspace's name, e.g. \"acme\"." }); |
| 134 | let environment = json!({ "type": "string", "description": "The environment's name, such as production." }); |
| 135 | let (properties, required): (Value, &[&str]) = match self { |
| 136 | ProtectionOp::UpdateEnvironment => ( |
| 137 | json!({ |
| 138 | "repo": repo, |
| 139 | "environment": environment, |
| 140 | "wait_timer": { "type": "integer", "description": "Minutes each job waits before it may start, 0 to 43200." }, |
| 141 | "prevent_self_review": { "type": "boolean", "description": "Whoever started a run may not approve its jobs." }, |
| 142 | "reviewers": { |
| 143 | "type": ["array", "null"], |
| 144 | "description": "Up to 6 people or teams who may approve its jobs; empty for none.", |
| 145 | "items": { |
| 146 | "type": "object", |
| 147 | "properties": { |
| 148 | "type": { "type": "string", "enum": ["User", "Team"] }, |
| 149 | "name": { "type": "string", "description": "A username, or a team's slug in the repository's workspace." }, |
| 150 | }, |
| 151 | }, |
| 152 | }, |
| 153 | "deployment_branch_policy": { |
| 154 | "type": ["object", "null"], |
| 155 | "description": "null: every branch may deploy. protected_branches: only protected ones. custom_branch_policies: only those in branch_policies.", |
| 156 | "properties": { |
| 157 | "protected_branches": { "type": "boolean" }, |
| 158 | "custom_branch_policies": { "type": "boolean" }, |
| 159 | }, |
| 160 | }, |
| 161 | "branch_policies": { |
| 162 | "type": "array", |
| 163 | "description": "With custom_branch_policies: the branches and tags that may deploy, at most 50.", |
| 164 | "items": { |
| 165 | "type": "object", |
| 166 | "properties": { |
| 167 | "name": { "type": "string", "description": "A pattern, such as main, release/* or v*." }, |
| 168 | "type": { "type": "string", "enum": ["branch", "tag"] }, |
| 169 | }, |
| 170 | }, |
| 171 | }, |
| 172 | "can_admins_bypass": { "type": "boolean", "description": "Admins may approve without being reviewers, skipping the wait. True unless you say." }, |
| 173 | }), |
| 174 | &["repo", "environment"], |
| 175 | ), |
| 176 | ProtectionOp::DeleteEnvironment => (json!({ "repo": repo, "environment": environment }), &["repo", "environment"]), |
| 177 | ProtectionOp::GetPendingDeployments | ProtectionOp::ApproveWorkflowRun => (json!({ "repo": repo, "id": run }), &["repo", "id"]), |
| 178 | ProtectionOp::ReviewPendingDeployments => ( |
| 179 | json!({ |
| 180 | "repo": repo, |
| 181 | "id": run, |
| 182 | "environment_names": { "type": "array", "items": { "type": "string" }, "description": "The environments to review; every waiting one if left out." }, |
| 183 | "state": { "type": "string", "enum": ["approved", "rejected"] }, |
| 184 | "comment": { "type": "string", "description": "Why, kept with the review." }, |
| 185 | }), |
| 186 | &["repo", "id", "state"], |
| 187 | ), |
| 188 | ProtectionOp::GetWorkflowPermissions | ProtectionOp::GetForkPrApproval | ProtectionOp::GetActionsAccess => (json!({ "repo": repo }), &["repo"]), |
| 189 | ProtectionOp::SetActionsAccess => ( |
| 190 | json!({ |
| 191 | "repo": repo, |
| 192 | "access_level": { "type": "string", "enum": ["none", "organization", "user"] }, |
| 193 | }), |
| 194 | &["repo", "access_level"], |
| 195 | ), |
| 196 | ProtectionOp::SetWorkflowPermissions => ( |
| 197 | json!({ |
| 198 | "repo": repo, |
| 199 | "default_workflow_permissions": { "type": "string", "enum": ["read", "write", "inherit"] }, |
| 200 | "can_approve_pull_request_reviews": { "type": "boolean", "description": "Allow g1t Actions to create and approve pull requests." }, |
| 201 | }), |
| 202 | &["repo"], |
| 203 | ), |
| 204 | ProtectionOp::GetWorkspaceWorkflowPermissions => (json!({ "workspace": workspace }), &["workspace"]), |
| 205 | ProtectionOp::SetWorkspaceWorkflowPermissions => ( |
| 206 | json!({ |
| 207 | "workspace": workspace, |
| 208 | "default_workflow_permissions": { "type": "string", "enum": ["read", "write"], "description": "What new repositories get." }, |
| 209 | "max_workflow_permissions": { "type": "string", "enum": ["read", "write"], "description": "The most any repository's default may be." }, |
| 210 | "can_approve_pull_request_reviews": { "type": "boolean", "description": "Let repositories allow jobs to open and approve pull requests." }, |
| 211 | }), |
| 212 | &["workspace"], |
| 213 | ), |
| 214 | ProtectionOp::SetForkPrApproval => ( |
| 215 | json!({ |
| 216 | "repo": repo, |
| 217 | "approval_policy": { "type": "string", "enum": ["first_time_contributors", "outside_contributors", "all_external_contributors"] }, |
| 218 | }), |
| 219 | &["repo", "approval_policy"], |
| 220 | ), |
| 221 | ProtectionOp::CreateRepositoryDispatch => ( |
| 222 | json!({ |
| 223 | "repo": repo, |
| 224 | "event_type": { "type": "string", "description": "What happened, 1 to 100 characters; workflows choose it with `types:`." }, |
| 225 | "client_payload": { "type": "object", "description": "Anything the workflows should read, as github.event.client_payload." }, |
| 226 | }), |
| 227 | &["repo", "event_type"], |
| 228 | ), |
| 229 | }; |
| 230 | json!({ "type": "object", "properties": properties, "required": required }) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | fn text(input: &Value, key: &str) -> Option<String> { |
| 235 | match &input[key] { |
| 236 | Value::String(text) if !text.trim().is_empty() => Some(text.trim().to_owned()), |
| 237 | Value::Number(number) => Some(number.to_string()), |
| 238 | _ => None, |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | fn flag(input: &Value, key: &str) -> Option<bool> { |
| 243 | match &input[key] { |
| 244 | Value::Bool(value) => Some(*value), |
| 245 | Value::String(text) => match text.trim() { |
| 246 | "true" | "1" => Some(true), |
| 247 | "false" | "0" => Some(false), |
| 248 | _ => None, |
| 249 | }, |
| 250 | _ => None, |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | /// The actions service's arguments for an environment's change, from a |
| 255 | /// request shaped as the standard environments API is. |
| 256 | pub(crate) fn environment_change(input: &Value) -> std::result::Result<Map<String, Value>, String> { |
| 257 | let mut out = Map::new(); |
| 258 | if let Some(minutes) = input.get("wait_timer").filter(|v| !v.is_null()) { |
| 259 | let minutes = minutes.as_u64().or_else(|| minutes.as_str().and_then(|s| s.trim().parse().ok())).ok_or("wait_timer is a number of minutes.")?; |
| 260 | out.insert("waitMinutes".into(), minutes.into()); |
| 261 | } |
| 262 | if let Some(value) = flag(input, "prevent_self_review") { |
| 263 | out.insert("preventSelfReview".into(), value.into()); |
| 264 | } |
| 265 | if let Some(value) = flag(input, "can_admins_bypass") { |
| 266 | out.insert("adminsBypass".into(), value.into()); |
| 267 | } |
| 268 | match input.get("reviewers") { |
| 269 | None => {} |
| 270 | Some(Value::Null) => { |
| 271 | out.insert("reviewers".into(), json!([])); |
| 272 | } |
| 273 | Some(Value::Array(given)) => { |
| 274 | let mut reviewers = Vec::new(); |
| 275 | for reviewer in given { |
| 276 | let kind = reviewer["type"].as_str().unwrap_or("User").to_ascii_lowercase(); |
| 277 | let name = text(reviewer, "name").or_else(|| text(reviewer, "id")).or_else(|| text(reviewer, "login")).or_else(|| text(reviewer, "slug")); |
| 278 | let Some(name) = name else { return Err("Each reviewer has a name: a username or a team's slug.".to_owned()) }; |
| 279 | reviewers.push(json!({ "type": kind, "name": name })); |
| 280 | } |
| 281 | out.insert("reviewers".into(), Value::Array(reviewers)); |
| 282 | } |
| 283 | Some(_) => return Err("reviewers is a list of {\"type\", \"name\"}.".to_owned()), |
| 284 | } |
| 285 | match input.get("deployment_branch_policy") { |
| 286 | None => {} |
| 287 | Some(Value::Null) => { |
| 288 | out.insert("branchPolicy".into(), "all".into()); |
| 289 | } |
| 290 | Some(policy @ Value::Object(_)) => { |
| 291 | let protected = flag(policy, "protected_branches") == Some(true); |
| 292 | let custom = flag(policy, "custom_branch_policies") == Some(true); |
| 293 | let chosen = match (protected, custom) { |
| 294 | (true, true) => return Err("deployment_branch_policy is protected_branches or custom_branch_policies, not both.".to_owned()), |
| 295 | (true, false) => "protected", |
| 296 | (false, true) => "selected", |
| 297 | (false, false) => "all", |
| 298 | }; |
| 299 | out.insert("branchPolicy".into(), chosen.into()); |
| 300 | } |
| 301 | Some(_) => return Err("deployment_branch_policy is an object, or null.".to_owned()), |
| 302 | } |
| 303 | if let Some(Value::Array(patterns)) = input.get("branch_policies") { |
| 304 | let patterns: Vec<Value> = patterns |
| 305 | .iter() |
| 306 | .map(|pattern| json!({ "name": pattern["name"].as_str().unwrap_or_default(), "type": pattern["type"].as_str().unwrap_or("branch") })) |
| 307 | .collect(); |
| 308 | out.insert("branchPatterns".into(), Value::Array(patterns)); |
| 309 | } |
| 310 | Ok(out) |
| 311 | } |
| 312 | |
| 313 | /// An environment as the actions service keeps it (camelCase), in the |
| 314 | /// standard shape: `protection_rules`, `deployment_branch_policy` and |
| 315 | /// `can_admins_bypass`, with g1t's `branch_policies` beside them. |
| 316 | pub(crate) fn environment_view(env: &Value) -> Value { |
| 317 | let reviewers: Vec<Value> = env["reviewers"] |
| 318 | .as_array() |
| 319 | .map(|list| { |
| 320 | list.iter() |
| 321 | .map(|r| match r["type"].as_str() { |
| 322 | Some("team") => json!({ "type": "Team", "reviewer": { "slug": r["name"] } }), |
| 323 | _ => json!({ "type": "User", "reviewer": { "login": r["name"] } }), |
| 324 | }) |
| 325 | .collect() |
| 326 | }) |
| 327 | .unwrap_or_default(); |
| 328 | let mut rules = Vec::new(); |
| 329 | if !reviewers.is_empty() { |
| 330 | rules.push(json!({ "type": "required_reviewers", "prevent_self_review": env["preventSelfReview"], "reviewers": reviewers })); |
| 331 | } |
| 332 | if env["waitMinutes"].as_u64().unwrap_or(0) > 0 { |
| 333 | rules.push(json!({ "type": "wait_timer", "wait_timer": env["waitMinutes"] })); |
| 334 | } |
| 335 | let policy = env["branchPolicy"].as_str().unwrap_or("all"); |
| 336 | if policy != "all" { |
| 337 | rules.push(json!({ "type": "branch_policy" })); |
| 338 | } |
| 339 | json!({ |
| 340 | "name": env["name"], |
| 341 | "protection_rules": rules, |
| 342 | "deployment_branch_policy": match policy { |
| 343 | "protected" => json!({ "protected_branches": true, "custom_branch_policies": false }), |
| 344 | "selected" => json!({ "protected_branches": false, "custom_branch_policies": true }), |
| 345 | _ => Value::Null, |
| 346 | }, |
| 347 | "branch_policies": env["branchPatterns"], |
| 348 | "can_admins_bypass": env["adminsBypass"], |
| 349 | "protected": env["protected"], |
| 350 | "updated_at": env["updatedAt"], |
| 351 | "updated_by": env["updatedBy"], |
| 352 | }) |
| 353 | } |
| 354 | |
| 355 | /// A pending deployment, in the standard shape. |
| 356 | fn pending_view(pending: &Value) -> Value { |
| 357 | let reviewers: Vec<Value> = pending["reviewers"] |
| 358 | .as_array() |
| 359 | .map(|list| { |
| 360 | list.iter() |
| 361 | .map(|r| match r["type"].as_str() { |
| 362 | Some("team") => json!({ "type": "Team", "reviewer": { "slug": r["name"] } }), |
| 363 | _ => json!({ "type": "User", "reviewer": { "login": r["name"] } }), |
| 364 | }) |
| 365 | .collect() |
| 366 | }) |
| 367 | .unwrap_or_default(); |
| 368 | json!({ |
| 369 | "environment": { "name": pending["environment"] }, |
| 370 | "state": pending["state"], |
| 371 | "needs_review": pending["needsReview"], |
| 372 | "wait_until": pending["waitUntil"], |
| 373 | "current_user_can_approve": pending["canReview"], |
| 374 | "reviewers": reviewers, |
| 375 | "jobs": pending["jobs"], |
| 376 | "reviewed_by": pending["reviewedBy"], |
| 377 | "comment": pending["comment"], |
| 378 | "reviewed_at": pending["reviewedAt"], |
| 379 | }) |
| 380 | } |
| 381 | |
| 382 | fn map<T>(outcome: Outcome<T>, view: impl FnOnce(T) -> Value) -> Outcome<Value> { |
| 383 | match outcome { |
| 384 | Outcome::Ok(value) => Outcome::Ok(view(value)), |
| 385 | Outcome::Fail(refused) => Outcome::Fail(refused), |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | /// The protection rules of the environments `listed` (the deployments |
| 390 | /// service's answer to `list_environments` or `get_environment`) added to |
| 391 | /// it, and environments with rules but no deployments yet added to a list. |
| 392 | pub(crate) async fn with_protection(services: &Services, viewer: &Viewer, input: &Value, listed: Outcome<Value>, one: Option<&str>) -> Result<Outcome<Value>> { |
| 393 | let Some(repo) = repo_path(input) else { return Ok(listed) }; |
| 394 | let mut args = json!({ "viewer": viewer, "repo": repo }); |
| 395 | if let Some(name) = one { |
| 396 | args["name"] = json!(name); |
| 397 | } |
| 398 | let rules: Outcome<Vec<Value>> = g1t_kit::call(&services.actions, "environments", &args).await.unwrap_or(Outcome::Ok(Vec::new())); |
| 399 | let rules = match rules { |
| 400 | Outcome::Ok(rules) => rules, |
| 401 | Outcome::Fail(_) => return Ok(listed), |
| 402 | }; |
| 403 | let protection = |name: &str| rules.iter().find(|env| env["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name))).map(environment_view); |
| 404 | let add = |env: &mut Value| { |
| 405 | if let Some(view) = env["name"].as_str().and_then(protection) { |
| 406 | for key in ["protection_rules", "deployment_branch_policy", "branch_policies", "can_admins_bypass"] { |
| 407 | env[key] = view[key].clone(); |
| 408 | } |
| 409 | } |
| 410 | }; |
| 411 | Ok(match (listed, one) { |
| 412 | (Outcome::Ok(mut env), Some(_)) => { |
| 413 | add(&mut env); |
| 414 | Outcome::Ok(env) |
| 415 | } |
| 416 | // Never deployed, but protected: still an environment. |
| 417 | (Outcome::Fail(refused), Some(name)) => match protection(name).filter(|view| view["protected"] == true) { |
| 418 | Some(view) => Outcome::Ok(view), |
| 419 | None => Outcome::Fail(refused), |
| 420 | }, |
| 421 | (Outcome::Ok(mut list), None) => { |
| 422 | if let Some(environments) = list["environments"].as_array_mut() { |
| 423 | for env in environments.iter_mut() { |
| 424 | add(env); |
| 425 | } |
| 426 | for env in rules.iter().filter(|env| env["protected"] == true) { |
| 427 | let name = env["name"].as_str().unwrap_or_default(); |
| 428 | if !environments.iter().any(|known| known["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name))) { |
| 429 | environments.push(environment_view(env)); |
| 430 | } |
| 431 | } |
| 432 | } |
| 433 | Outcome::Ok(list) |
| 434 | } |
| 435 | (failed, None) => failed, |
| 436 | }) |
| 437 | } |
| 438 | |
| 439 | /// A workspace's policy, in the standard shape. |
| 440 | fn workspace_view(settings: &Value) -> Value { |
| 441 | json!({ |
| 442 | "default_workflow_permissions": settings["defaultPermissions"], |
| 443 | "max_workflow_permissions": settings["maxPermissions"], |
| 444 | "can_approve_pull_request_reviews": settings["canApprovePullRequests"], |
| 445 | }) |
| 446 | } |
| 447 | |
| 448 | pub async fn run(op: ProtectionOp, services: &Services, viewer: &Viewer, input: &Value) -> Result<Outcome<Value>> { |
| 449 | if op.writes() && viewer.is_none() { |
| 450 | return Ok(Outcome::fail(FailureCode::Unauthenticated, "This needs a g1t access token.")); |
| 451 | } |
| 452 | let actor = || viewer.clone().unwrap_or_default(); |
| 453 | let actions = &services.actions; |
| 454 | if !op.needs_repo() { |
| 455 | let Some(workspace) = text(input, "workspace") else { |
| 456 | return Ok(Outcome::fail(FailureCode::Invalid, "Name the workspace.")); |
| 457 | }; |
| 458 | let settings: Outcome<Value> = if op == ProtectionOp::GetWorkspaceWorkflowPermissions { |
| 459 | g1t_kit::call(actions, "workspace_actions_settings", &json!({ "viewer": viewer, "workspace": workspace })).await? |
| 460 | } else { |
| 461 | g1t_kit::call( |
| 462 | actions, |
| 463 | "set_workspace_actions_settings", |
| 464 | &json!({ |
| 465 | "actor": actor(), |
| 466 | "workspace": workspace, |
| 467 | "defaultPermissions": text(input, "default_workflow_permissions"), |
| 468 | "maxPermissions": text(input, "max_workflow_permissions"), |
| 469 | "canApprovePullRequests": flag(input, "can_approve_pull_request_reviews"), |
| 470 | }), |
| 471 | ) |
| 472 | .await? |
| 473 | }; |
| 474 | return Ok(map(settings, |s| workspace_view(&s))); |
| 475 | } |
| 476 | let Some(repo) = repo_path(input) else { |
| 477 | return Ok(Outcome::fail(FailureCode::Invalid, "Give the repository as \"owner/name\".")); |
| 478 | }; |
| 479 | let id = text(input, "id").unwrap_or_default(); |
| 480 | let environment = text(input, "environment").unwrap_or_default(); |
| 481 | Ok(match op { |
| 482 | ProtectionOp::UpdateEnvironment => { |
| 483 | let mut args = match environment_change(input) { |
| 484 | Ok(args) => args, |
| 485 | Err(message) => return Ok(Outcome::fail(FailureCode::Invalid, message)), |
| 486 | }; |
| 487 | args.insert("actor".into(), serde_json::to_value(actor())?); |
| 488 | args.insert("repo".into(), serde_json::to_value(&repo)?); |
| 489 | args.insert("name".into(), environment.into()); |
| 490 | let saved: Outcome<Value> = g1t_kit::call(actions, "set_environment", &Value::Object(args)).await?; |
| 491 | map(saved, |env| environment_view(&env)) |
| 492 | } |
| 493 | ProtectionOp::DeleteEnvironment => { |
| 494 | let removed: Outcome<bool> = |
| 495 | g1t_kit::call(actions, "delete_environment", &json!({ "actor": actor(), "repo": repo, "name": environment })).await?; |
| 496 | map(removed, |removed| json!({ "deleted": removed })) |
| 497 | } |
| 498 | ProtectionOp::GetPendingDeployments => { |
| 499 | let pending: Outcome<Vec<Value>> = g1t_kit::call(actions, "pending_deployments", &json!({ "viewer": viewer, "repo": repo, "id": id })).await?; |
| 500 | map(pending, |list| Value::Array(list.iter().map(pending_view).collect())) |
| 501 | } |
| 502 | ProtectionOp::ReviewPendingDeployments => { |
| 503 | let names: Vec<String> = ["environment_names", "environments", "environment_ids"] |
| 504 | .iter() |
| 505 | .find_map(|key| input[*key].as_array()) |
| 506 | .map(|list| list.iter().filter_map(|v| v.as_str().map(str::to_owned).or_else(|| v.as_u64().map(|n| n.to_string()))).collect()) |
| 507 | .unwrap_or_default(); |
| 508 | let reviewed: Outcome<Vec<Value>> = g1t_kit::call( |
| 509 | actions, |
| 510 | "review_deployments", |
| 511 | &json!({ |
| 512 | "actor": actor(), |
| 513 | "repo": repo, |
| 514 | "id": id, |
| 515 | "environments": names, |
| 516 | "state": text(input, "state").unwrap_or_default(), |
| 517 | "comment": text(input, "comment"), |
| 518 | }), |
| 519 | ) |
| 520 | .await?; |
| 521 | map(reviewed, |list| Value::Array(list.iter().map(pending_view).collect())) |
| 522 | } |
| 523 | ProtectionOp::ApproveWorkflowRun => g1t_kit::call(actions, "approve_run", &json!({ "actor": actor(), "repo": repo, "id": id })).await?, |
| 524 | ProtectionOp::GetWorkflowPermissions | ProtectionOp::SetWorkflowPermissions => { |
| 525 | let settings: Outcome<Value> = if op == ProtectionOp::GetWorkflowPermissions { |
| 526 | g1t_kit::call(actions, "actions_settings", &json!({ "viewer": viewer, "repo": repo })).await? |
| 527 | } else { |
| 528 | g1t_kit::call( |
| 529 | actions, |
| 530 | "set_actions_settings", |
| 531 | &json!({ |
| 532 | "actor": actor(), |
| 533 | "repo": repo, |
| 534 | "defaultPermissions": text(input, "default_workflow_permissions"), |
| 535 | "canApprovePullRequests": flag(input, "can_approve_pull_request_reviews"), |
| 536 | }), |
| 537 | ) |
| 538 | .await? |
| 539 | }; |
| 540 | map(settings, |s| { |
| 541 | json!({ |
| 542 | "default_workflow_permissions": s["defaultPermissions"], |
| 543 | "default_chosen": s["defaultChosen"], |
| 544 | "max_workflow_permissions": s["maxPermissions"], |
| 545 | "can_approve_pull_request_reviews": s["canApprovePullRequests"], |
| 546 | }) |
| 547 | }) |
| 548 | } |
| 549 | ProtectionOp::GetForkPrApproval | ProtectionOp::SetForkPrApproval => { |
| 550 | let settings: Outcome<Value> = if op == ProtectionOp::GetForkPrApproval { |
| 551 | g1t_kit::call(actions, "actions_settings", &json!({ "viewer": viewer, "repo": repo })).await? |
| 552 | } else { |
| 553 | g1t_kit::call( |
| 554 | actions, |
| 555 | "set_actions_settings", |
| 556 | &json!({ "actor": actor(), "repo": repo, "approvalPolicy": text(input, "approval_policy").unwrap_or_default() }), |
| 557 | ) |
| 558 | .await? |
| 559 | }; |
| 560 | map(settings, |s| json!({ "approval_policy": s["approvalPolicy"] })) |
| 561 | } |
| 562 | ProtectionOp::GetActionsAccess | ProtectionOp::SetActionsAccess => { |
| 563 | let settings: Outcome<Value> = if op == ProtectionOp::GetActionsAccess { |
| 564 | g1t_kit::call(actions, "actions_settings", &json!({ "viewer": viewer, "repo": repo })).await? |
| 565 | } else { |
| 566 | g1t_kit::call( |
| 567 | actions, |
| 568 | "set_actions_settings", |
| 569 | &json!({ "actor": actor(), "repo": repo, "accessLevel": text(input, "access_level").unwrap_or_default() }), |
| 570 | ) |
| 571 | .await? |
| 572 | }; |
| 573 | map(settings, |s| json!({ "access_level": s["accessLevel"] })) |
| 574 | } |
| 575 | ProtectionOp::CreateRepositoryDispatch => { |
| 576 | let started: Outcome<u32> = g1t_kit::call( |
| 577 | actions, |
| 578 | "repository_dispatch", |
| 579 | &json!({ |
| 580 | "actor": actor(), |
| 581 | "repo": repo, |
| 582 | "eventType": text(input, "event_type").unwrap_or_default(), |
| 583 | "clientPayload": input.get("client_payload").cloned().unwrap_or(Value::Null), |
| 584 | }), |
| 585 | ) |
| 586 | .await?; |
| 587 | map(started, |runs| json!({ "runs": runs })) |
| 588 | } |
| 589 | // Answered above, before a repository is read. |
| 590 | ProtectionOp::GetWorkspaceWorkflowPermissions | ProtectionOp::SetWorkspaceWorkflowPermissions => { |
| 591 | Outcome::fail(FailureCode::Invalid, "Name the workspace.") |
| 592 | } |
| 593 | }) |
| 594 | } |
| 595 | |
| 596 | #[cfg(test)] |
| 597 | mod tests { |
| 598 | use super::*; |
| 599 | |
| 600 | #[test] |
| 601 | fn an_environment_change_reads_the_standard_shape() { |
| 602 | let args = environment_change(&json!({ |
| 603 | "wait_timer": 30, |
| 604 | "prevent_self_review": true, |
| 605 | "reviewers": [{ "type": "User", "id": "ada" }, { "type": "Team", "name": "deployers" }], |
| 606 | "deployment_branch_policy": { "protected_branches": false, "custom_branch_policies": true }, |
| 607 | "branch_policies": [{ "name": "release/*", "type": "branch" }], |
| 608 | })) |
| 609 | .unwrap(); |
| 610 | assert_eq!(args["waitMinutes"], 30); |
| 611 | assert_eq!(args["preventSelfReview"], true); |
| 612 | assert_eq!(args["reviewers"], json!([{ "type": "user", "name": "ada" }, { "type": "team", "name": "deployers" }])); |
| 613 | assert_eq!(args["branchPolicy"], "selected"); |
| 614 | assert_eq!(args["branchPatterns"], json!([{ "name": "release/*", "type": "branch" }])); |
| 615 | // Left out stays; null clears. |
| 616 | let cleared = environment_change(&json!({ "deployment_branch_policy": null, "reviewers": null })).unwrap(); |
| 617 | assert_eq!(cleared["branchPolicy"], "all"); |
| 618 | assert_eq!(cleared["reviewers"], json!([])); |
| 619 | assert!(!environment_change(&json!({})).unwrap().contains_key("waitMinutes")); |
| 620 | assert!(environment_change(&json!({ "deployment_branch_policy": { "protected_branches": true, "custom_branch_policies": true } })).is_err()); |
| 621 | } |
| 622 | |
| 623 | #[test] |
| 624 | fn an_environment_reads_as_the_standard_shape() { |
| 625 | let view = environment_view(&json!({ |
| 626 | "name": "production", "reviewers": [{ "type": "user", "name": "ada" }], "preventSelfReview": true, |
| 627 | "waitMinutes": 10, "branchPolicy": "protected", "branchPatterns": [], "adminsBypass": false, "protected": true, |
| 628 | })); |
| 629 | let types: Vec<&str> = view["protection_rules"].as_array().unwrap().iter().map(|r| r["type"].as_str().unwrap()).collect(); |
| 630 | assert_eq!(types, ["required_reviewers", "wait_timer", "branch_policy"]); |
| 631 | assert_eq!(view["protection_rules"][0]["reviewers"][0]["reviewer"]["login"], "ada"); |
| 632 | assert_eq!(view["deployment_branch_policy"]["protected_branches"], true); |
| 633 | assert_eq!(view["can_admins_bypass"], false); |
| 634 | } |
| 635 | |
| 636 | #[test] |
| 637 | fn each_operation_is_described_with_a_schema() { |
| 638 | for op in ProtectionOp::ALL { |
| 639 | assert!(!op.title().is_empty() && op.description().len() > 40, "{}", op.name()); |
| 640 | let needs = if op.needs_repo() { "repo" } else { "workspace" }; |
| 641 | assert!(op.input()["required"].as_array().unwrap().contains(&json!(needs)), "{}", op.name()); |
| 642 | } |
| 643 | } |
| 644 | } |