Skip to content
531 linesCodeBlameRaw

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.

Actions: keep workflow runs safe1//! 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
9use g1t_contracts::{FailureCode, Outcome, Viewer};
10use serde_json::{Map, Value, json};
11use worker::Result;
12
13use crate::operations::{Services, repo_path};
14
15/// One operation.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum ProtectionOp {
18 UpdateEnvironment,
19 DeleteEnvironment,
20 GetPendingDeployments,
21 ReviewPendingDeployments,
22 ApproveWorkflowRun,
23 GetWorkflowPermissions,
24 SetWorkflowPermissions,
25 GetForkPrApproval,
26 SetForkPrApproval,
27 CreateRepositoryDispatch,
28}
29
30impl ProtectionOp {
31 /// Every one: `Op::ALL` lists each as `Op::Protection(…)`, which a test
32 /// checks against this.
33 #[cfg(test)]
34 pub const ALL: [ProtectionOp; 10] = [
35 ProtectionOp::UpdateEnvironment,
36 ProtectionOp::DeleteEnvironment,
37 ProtectionOp::GetPendingDeployments,
38 ProtectionOp::ReviewPendingDeployments,
39 ProtectionOp::ApproveWorkflowRun,
40 ProtectionOp::GetWorkflowPermissions,
41 ProtectionOp::SetWorkflowPermissions,
42 ProtectionOp::GetForkPrApproval,
43 ProtectionOp::SetForkPrApproval,
44 ProtectionOp::CreateRepositoryDispatch,
45 ];
46
47 pub fn name(self) -> &'static str {
48 match self {
49 ProtectionOp::UpdateEnvironment => "update_environment",
50 ProtectionOp::DeleteEnvironment => "delete_environment",
51 ProtectionOp::GetPendingDeployments => "get_pending_deployments",
52 ProtectionOp::ReviewPendingDeployments => "review_pending_deployments",
53 ProtectionOp::ApproveWorkflowRun => "approve_workflow_run",
54 ProtectionOp::GetWorkflowPermissions => "get_workflow_permissions",
55 ProtectionOp::SetWorkflowPermissions => "set_workflow_permissions",
56 ProtectionOp::GetForkPrApproval => "get_fork_pr_approval",
57 ProtectionOp::SetForkPrApproval => "set_fork_pr_approval",
58 ProtectionOp::CreateRepositoryDispatch => "create_repository_dispatch",
59 }
60 }
61
62 pub fn title(self) -> &'static str {
63 match self {
64 ProtectionOp::UpdateEnvironment => "Create or update an environment's protection rules",
65 ProtectionOp::DeleteEnvironment => "Delete an environment's protection rules",
66 ProtectionOp::GetPendingDeployments => "Get a run's pending deployments",
67 ProtectionOp::ReviewPendingDeployments => "Review a run's pending deployments",
68 ProtectionOp::ApproveWorkflowRun => "Approve a workflow run",
69 ProtectionOp::GetWorkflowPermissions => "Get the default workflow permissions",
70 ProtectionOp::SetWorkflowPermissions => "Set the default workflow permissions",
71 ProtectionOp::GetForkPrApproval => "Get the approval policy for outside pull requests",
72 ProtectionOp::SetForkPrApproval => "Set the approval policy for outside pull requests",
73 ProtectionOp::CreateRepositoryDispatch => "Create a repository dispatch event",
74 }
75 }
76
77 pub fn description(self) -> &'static str {
78 match self {
79 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.",
80 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.",
81 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.",
82 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.",
83 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.",
84 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; the default) or write (every permission). can_approve_pull_request_reviews is always false: a job's token never approves pull requests. Needs the Read role.",
85 ProtectionOp::SetWorkflowPermissions => "Set default_workflow_permissions to read or write. 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.",
86 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.",
87 ProtectionOp::SetForkPrApproval => "Set approval_policy: first_time_contributors, outside_contributors or all_external_contributors. Needs the Admin role.",
88 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.",
89 }
90 }
91
92 /// Whether it changes anything (the caller is its actor).
93 pub fn writes(self) -> bool {
94 !matches!(self, ProtectionOp::GetPendingDeployments | ProtectionOp::GetWorkflowPermissions | ProtectionOp::GetForkPrApproval)
95 }
96
97 pub fn input(self) -> Value {
98 let repo = json!({ "type": "string", "description": "Repository as \"owner/name\", e.g. \"flagon-io/hello\"." });
99 let run = json!({ "type": "string", "description": "The run's id, run_…." });
100 let environment = json!({ "type": "string", "description": "The environment's name, such as production." });
101 let (properties, required): (Value, &[&str]) = match self {
102 ProtectionOp::UpdateEnvironment => (
103 json!({
104 "repo": repo,
105 "environment": environment,
106 "wait_timer": { "type": "integer", "description": "Minutes each job waits before it may start, 0 to 43200." },
107 "prevent_self_review": { "type": "boolean", "description": "Whoever started a run may not approve its jobs." },
108 "reviewers": {
109 "type": ["array", "null"],
110 "description": "Up to 6 people or teams who may approve its jobs; empty for none.",
111 "items": {
112 "type": "object",
113 "properties": {
114 "type": { "type": "string", "enum": ["User", "Team"] },
115 "name": { "type": "string", "description": "A username, or a team's slug in the repository's workspace." },
116 },
117 },
118 },
119 "deployment_branch_policy": {
120 "type": ["object", "null"],
121 "description": "null: every branch may deploy. protected_branches: only protected ones. custom_branch_policies: only those in branch_policies.",
122 "properties": {
123 "protected_branches": { "type": "boolean" },
124 "custom_branch_policies": { "type": "boolean" },
125 },
126 },
127 "branch_policies": {
128 "type": "array",
129 "description": "With custom_branch_policies: the branches and tags that may deploy, at most 50.",
130 "items": {
131 "type": "object",
132 "properties": {
133 "name": { "type": "string", "description": "A pattern, such as main, release/* or v*." },
134 "type": { "type": "string", "enum": ["branch", "tag"] },
135 },
136 },
137 },
138 "can_admins_bypass": { "type": "boolean", "description": "Admins may approve without being reviewers, skipping the wait. True unless you say." },
139 }),
140 &["repo", "environment"],
141 ),
142 ProtectionOp::DeleteEnvironment => (json!({ "repo": repo, "environment": environment }), &["repo", "environment"]),
143 ProtectionOp::GetPendingDeployments | ProtectionOp::ApproveWorkflowRun => (json!({ "repo": repo, "id": run }), &["repo", "id"]),
144 ProtectionOp::ReviewPendingDeployments => (
145 json!({
146 "repo": repo,
147 "id": run,
148 "environment_names": { "type": "array", "items": { "type": "string" }, "description": "The environments to review; every waiting one if left out." },
149 "state": { "type": "string", "enum": ["approved", "rejected"] },
150 "comment": { "type": "string", "description": "Why, kept with the review." },
151 }),
152 &["repo", "id", "state"],
153 ),
154 ProtectionOp::GetWorkflowPermissions | ProtectionOp::GetForkPrApproval => (json!({ "repo": repo }), &["repo"]),
155 ProtectionOp::SetWorkflowPermissions => (
156 json!({
157 "repo": repo,
158 "default_workflow_permissions": { "type": "string", "enum": ["read", "write"] },
159 }),
160 &["repo", "default_workflow_permissions"],
161 ),
162 ProtectionOp::SetForkPrApproval => (
163 json!({
164 "repo": repo,
165 "approval_policy": { "type": "string", "enum": ["first_time_contributors", "outside_contributors", "all_external_contributors"] },
166 }),
167 &["repo", "approval_policy"],
168 ),
169 ProtectionOp::CreateRepositoryDispatch => (
170 json!({
171 "repo": repo,
172 "event_type": { "type": "string", "description": "What happened, 1 to 100 characters; workflows choose it with `types:`." },
173 "client_payload": { "type": "object", "description": "Anything the workflows should read, as github.event.client_payload." },
174 }),
175 &["repo", "event_type"],
176 ),
177 };
178 json!({ "type": "object", "properties": properties, "required": required })
179 }
180}
181
182fn text(input: &Value, key: &str) -> Option<String> {
183 match &input[key] {
184 Value::String(text) if !text.trim().is_empty() => Some(text.trim().to_owned()),
185 Value::Number(number) => Some(number.to_string()),
186 _ => None,
187 }
188}
189
190fn flag(input: &Value, key: &str) -> Option<bool> {
191 match &input[key] {
192 Value::Bool(value) => Some(*value),
193 Value::String(text) => match text.trim() {
194 "true" | "1" => Some(true),
195 "false" | "0" => Some(false),
196 _ => None,
197 },
198 _ => None,
199 }
200}
201
202/// The actions service's arguments for an environment's change, from a
203/// request shaped as the standard environments API is.
204pub(crate) fn environment_change(input: &Value) -> std::result::Result<Map<String, Value>, String> {
205 let mut out = Map::new();
206 if let Some(minutes) = input.get("wait_timer").filter(|v| !v.is_null()) {
207 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.")?;
208 out.insert("waitMinutes".into(), minutes.into());
209 }
210 if let Some(value) = flag(input, "prevent_self_review") {
211 out.insert("preventSelfReview".into(), value.into());
212 }
213 if let Some(value) = flag(input, "can_admins_bypass") {
214 out.insert("adminsBypass".into(), value.into());
215 }
216 match input.get("reviewers") {
217 None => {}
218 Some(Value::Null) => {
219 out.insert("reviewers".into(), json!([]));
220 }
221 Some(Value::Array(given)) => {
222 let mut reviewers = Vec::new();
223 for reviewer in given {
224 let kind = reviewer["type"].as_str().unwrap_or("User").to_ascii_lowercase();
225 let name = text(reviewer, "name").or_else(|| text(reviewer, "id")).or_else(|| text(reviewer, "login")).or_else(|| text(reviewer, "slug"));
226 let Some(name) = name else { return Err("Each reviewer has a name: a username or a team's slug.".to_owned()) };
227 reviewers.push(json!({ "type": kind, "name": name }));
228 }
229 out.insert("reviewers".into(), Value::Array(reviewers));
230 }
231 Some(_) => return Err("reviewers is a list of {\"type\", \"name\"}.".to_owned()),
232 }
233 match input.get("deployment_branch_policy") {
234 None => {}
235 Some(Value::Null) => {
236 out.insert("branchPolicy".into(), "all".into());
237 }
238 Some(policy @ Value::Object(_)) => {
239 let protected = flag(policy, "protected_branches") == Some(true);
240 let custom = flag(policy, "custom_branch_policies") == Some(true);
241 let chosen = match (protected, custom) {
242 (true, true) => return Err("deployment_branch_policy is protected_branches or custom_branch_policies, not both.".to_owned()),
243 (true, false) => "protected",
244 (false, true) => "selected",
245 (false, false) => "all",
246 };
247 out.insert("branchPolicy".into(), chosen.into());
248 }
249 Some(_) => return Err("deployment_branch_policy is an object, or null.".to_owned()),
250 }
251 if let Some(Value::Array(patterns)) = input.get("branch_policies") {
252 let patterns: Vec<Value> = patterns
253 .iter()
254 .map(|pattern| json!({ "name": pattern["name"].as_str().unwrap_or_default(), "type": pattern["type"].as_str().unwrap_or("branch") }))
255 .collect();
256 out.insert("branchPatterns".into(), Value::Array(patterns));
257 }
258 Ok(out)
259}
260
261/// An environment as the actions service keeps it (camelCase), in the
262/// standard shape: `protection_rules`, `deployment_branch_policy` and
263/// `can_admins_bypass`, with g1t's `branch_policies` beside them.
264pub(crate) fn environment_view(env: &Value) -> Value {
265 let reviewers: Vec<Value> = env["reviewers"]
266 .as_array()
267 .map(|list| {
268 list.iter()
269 .map(|r| match r["type"].as_str() {
270 Some("team") => json!({ "type": "Team", "reviewer": { "slug": r["name"] } }),
271 _ => json!({ "type": "User", "reviewer": { "login": r["name"] } }),
272 })
273 .collect()
274 })
275 .unwrap_or_default();
276 let mut rules = Vec::new();
277 if !reviewers.is_empty() {
278 rules.push(json!({ "type": "required_reviewers", "prevent_self_review": env["preventSelfReview"], "reviewers": reviewers }));
279 }
280 if env["waitMinutes"].as_u64().unwrap_or(0) > 0 {
281 rules.push(json!({ "type": "wait_timer", "wait_timer": env["waitMinutes"] }));
282 }
283 let policy = env["branchPolicy"].as_str().unwrap_or("all");
284 if policy != "all" {
285 rules.push(json!({ "type": "branch_policy" }));
286 }
287 json!({
288 "name": env["name"],
289 "protection_rules": rules,
290 "deployment_branch_policy": match policy {
291 "protected" => json!({ "protected_branches": true, "custom_branch_policies": false }),
292 "selected" => json!({ "protected_branches": false, "custom_branch_policies": true }),
293 _ => Value::Null,
294 },
295 "branch_policies": env["branchPatterns"],
296 "can_admins_bypass": env["adminsBypass"],
297 "protected": env["protected"],
298 "updated_at": env["updatedAt"],
299 "updated_by": env["updatedBy"],
300 })
301}
302
303/// A pending deployment, in the standard shape.
304fn pending_view(pending: &Value) -> Value {
305 let reviewers: Vec<Value> = pending["reviewers"]
306 .as_array()
307 .map(|list| {
308 list.iter()
309 .map(|r| match r["type"].as_str() {
310 Some("team") => json!({ "type": "Team", "reviewer": { "slug": r["name"] } }),
311 _ => json!({ "type": "User", "reviewer": { "login": r["name"] } }),
312 })
313 .collect()
314 })
315 .unwrap_or_default();
316 json!({
317 "environment": { "name": pending["environment"] },
318 "state": pending["state"],
319 "needs_review": pending["needsReview"],
320 "wait_until": pending["waitUntil"],
321 "current_user_can_approve": pending["canReview"],
322 "reviewers": reviewers,
323 "jobs": pending["jobs"],
324 "reviewed_by": pending["reviewedBy"],
325 "comment": pending["comment"],
326 "reviewed_at": pending["reviewedAt"],
327 })
328}
329
330fn map<T>(outcome: Outcome<T>, view: impl FnOnce(T) -> Value) -> Outcome<Value> {
331 match outcome {
332 Outcome::Ok(value) => Outcome::Ok(view(value)),
333 Outcome::Fail(refused) => Outcome::Fail(refused),
334 }
335}
336
337/// The protection rules of the environments `listed` (the deployments
338/// service's answer to `list_environments` or `get_environment`) added to
339/// it, and environments with rules but no deployments yet added to a list.
340pub(crate) async fn with_protection(services: &Services, viewer: &Viewer, input: &Value, listed: Outcome<Value>, one: Option<&str>) -> Result<Outcome<Value>> {
341 let Some(repo) = repo_path(input) else { return Ok(listed) };
342 let mut args = json!({ "viewer": viewer, "repo": repo });
343 if let Some(name) = one {
344 args["name"] = json!(name);
345 }
346 let rules: Outcome<Vec<Value>> = g1t_kit::call(&services.actions, "environments", &args).await.unwrap_or(Outcome::Ok(Vec::new()));
347 let rules = match rules {
348 Outcome::Ok(rules) => rules,
349 Outcome::Fail(_) => return Ok(listed),
350 };
351 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);
352 let add = |env: &mut Value| {
353 if let Some(view) = env["name"].as_str().and_then(protection) {
354 for key in ["protection_rules", "deployment_branch_policy", "branch_policies", "can_admins_bypass"] {
355 env[key] = view[key].clone();
356 }
357 }
358 };
359 Ok(match (listed, one) {
360 (Outcome::Ok(mut env), Some(_)) => {
361 add(&mut env);
362 Outcome::Ok(env)
363 }
364 // Never deployed, but protected: still an environment.
365 (Outcome::Fail(refused), Some(name)) => match protection(name).filter(|view| view["protected"] == true) {
366 Some(view) => Outcome::Ok(view),
367 None => Outcome::Fail(refused),
368 },
369 (Outcome::Ok(mut list), None) => {
370 if let Some(environments) = list["environments"].as_array_mut() {
371 for env in environments.iter_mut() {
372 add(env);
373 }
374 for env in rules.iter().filter(|env| env["protected"] == true) {
375 let name = env["name"].as_str().unwrap_or_default();
376 if !environments.iter().any(|known| known["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name))) {
377 environments.push(environment_view(env));
378 }
379 }
380 }
381 Outcome::Ok(list)
382 }
383 (failed, None) => failed,
384 })
385}
386
387pub async fn run(op: ProtectionOp, services: &Services, viewer: &Viewer, input: &Value) -> Result<Outcome<Value>> {
388 let Some(repo) = repo_path(input) else {
389 return Ok(Outcome::fail(FailureCode::Invalid, "Give the repository as \"owner/name\"."));
390 };
391 if op.writes() && viewer.is_none() {
392 return Ok(Outcome::fail(FailureCode::Unauthenticated, "This needs a g1t access token."));
393 }
394 let actor = || viewer.clone().unwrap_or_default();
395 let actions = &services.actions;
396 let id = text(input, "id").unwrap_or_default();
397 let environment = text(input, "environment").unwrap_or_default();
398 Ok(match op {
399 ProtectionOp::UpdateEnvironment => {
400 let mut args = match environment_change(input) {
401 Ok(args) => args,
402 Err(message) => return Ok(Outcome::fail(FailureCode::Invalid, message)),
403 };
404 args.insert("actor".into(), serde_json::to_value(actor())?);
405 args.insert("repo".into(), serde_json::to_value(&repo)?);
406 args.insert("name".into(), environment.into());
407 let saved: Outcome<Value> = g1t_kit::call(actions, "set_environment", &Value::Object(args)).await?;
408 map(saved, |env| environment_view(&env))
409 }
410 ProtectionOp::DeleteEnvironment => {
411 let removed: Outcome<bool> =
412 g1t_kit::call(actions, "delete_environment", &json!({ "actor": actor(), "repo": repo, "name": environment })).await?;
413 map(removed, |removed| json!({ "deleted": removed }))
414 }
415 ProtectionOp::GetPendingDeployments => {
416 let pending: Outcome<Vec<Value>> = g1t_kit::call(actions, "pending_deployments", &json!({ "viewer": viewer, "repo": repo, "id": id })).await?;
417 map(pending, |list| Value::Array(list.iter().map(pending_view).collect()))
418 }
419 ProtectionOp::ReviewPendingDeployments => {
420 let names: Vec<String> = ["environment_names", "environments", "environment_ids"]
421 .iter()
422 .find_map(|key| input[*key].as_array())
423 .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())
424 .unwrap_or_default();
425 let reviewed: Outcome<Vec<Value>> = g1t_kit::call(
426 actions,
427 "review_deployments",
428 &json!({
429 "actor": actor(),
430 "repo": repo,
431 "id": id,
432 "environments": names,
433 "state": text(input, "state").unwrap_or_default(),
434 "comment": text(input, "comment"),
435 }),
436 )
437 .await?;
438 map(reviewed, |list| Value::Array(list.iter().map(pending_view).collect()))
439 }
440 ProtectionOp::ApproveWorkflowRun => g1t_kit::call(actions, "approve_run", &json!({ "actor": actor(), "repo": repo, "id": id })).await?,
441 ProtectionOp::GetWorkflowPermissions | ProtectionOp::SetWorkflowPermissions => {
442 let settings: Outcome<Value> = if op == ProtectionOp::GetWorkflowPermissions {
443 g1t_kit::call(actions, "actions_settings", &json!({ "viewer": viewer, "repo": repo })).await?
444 } else {
445 g1t_kit::call(
446 actions,
447 "set_actions_settings",
448 &json!({ "actor": actor(), "repo": repo, "defaultPermissions": text(input, "default_workflow_permissions").unwrap_or_default() }),
449 )
450 .await?
451 };
452 map(settings, |s| json!({ "default_workflow_permissions": s["defaultPermissions"], "can_approve_pull_request_reviews": false }))
453 }
454 ProtectionOp::GetForkPrApproval | ProtectionOp::SetForkPrApproval => {
455 let settings: Outcome<Value> = if op == ProtectionOp::GetForkPrApproval {
456 g1t_kit::call(actions, "actions_settings", &json!({ "viewer": viewer, "repo": repo })).await?
457 } else {
458 g1t_kit::call(
459 actions,
460 "set_actions_settings",
461 &json!({ "actor": actor(), "repo": repo, "approvalPolicy": text(input, "approval_policy").unwrap_or_default() }),
462 )
463 .await?
464 };
465 map(settings, |s| json!({ "approval_policy": s["approvalPolicy"] }))
466 }
467 ProtectionOp::CreateRepositoryDispatch => {
468 let started: Outcome<u32> = g1t_kit::call(
469 actions,
470 "repository_dispatch",
471 &json!({
472 "actor": actor(),
473 "repo": repo,
474 "eventType": text(input, "event_type").unwrap_or_default(),
475 "clientPayload": input.get("client_payload").cloned().unwrap_or(Value::Null),
476 }),
477 )
478 .await?;
479 map(started, |runs| json!({ "runs": runs }))
480 }
481 })
482}
483
484#[cfg(test)]
485mod tests {
486 use super::*;
487
488 #[test]
489 fn an_environment_change_reads_the_standard_shape() {
490 let args = environment_change(&json!({
491 "wait_timer": 30,
492 "prevent_self_review": true,
493 "reviewers": [{ "type": "User", "id": "ada" }, { "type": "Team", "name": "deployers" }],
494 "deployment_branch_policy": { "protected_branches": false, "custom_branch_policies": true },
495 "branch_policies": [{ "name": "release/*", "type": "branch" }],
496 }))
497 .unwrap();
498 assert_eq!(args["waitMinutes"], 30);
499 assert_eq!(args["preventSelfReview"], true);
500 assert_eq!(args["reviewers"], json!([{ "type": "user", "name": "ada" }, { "type": "team", "name": "deployers" }]));
501 assert_eq!(args["branchPolicy"], "selected");
502 assert_eq!(args["branchPatterns"], json!([{ "name": "release/*", "type": "branch" }]));
503 // Left out stays; null clears.
504 let cleared = environment_change(&json!({ "deployment_branch_policy": null, "reviewers": null })).unwrap();
505 assert_eq!(cleared["branchPolicy"], "all");
506 assert_eq!(cleared["reviewers"], json!([]));
507 assert!(!environment_change(&json!({})).unwrap().contains_key("waitMinutes"));
508 assert!(environment_change(&json!({ "deployment_branch_policy": { "protected_branches": true, "custom_branch_policies": true } })).is_err());
509 }
510
511 #[test]
512 fn an_environment_reads_as_the_standard_shape() {
513 let view = environment_view(&json!({
514 "name": "production", "reviewers": [{ "type": "user", "name": "ada" }], "preventSelfReview": true,
515 "waitMinutes": 10, "branchPolicy": "protected", "branchPatterns": [], "adminsBypass": false, "protected": true,
516 }));
517 let types: Vec<&str> = view["protection_rules"].as_array().unwrap().iter().map(|r| r["type"].as_str().unwrap()).collect();
518 assert_eq!(types, ["required_reviewers", "wait_timer", "branch_policy"]);
519 assert_eq!(view["protection_rules"][0]["reviewers"][0]["reviewer"]["login"], "ada");
520 assert_eq!(view["deployment_branch_policy"]["protected_branches"], true);
521 assert_eq!(view["can_admins_bypass"], false);
522 }
523
524 #[test]
525 fn each_operation_is_described_with_a_schema() {
526 for op in ProtectionOp::ALL {
527 assert!(!op.title().is_empty() && op.description().len() > 40, "{}", op.name());
528 assert!(op.input()["required"].as_array().unwrap().contains(&json!("repo")), "{}", op.name());
529 }
530 }
531}