From 16c2eb97753c8d81ac8a94e3e3351a6a54f9b268 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:45:01 -0800 Subject: [PATCH 1/2] feat: required_checks_bypass, the teams that may bypass Require CI sync makes the ruleset's bypass list exactly the configured teams (pull_request or always); sync-from-org and diff read it back, and a list the token can't see or a config can't name is never a clean diff. --- README.md | 10 +- docs/changelog.md | 1 + docs/usage.md | 3 + src/config.rs | 70 ++++++++++ src/github.rs | 317 ++++++++++++++++++++++++++++++++++++++++++---- 5 files changed, 370 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 679ef92..81f8ee7 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ Every command refuses a config with a key it doesn't know before it contacts Git ```text config.yaml: repos[3].settings (repo old-tool): unknown setting `archive`. Did you mean `archived`? ... config.yaml: repos[3].settings (repo old-tool): `default_repository_permission` is not a repository setting: it would be sent to PATCH /orgs/{org}, which is not the repo. ... -config.yaml: repos[3].archived: unknown field `archived`, expected one of `name`, `settings`, `visibility`, `use_default_webhook`, `webhook`, `branch_protections`, `required_checks` +config.yaml: repos[3].archived: unknown field `archived`, expected one of `name`, `settings`, `visibility`, `use_default_webhook`, `webhook`, `branch_protections`, `required_checks`, `required_checks_bypass` ``` **Example `config.yaml`:** @@ -248,6 +248,9 @@ repos: repos: - name: service required_checks: [Format, Unit Tests, "Clippy & Docs"] + required_checks_bypass: # optional: who may merge past the checks, and how + - team: core-team + mode: pull_request # only by merging a PR; `always` also allows direct pushes ``` - `sync` keeps them in the repo's own ruleset named `Require CI`: active, on the default branch (`~DEFAULT_BRANCH`), not strict (a PR needn't be up to date with the branch), one `required_status_checks` rule. It creates the ruleset if the repo has none by that name and rewrites it when its checks (in any order) or any of those properties differ. An existing `Require CI` ruleset is adopted by name. @@ -255,9 +258,10 @@ repos: - `allow_auto_merge` is written after the repo's `Require CI` ruleset, so if the ruleset write fails, auto-merge isn't left on without the checks it waits for. - A name listed twice is refused when the config is loaded. A `Require CI` ruleset that requires one check twice (from different apps) is refused like one with another rule: a config can't say which pin to keep. - gh-config owns every rule in `Require CI`: if it holds any other rule, `sync` stops with an error naming the repo and the rule instead of dropping it. Keep other rules in other rulesets. -- `sync --dry-run` names the checks an update would stop requiring. +- `required_checks_bypass` is the ruleset's whole bypass list: `sync` makes it exactly these teams (by slug), so leaving it out removes every bypass, including the org's admins, apps and roles a ruleset can name but a config can't. `mode` is `pull_request` (merging a PR may skip the checks; a direct push may not) or `always`. A team that isn't in the config's `teams` (when it lists any), a team named twice, an unknown mode, or a bypass list without `required_checks` is refused when the config is loaded; a team the org doesn't have is refused before the repo's ruleset is written. +- `sync --dry-run` names the checks an update would stop requiring, who may bypass them after it and who no longer may. - A repo with no `required_checks` is left alone: `sync` doesn't read or delete its rulesets. To stop requiring checks, delete the ruleset on GitHub and the key. -- `sync-from-org` records the checks of each repo's `Require CI` ruleset, in the file's order when the file names the same ones; `diff` compares them as a set. It costs one rulesets request per repo, plus one when `Require CI` exists. A ruleset that can't be read keeps what the file has, and `diff` names the repo and exits 1. Properties other than the checks aren't recorded, so `diff` shows no change when only those differ; `sync` still corrects them. +- `sync-from-org` records the checks of each repo's `Require CI` ruleset, in the file's order when the file names the same ones; `diff` compares them as a set. It costs one rulesets request per repo, plus one when `Require CI` exists. A ruleset that can't be read keeps what the file has, and `diff` names the repo and exits 1. It records the bypass list too, reading team ids as slugs (one teams request in all). GitHub shows a ruleset's bypass list only to a token that can administer the repo; when it doesn't, or the list holds anything other than the org's teams, the file's list is kept and `diff` names the repo and exits 1. Properties other than the checks and the bypass list aren't recorded, so `diff` shows no change when only those differ; `sync` still corrects them. ### Webhooks diff --git a/docs/changelog.md b/docs/changelog.md index 1994a8e..5b732bc 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -7,6 +7,7 @@ All notable changes to this project will be documented in this file. - `sync` creates repos the config lists and GitHub doesn't have, with their `visibility`. - `sync-from-org` and `diff` record `allow_auto_merge` and private repos' Actions `access_level`, so the drift check keeps them; `sync` reads `access_level` before writing it. - New repo field `required_checks`, kept in the repo ruleset `Require CI`. +- New repo field `required_checks_bypass`: the teams, and only those, that may bypass `Require CI` (`pull_request` or `always`). `sync` writes it, `sync-from-org` and `diff` read it back. ## [v1.3.2] - 2026-11-09 diff --git a/docs/usage.md b/docs/usage.md index 153073f..4b34ef9 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -53,6 +53,9 @@ repos: # (list) Repository configurations visibility: private # (string, optional) "public" or "private"; required for sync to create a missing repo required_checks: # (list, optional) Checks a PR to the default branch must pass (ruleset `Require CI`) - Unit Tests + required_checks_bypass: # (list, optional) The only teams that may merge past required_checks + - team: core-team # (string) Team slug + mode: pull_request # (string) pull_request (by merging a PR) or always (also direct pushes) webhook: # (object, optional) This repo's own webhook url: "http://example.com" # (string) Webhook endpoint URL content_type: "json" # (string) Payload content type diff --git a/src/config.rs b/src/config.rs index 0cf853e..001dd3b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -88,6 +88,38 @@ pub struct Repo { /// `Require CI` ruleset. Empty: `sync` leaves the repo's rulesets alone. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub required_checks: Vec, + /// The teams that may merge past `required_checks`, and how. Nobody else can: `sync` makes the ruleset's + /// bypass list exactly this, so leaving it out removes every bypass. Needs `required_checks`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub required_checks_bypass: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +/// A team that may bypass a repo's `required_checks`. +pub struct CheckBypass { + /// The team's slug, as in `teams`. + pub team: String, + pub mode: BypassMode, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +/// GitHub's ruleset `bypass_mode`. +pub enum BypassMode { + /// Only by merging a PR; a direct push still has to pass the checks. + PullRequest, + /// By merging a PR or by pushing directly. + Always, +} + +impl BypassMode { + pub fn as_str(self) -> &'static str { + match self { + BypassMode::PullRequest => "pull_request", + BypassMode::Always => "always", + } + } } #[derive(Debug, Serialize, Deserialize, Clone)] // Added Clone @@ -191,6 +223,21 @@ impl Config { repo.name ))); } + let bypass = &repo.required_checks_bypass; + let bypass_problem = if !bypass.is_empty() && checks.is_empty() { + Some("a bypass list needs `required_checks`: without them `sync` leaves the repo's rulesets alone.".to_string()) + } else if let Some(dup) = bypass.iter().enumerate().find_map(|(j, b)| bypass.iter().take(j).any(|x| x.team == b.team).then_some(&b.team)) { + Some(format!("team `{dup}` is listed twice.")) + } else { + let unknown = bypass.iter().find(|b| !config.teams.is_empty() && !config.teams.iter().any(|t| t.name == b.team)); + unknown.map(|b| format!("team `{}` isn't one of the config's `teams`.", b.team)) + }; + if let Some(problem) = bypass_problem { + return Err(crate::error::AppError::Config(format!( + "{main_path}: repos[{i}].required_checks_bypass (repo {}): {problem}", + repo.name + ))); + } if repo.use_default_webhook && (repo.webhook.is_some() || config.default_webhook.is_none()) { return Err(crate::error::AppError::Config(format!( "{main_path}: repos[{i}] (repo {}): `use_default_webhook` needs a top-level `default_webhook` and no `webhook` of its own.", @@ -373,6 +420,29 @@ allow_force_pushes: false assert!(err.contains("required_checks") && err.contains("`A` is listed twice"), "{err}"); } + #[test] + fn a_bypass_list_names_known_teams_once_with_a_known_mode_and_needs_checks() { + let load = |text: &str| { + let mut file = tempfile::NamedTempFile::new().unwrap(); + std::io::Write::write_all(&mut file, text.as_bytes()).unwrap(); + Config::from_file_with_defaults(file.path().to_str().unwrap(), None).map_err(|e| e.to_string()) + }; + let teams = "teams:\n- name: core\n members: []\n"; + let ok = load(&format!("org: o\nrepos:\n- name: r\n required_checks: [A]\n required_checks_bypass:\n - team: core\n mode: pull_request\n{teams}")).unwrap(); + assert_eq!(ok.repos[0].required_checks_bypass, [CheckBypass { team: "core".into(), mode: BypassMode::PullRequest }]); + for (bypass, expected) in [ + ("[{team: core, mode: sometimes}]", "unknown variant `sometimes`"), + ("[{team: core, mode: always, why: x}]", "unknown field `why`"), + ("[{team: core, mode: always}, {team: core, mode: pull_request}]", "team `core` is listed twice"), + ("[{team: ghosts, mode: always}]", "team `ghosts` isn't one of the config's `teams`"), + ] { + let err = load(&format!("org: o\nrepos:\n- name: r\n required_checks: [A]\n required_checks_bypass: {bypass}\n{teams}")).unwrap_err(); + assert!(err.contains("required_checks_bypass") && err.contains(expected), "{bypass}: {err}"); + } + let err = load(&format!("org: o\nrepos:\n- name: r\n required_checks_bypass: [{{team: core, mode: always}}]\n{teams}")).unwrap_err(); + assert!(err.contains("needs `required_checks`"), "{err}"); + } + #[test] fn test_config_with_branch_protections() { let yaml = r#" diff --git a/src/github.rs b/src/github.rs index 0c93cb3..a8db821 100644 --- a/src/github.rs +++ b/src/github.rs @@ -9,7 +9,7 @@ Public APIs are documented for maintainability. Internal response structs are used for deserialization. */ -use crate::config::{Assignment, Repo, RepoSettings, Team, User, WebhookConfig, Config}; +use crate::config::{Assignment, BypassMode, CheckBypass, Repo, RepoSettings, Team, User, WebhookConfig, Config}; use crate::error::{AppError, AppResult}; use colored::*; use log::{debug, info, error}; @@ -50,10 +50,79 @@ struct RequiredCheck { integration_id: Option, } +/// One entry of a ruleset's bypass list, as GitHub holds it: a team, an app, a role, the org's admins... +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +struct BypassActor { + actor_type: String, + actor_id: Option, + mode: String, +} + +/// The org's teams, `(slug, id)`: a config names a team by slug, a ruleset by id. +type TeamIds = [(String, u64)]; + +impl BypassActor { + fn team(id: u64, mode: BypassMode) -> Self { + BypassActor { actor_type: "Team".into(), actor_id: Some(id), mode: mode.as_str().into() } + } + + /// The config entry for this actor, if a config can name it: a team the org has, with a known mode. + fn as_config(&self, teams: &TeamIds) -> Option { + let team = teams.iter().find(|(_, id)| self.actor_type == "Team" && Some(*id) == self.actor_id)?.0.clone(); + let mode = serde_yaml::from_value(serde_yaml::Value::String(self.mode.clone())).ok()?; + Some(CheckBypass { team, mode }) + } + + /// For people to read. + fn describe(&self, teams: &TeamIds) -> String { + match (self.as_config(teams), self.actor_id) { + (Some(b), _) => format!("{} ({})", b.team, self.mode), + (None, Some(id)) => format!("{} #{id} ({})", self.actor_type, self.mode), + (None, None) => format!("{} ({})", self.actor_type, self.mode), + } + } +} + +/// The bypass list a config's entries stand for, sorted. A team the org doesn't have is refused. +fn bypass_actors(org: &str, repo: &Repo, teams: &TeamIds) -> AppResult> { + let mut actors = repo + .required_checks_bypass + .iter() + .map(|b| { + let id = teams.iter().find(|(slug, _)| *slug == b.team).map(|(_, id)| *id).ok_or_else(|| { + AppError::Config(format!( + "Repo {}: `required_checks_bypass` names team `{}`, which {org} doesn't have. A team the config adds is created after the repos: run sync again once it exists.", + repo.name, b.team + )) + })?; + Ok(BypassActor::team(id, b.mode)) + }) + .collect::>>()?; + actors.sort(); + Ok(actors) +} + +/// The bypass part of a dry run's line: who may bypass after the write, and who no longer may. +fn bypass_change(bypass: &[BypassActor], held: Option<&[BypassActor]>, exists: bool, teams: &TeamIds) -> String { + let named = |actors: &[&BypassActor]| actors.iter().map(|a| a.describe(teams)).collect::>().join(", "); + let allowed = if bypass.is_empty() { "nobody".to_string() } else { named(&bypass.iter().collect::>()) }; + let dropped = match held { + Some(held) => { + let gone: Vec<_> = held.iter().filter(|a| !bypass.contains(a)).collect(); + if gone.is_empty() { String::new() } else { format!("; no longer bypassing: {}", named(&gone)) } + } + None if exists => "; its current bypass list can't be read with this token".to_string(), + None => String::new(), + }; + format!("bypass: {allowed}{dropped}") +} + /// A repo's `Require CI` ruleset as GitHub holds it. struct RequireCi { id: u64, checks: Vec, + /// Sorted. `None` when GitHub didn't say: it shows a ruleset's bypass list only to tokens that can administer the repo. + bypass: Option>, /// Whether everything but the checks is what `sync` writes: active, on the default branch, not strict. standard: bool, } @@ -64,8 +133,15 @@ impl RequireCi { } } -/// The `Require CI` ruleset `sync` writes for `checks`. -fn require_ci_body(checks: &[RequiredCheck]) -> serde_json::Value { +/// The `Require CI` ruleset `sync` writes for `checks`, which only `bypass` may merge past. +fn require_ci_body(checks: &[RequiredCheck], bypass: &[BypassActor]) -> serde_json::Value { + let bypass: Vec<_> = bypass + .iter() + .map(|a| match a.actor_id { + Some(id) => json!({ "actor_id": id, "actor_type": a.actor_type, "bypass_mode": a.mode }), + None => json!({ "actor_type": a.actor_type, "bypass_mode": a.mode }), + }) + .collect(); let checks: Vec<_> = checks .iter() .map(|c| match c.integration_id { @@ -77,6 +153,7 @@ fn require_ci_body(checks: &[RequiredCheck]) -> serde_json::Value { "name": REQUIRE_CI, "target": "branch", "enforcement": "active", + "bypass_actors": bypass, "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } }, "rules": [{ "type": REQUIRED_STATUS_CHECKS, @@ -124,7 +201,19 @@ fn parse_require_ci(repo: &str, ruleset: &serde_json::Value) -> AppResult = actors + .iter() + .map(|a| BypassActor { + actor_type: a["actor_type"].as_str().unwrap_or("?").to_string(), + actor_id: a["actor_id"].as_u64(), + mode: a["bypass_mode"].as_str().unwrap_or("?").to_string(), + }) + .collect(); + actors.sort(); + actors + }); + Ok(RequireCi { id, checks, bypass, standard }) } /// Whether two check lists hold the same names, in any order. @@ -420,12 +509,26 @@ impl GitHubClient { parse_require_ci(repo, &ruleset).map(Some) } - /// Makes the repo's `Require CI` ruleset require exactly `repo.required_checks`. A repo with none is left alone. - async fn sync_required_checks(&self, repo: &Repo, dry_run: bool) -> AppResult<()> { + /// The org's teams as `(slug, id)`. + async fn team_ids(&self) -> AppResult> { + let teams: Vec = self.get_all(&format!("{}/orgs/{}/teams?per_page=100", self.api_url, self.org)).await?; + teams + .iter() + .map(|t| match (t["slug"].as_str(), t["id"].as_u64()) { + (Some(slug), Some(id)) => Ok((slug.to_string(), id)), + _ => Err(AppError::GitHubApi("Missing team slug or id".to_string())), + }) + .collect() + } + + /// Makes the repo's `Require CI` ruleset require exactly `repo.required_checks`, with exactly + /// `repo.required_checks_bypass` allowed past them. A repo with no checks is left alone. + async fn sync_required_checks(&self, repo: &Repo, teams: &TeamIds, dry_run: bool) -> AppResult<()> { let checks = &repo.required_checks; if checks.is_empty() { return Ok(()); } + let bypass = bypass_actors(&self.org, repo, teams)?; let current = self.read_require_ci(&repo.name).await?; let held = current.as_ref().map(|c| c.checks.clone()).unwrap_or_default(); // A check kept from the ruleset keeps the app it's pinned to; a new one has none. @@ -433,8 +536,9 @@ impl GitHubClient { .iter() .map(|name| held.iter().find(|c| &c.context == name).cloned().unwrap_or(RequiredCheck { context: name.clone(), integration_id: None })) .collect(); + let held_bypass = current.as_ref().and_then(|c| c.bypass.clone()); let (method, url) = match current { - Some(current) if current.standard && same_checks(¤t.contexts(), checks) => return Ok(()), + Some(current) if current.standard && same_checks(¤t.contexts(), checks) && current.bypass.as_ref() == Some(&bypass) => return Ok(()), Some(current) => (Method::PUT, format!("{}/repos/{}/{}/rulesets/{}", self.api_url, self.org, repo.name, current.id)), None => (Method::POST, format!("{}/repos/{}/{}/rulesets", self.api_url, self.org, repo.name)), }; @@ -442,11 +546,12 @@ impl GitHubClient { if dry_run { let removed: Vec<_> = held.iter().map(|c| c.context.as_str()).filter(|c| !checks.iter().any(|n| n == c)).collect(); let removed = if removed.is_empty() { String::new() } else { format!("; no longer requiring: {}", removed.join(", ")) }; - println!("[Dry Run] Would {verb} ruleset `{REQUIRE_CI}` on {}/{} requiring: {}{removed}", self.org, repo.name, checks.join(", ")); + let bypass = bypass_change(&bypass, held_bypass.as_deref(), method == Method::PUT, teams); + println!("[Dry Run] Would {verb} ruleset `{REQUIRE_CI}` on {}/{} requiring: {}{removed}; {bypass}", self.org, repo.name, checks.join(", ")); return Ok(()); } - self.client.request(method, &url, "application/vnd.github+json", Some(require_ci_body(&desired))).await?; - info!("Ruleset `{REQUIRE_CI}` on {}/{} now requires: {}", self.org, repo.name, checks.join(", ")); + self.client.request(method, &url, "application/vnd.github+json", Some(require_ci_body(&desired, &bypass))).await?; + info!("Ruleset `{REQUIRE_CI}` on {}/{} now requires: {}; bypass: {}", self.org, repo.name, checks.join(", "), bypass.len()); Ok(()) } @@ -990,6 +1095,13 @@ impl GitHubClient { yaml_content.push_str(&format!(" - {}\n", serde_yaml::to_string(check)?.trim())); } } + if !repo.required_checks_bypass.is_empty() { + yaml_content.push_str(" required_checks_bypass:\n"); + for bypass in &repo.required_checks_bypass { + yaml_content.push_str(&format!(" - team: {}\n", serde_yaml::to_string(&bypass.team)?.trim())); + yaml_content.push_str(&format!(" mode: {}\n", bypass.mode.as_str())); + } + } // Add branch protections if needed if !repo.branch_protections.is_empty() { // Serialize properly @@ -1047,6 +1159,7 @@ impl GitHubClient { // This is essentially the original logic of generate_config_from_org let mut repos = Vec::new(); let mut unread = Vec::new(); + let team_ids = self.team_ids().await?; let repo_url = format!("{}/orgs/{}/repos?per_page=100", self.api_url, self.org); let repo_json: Vec = self.get_all(&repo_url).await?; @@ -1118,16 +1231,39 @@ impl GitHubClient { } }; let file_checks = in_file.map(|r| r.required_checks.clone()).unwrap_or_default(); - let required_checks = match self.read_require_ci(&name).await { - // The file's order when it names the same checks, so regenerating doesn't reorder them. - Ok(found) => match found.map(|r| r.contexts()).unwrap_or_default() { - checks if same_checks(&checks, &file_checks) => file_checks, - checks => checks, - }, + let file_bypass = in_file.map(|r| r.required_checks_bypass.clone()).unwrap_or_default(); + let (required_checks, required_checks_bypass) = match self.read_require_ci(&name).await { + Ok(found) => { + // The file's order when it names the same checks, so regenerating doesn't reorder them. + let checks = match found.as_ref().map(RequireCi::contexts).unwrap_or_default() { + checks if same_checks(&checks, &file_checks) => file_checks, + checks => checks, + }; + let bypass = match found.as_ref().map(|r| r.bypass.as_deref()) { + None => Ok(Vec::new()), + Some(None) => Err("GitHub didn't show its bypass list (it does only to tokens that can administer the repo)".to_string()), + Some(Some(actors)) => actors + .iter() + .map(|a| a.as_config(&team_ids).ok_or_else(|| format!("its bypass list holds {}, which a config can't name", a.describe(&team_ids)))) + .collect::, _>>(), + }; + let bypass = match bypass { + Ok(mut bypass) => { + bypass.sort(); + bypass + } + Err(why) => { + error!("The `{REQUIRE_CI}` ruleset of repo {name}: {why}. Its bypass list stays as the file has it."); + unread.push(format!("{name} (required-check bypass)")); + file_bypass + } + }; + (checks, bypass) + } Err(e) => { error!("Failed to read the `{}` ruleset of repo {}: {}. Its required checks stay as the file has them.", REQUIRE_CI, name, e); unread.push(format!("{name} (required checks)")); - file_checks + (file_checks, file_bypass) } }; @@ -1139,17 +1275,14 @@ impl GitHubClient { webhook, branch_protections: vec![], // Add logic to fetch these if needed required_checks, + required_checks_bypass, }); } // Fetch teams, users, assignments as before (full state needed for generation) let mut teams = Vec::new(); - let team_url = format!("{}/orgs/{}/teams?per_page=100", self.api_url, self.org); - let team_json: Vec = self.get_all(&team_url).await?; - - for team in team_json { + for (name, _) in team_ids { // Fetch full team data including members - let name = team["slug"].as_str().ok_or_else(|| AppError::GitHubApi("Missing team slug".to_string()))?.to_string(); let mut members: Vec = self.get_team_members(&name).await?.into_iter().collect(); members.sort(); @@ -1211,6 +1344,7 @@ impl GitHubClient { // An archived repo is read-only: unarchive before its other changes, archive after all of them, // and leave the settings and webhook of a repo that stays archived alone. let mut to_archive = Vec::new(); + let teams = if config.repos.iter().any(|r| !r.required_checks.is_empty()) { self.team_ids().await? } else { Vec::new() }; for repo in &config.repos { // --- Add logging just before the failing call --- info!("Processing repo: {}/{}", self.org, repo.name); @@ -1264,7 +1398,7 @@ impl GitHubClient { if let Some(webhook) = repo.webhook.as_ref() { self.manage_webhooks(&repo.name, webhook, dry_run).await?; } - self.sync_required_checks(repo, dry_run).await?; + self.sync_required_checks(repo, &teams, dry_run).await?; self.update_repo_settings(repo, ¤t, |k| k == ALLOW_AUTO_MERGE, dry_run).await?; } @@ -1324,9 +1458,10 @@ impl GitHubClient { } } } - // Required checks are a set: their order means nothing. + // Required checks and their bypass list are sets: their order means nothing. for repo in diff_local_config.repos.iter_mut().chain(diff_github_config.repos.iter_mut()) { repo.required_checks.sort(); + repo.required_checks_bypass.sort(); } // --- Step 4: Compare the webhook each repo ends up with --- @@ -1514,10 +1649,30 @@ mod tests { hooks: impl Fn(&str) -> serde_json::Value, rulesets: impl Fn(&str) -> Option>, ) -> Vec { + mock_org_with_teams(server, &[], repos, hooks, rulesets).await + } + + /// `mock_org_full` with teams `(slug, id)`, each with no members and no repos. + async fn mock_org_with_teams( + server: &mut mockito::ServerGuard, + teams: &[(&str, u64)], + repos: &[(&str, serde_json::Value)], + hooks: impl Fn(&str) -> serde_json::Value, + rulesets: impl Fn(&str) -> Option>, + ) -> Vec { + let team_list: Vec<_> = teams.iter().map(|(slug, id)| json!({"slug": slug, "name": slug, "id": id})).collect(); let mut mocks = vec![ - server.mock("GET", "/orgs/o/teams?per_page=100").with_body("[]").create_async().await, + server.mock("GET", "/orgs/o/teams?per_page=100").with_body(json!(team_list).to_string()).create_async().await, server.mock("GET", "/orgs/o/members?per_page=100").with_body("[]").create_async().await, ]; + for (slug, _) in teams { + let url = format!("/orgs/o/teams/{slug}"); + mocks.push(server.mock("GET", url.as_str()).with_body(json!({"name": slug}).to_string()).create_async().await); + for what in ["members", "repos"] { + let url = format!("/orgs/o/teams/{slug}/{what}?per_page=100"); + mocks.push(server.mock("GET", url.as_str()).with_body("[]").create_async().await); + } + } let page = |n: usize| if n == 1 { "/orgs/o/repos?per_page=100".to_string() } else { format!("/orgs/o/repos?per_page=100&page={n}") }; for (i, (name, fields)) in repos.iter().enumerate() { let mut repo = json!({"name": name, "private": false, "visibility": "public", "archived": false, @@ -1562,7 +1717,7 @@ mod tests { /// A `Require CI` ruleset with id `id` requiring `checks`, as `sync` writes it. fn require_ci(id: u64, checks: &[&str]) -> serde_json::Value { - let mut ruleset = require_ci_body(&unpinned(checks)); + let mut ruleset = require_ci_body(&unpinned(checks), &[]); ruleset["id"] = json!(id); ruleset } @@ -2115,7 +2270,7 @@ assignments: client(&server).sync(path, true).await.expect("dry run"); assert!(writes.lock().expect("lock").is_empty(), "a dry run wrote to GitHub"); client(&server).sync(path, false).await.expect("sync"); - let body = |checks: &[&str]| require_ci_body(&unpinned(checks)).to_string(); + let body = |checks: &[&str]| require_ci_body(&unpinned(checks), &[]).to_string(); assert_eq!( *writes.lock().expect("lock"), [format!("POST /repos/o/fresh/rulesets {}", body(&["A", "Clippy & Docs"])), format!("PUT /repos/o/adopt/rulesets/7 {}", body(&["A", "B"]))] @@ -2271,7 +2426,7 @@ assignments: let [put] = writes.as_slice() else { panic!("{writes:?}") }; let sent: serde_json::Value = serde_json::from_str(put.trim_start_matches("PUT /repos/o/r/rulesets/42 ")).expect("json body"); let expected: serde_json::Value = serde_json::from_str(r#"{ - "name": "Require CI", "target": "branch", "enforcement": "active", + "name": "Require CI", "target": "branch", "enforcement": "active", "bypass_actors": [], "conditions": {"ref_name": {"include": ["~DEFAULT_BRANCH"], "exclude": []}}, "rules": [{"type": "required_status_checks", "parameters": { "strict_required_status_checks_policy": false, "do_not_enforce_on_create": false, @@ -2280,6 +2435,112 @@ assignments: assert_eq!(sent, expected); } + /// A `Require CI` ruleset requiring `A`, with `bypass_actors` as given (`None`: GitHub didn't show it). + fn require_a_with(id: u64, bypass: Option) -> serde_json::Value { + let mut ruleset = require_ci(id, &["A"]); + match bypass { + Some(bypass) => ruleset["bypass_actors"] = bypass, + None => drop(ruleset.as_object_mut().expect("object").remove("bypass_actors")), + } + ruleset + } + + #[tokio::test] + async fn an_adopted_ruleset_bypass_list_becomes_exactly_the_configs() { + let mut server = mockito::Server::new_async().await; + // Held: the core team always, the org's admins, an app. Wanted: the core team by PR only, nobody else. + let held = json!([ + {"actor_id": 9, "actor_type": "Team", "bypass_mode": "always"}, + {"actor_id": 1, "actor_type": "OrganizationAdmin", "bypass_mode": "always"}, + {"actor_id": 77, "actor_type": "Integration", "bypass_mode": "pull_request"}, + ]); + let ruleset = require_a_with(42, Some(held.clone())); + let _mocks = mock_org_with_teams(&mut server, &[("core", 9), ("other", 10)], &[("r", json!({}))], |_| json!([]), |_| Some(vec![ruleset.clone()])).await; + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let _put = record(&mut server, &writes, "PUT", "/repos/o/r/rulesets/42").await; + let file = write_file("org: o\nrepos:\n- name: r\n required_checks: [A]\n required_checks_bypass:\n - team: core\n mode: pull_request\n"); + let path = file.path().to_str().expect("utf-8 path"); + + // What GitHub holds can't all be written in a config: diff says so instead of calling it a match. + assert!(client(&server).diff(path).await.expect("diff"), "a bypass list a config can't name was called a match"); + client(&server).sync(path, true).await.expect("dry run"); + assert!(writes.lock().expect("lock").is_empty(), "a dry run wrote to GitHub"); + client(&server).sync(path, false).await.expect("sync"); + let writes = writes.lock().expect("lock"); + let [put] = writes.as_slice() else { panic!("{writes:?}") }; + let sent: serde_json::Value = serde_json::from_str(put.trim_start_matches("PUT /repos/o/r/rulesets/42 ")).expect("json body"); + assert_eq!(sent["bypass_actors"], json!([{"actor_id": 9, "actor_type": "Team", "bypass_mode": "pull_request"}])); + assert_eq!(sent["rules"], ruleset["rules"], "the checks changed"); + } + + #[test] + fn a_dry_run_names_who_may_bypass_and_who_no_longer_may() { + let teams = [("core".to_string(), 9)]; + let core_pr = [BypassActor::team(9, BypassMode::PullRequest)]; + let held = [ + BypassActor::team(9, BypassMode::Always), + BypassActor { actor_type: "OrganizationAdmin".into(), actor_id: Some(1), mode: "always".into() }, + ]; + assert_eq!( + bypass_change(&core_pr, Some(&held), true, &teams), + "bypass: core (pull_request); no longer bypassing: core (always), OrganizationAdmin #1 (always)" + ); + assert_eq!(bypass_change(&[], None, false, &teams), "bypass: nobody"); + assert_eq!(bypass_change(&core_pr, None, true, &teams), "bypass: core (pull_request); its current bypass list can't be read with this token"); + } + + #[tokio::test] + async fn a_teams_bypass_round_trips_and_a_matching_ruleset_is_not_rewritten() { + let mut server = mockito::Server::new_async().await; + let ruleset = require_a_with(5, Some(json!([ + {"actor_id": 10, "actor_type": "Team", "bypass_mode": "always"}, + {"actor_id": 9, "actor_type": "Team", "bypass_mode": "pull_request"}, + ]))); + let _mocks = mock_org_with_teams(&mut server, &[("core", 9), ("other", 10)], &[("r", json!({}))], |_| json!([]), |_| Some(vec![ruleset.clone()])).await; + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let _put = record(&mut server, &writes, "PUT", "/repos/o/r/rulesets/5").await; + let file = write_file("org: o\nrepos:\n- name: r\n required_checks: [A]\n"); + let path = file.path().to_str().expect("utf-8 path"); + client(&server).generate_config_and_write(path, false).await.expect("export"); + let yaml = std::fs::read_to_string(path).expect("read export"); + assert!( + repo_block(&yaml, "r").contains(" required_checks_bypass:\n - team: core\n mode: pull_request\n - team: other\n mode: always\n"), + "{yaml}" + ); + assert!(!client(&server).diff(path).await.expect("diff"), "the exported config doesn't match what it was read from"); + client(&server).sync(path, false).await.expect("sync"); + assert!(writes.lock().expect("lock").is_empty(), "a matching ruleset was rewritten"); + } + + #[tokio::test] + async fn a_bypass_list_the_token_cant_see_is_kept_from_the_file_rewritten_by_sync_and_never_a_clean_diff() { + let mut server = mockito::Server::new_async().await; + let ruleset = require_a_with(5, None); + let _mocks = mock_org_with_teams(&mut server, &[("core", 9)], &[("r", json!({}))], |_| json!([]), |_| Some(vec![ruleset.clone()])).await; + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let _put = record(&mut server, &writes, "PUT", "/repos/o/r/rulesets/5").await; + let file = write_file("org: o\nrepos:\n- name: r\n required_checks: [A]\n required_checks_bypass: [{team: core, mode: pull_request}]\n"); + let path = file.path().to_str().expect("utf-8 path"); + assert!(client(&server).diff(path).await.expect("diff"), "diff called a bypass list it never read a match"); + client(&server).generate_config_and_write(path, false).await.expect("export"); + let yaml = std::fs::read_to_string(path).expect("read export"); + assert!(repo_block(&yaml, "r").contains(" required_checks_bypass:\n - team: core\n mode: pull_request\n"), "{yaml}"); + client(&server).sync(path, false).await.expect("sync"); + assert_eq!(writes.lock().expect("lock").len(), 1, "an unseen bypass list was assumed to match"); + } + + #[tokio::test] + async fn a_bypass_team_the_org_doesnt_have_is_refused_before_any_ruleset_write() { + let mut server = mockito::Server::new_async().await; + let _mocks = mock_org_with_teams(&mut server, &[("core", 9)], &[("r", json!({}))], |_| json!([]), |_| Some(vec![])).await; + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let _post = record(&mut server, &writes, "POST", "/repos/o/r/rulesets").await; + let file = write_file("org: o\nrepos:\n- name: r\n required_checks: [A]\n required_checks_bypass: [{team: ghosts, mode: always}]\n"); + let err = client(&server).sync(file.path().to_str().expect("utf-8 path"), false).await.expect_err("accepted"); + assert!(err.to_string().contains("team `ghosts`"), "{err}"); + assert!(writes.lock().expect("lock").is_empty(), "wrote a ruleset for an unknown team"); + } + #[tokio::test] async fn required_checks_that_cant_be_read_keep_the_files_and_are_never_a_clean_diff() { let mut server = mockito::Server::new_async().await; From 6ac13e4f5a76d309f2b984016eb41dc99ff75797 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:35:01 -0800 Subject: [PATCH 2/2] fix: create teams before repos so a bypass may name a new team; never export a config that wouldn't load sync creates the config's teams first and checks every bypass list before its first write. sync-from-org drops a bypass list from a ruleset that requires no checks, and refuses to replace the file with a config the loader rejects. --- README.md | 4 +- src/config.rs | 9 +++++ src/github.rs | 107 ++++++++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 110 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 81f8ee7..efc44f4 100644 --- a/README.md +++ b/README.md @@ -258,10 +258,10 @@ repos: - `allow_auto_merge` is written after the repo's `Require CI` ruleset, so if the ruleset write fails, auto-merge isn't left on without the checks it waits for. - A name listed twice is refused when the config is loaded. A `Require CI` ruleset that requires one check twice (from different apps) is refused like one with another rule: a config can't say which pin to keep. - gh-config owns every rule in `Require CI`: if it holds any other rule, `sync` stops with an error naming the repo and the rule instead of dropping it. Keep other rules in other rulesets. -- `required_checks_bypass` is the ruleset's whole bypass list: `sync` makes it exactly these teams (by slug), so leaving it out removes every bypass, including the org's admins, apps and roles a ruleset can name but a config can't. `mode` is `pull_request` (merging a PR may skip the checks; a direct push may not) or `always`. A team that isn't in the config's `teams` (when it lists any), a team named twice, an unknown mode, or a bypass list without `required_checks` is refused when the config is loaded; a team the org doesn't have is refused before the repo's ruleset is written. +- `required_checks_bypass` is the ruleset's whole bypass list: `sync` makes it exactly these teams (by slug), so leaving it out removes every bypass, including the org's admins, apps and roles a ruleset can name but a config can't. `mode` is `pull_request` (merging a PR may skip the checks; a direct push may not) or `always`. A team that isn't in the config's `teams` (when it lists any), a team named twice, an unknown mode, or a bypass list without `required_checks` is refused when the config is loaded; `sync` creates the config's `teams` before it touches any repo, so a bypass list may name a team the same config adds. A team that neither the org nor the config's `teams` has is refused before `sync` writes anything. - `sync --dry-run` names the checks an update would stop requiring, who may bypass them after it and who no longer may. - A repo with no `required_checks` is left alone: `sync` doesn't read or delete its rulesets. To stop requiring checks, delete the ruleset on GitHub and the key. -- `sync-from-org` records the checks of each repo's `Require CI` ruleset, in the file's order when the file names the same ones; `diff` compares them as a set. It costs one rulesets request per repo, plus one when `Require CI` exists. A ruleset that can't be read keeps what the file has, and `diff` names the repo and exits 1. It records the bypass list too, reading team ids as slugs (one teams request in all). GitHub shows a ruleset's bypass list only to a token that can administer the repo; when it doesn't, or the list holds anything other than the org's teams, the file's list is kept and `diff` names the repo and exits 1. Properties other than the checks and the bypass list aren't recorded, so `diff` shows no change when only those differ; `sync` still corrects them. +- `sync-from-org` records the checks of each repo's `Require CI` ruleset, in the file's order when the file names the same ones; `diff` compares them as a set. It costs one rulesets request per repo, plus one when `Require CI` exists. A ruleset that can't be read keeps what the file has, and `diff` names the repo and exits 1. It records the bypass list too, reading team ids as slugs (one teams request in all). GitHub shows a ruleset's bypass list only to a token that can administer the repo; when it doesn't, or the list holds anything other than the org's teams, the file's list is kept and `diff` names the repo and exits 1. A ruleset that requires no checks is recorded without them and without a bypass list (a config can't hold a bypass list alone), and `sync-from-org` never writes a config that wouldn't load: it stops and leaves the file as it is. Properties other than the checks and the bypass list aren't recorded, so `diff` shows no change when only those differ; `sync` still corrects them. ### Webhooks diff --git a/src/config.rs b/src/config.rs index 001dd3b..073b148 100644 --- a/src/config.rs +++ b/src/config.rs @@ -210,6 +210,15 @@ impl Config { } } + Self::from_value(main_config, main_path) + } + + /// Reads a config from YAML text; `main_path` names it in errors. Checked like a config file. + pub fn from_yaml_str(text: &str, main_path: &str) -> crate::error::AppResult { + Self::from_value(serde_yaml::from_str(text).map_err(crate::error::AppError::Serialization)?, main_path) + } + + fn from_value(main_config: Value, main_path: &str) -> crate::error::AppResult { // Unknown or misplaced keys are refused, naming the file, where the key is and the keys allowed there. let config: Config = serde_path_to_error::deserialize(main_config) .map_err(|e| crate::error::AppError::Config(format!("{main_path}: {}: {}", e.path(), e.inner())))?; diff --git a/src/github.rs b/src/github.rs index a8db821..64b6042 100644 --- a/src/github.rs +++ b/src/github.rs @@ -91,7 +91,7 @@ fn bypass_actors(org: &str, repo: &Repo, teams: &TeamIds) -> AppResult { @@ -1344,7 +1351,22 @@ impl GitHubClient { // An archived repo is read-only: unarchive before its other changes, archive after all of them, // and leave the settings and webhook of a repo that stays archived alone. let mut to_archive = Vec::new(); - let teams = if config.repos.iter().any(|r| !r.required_checks.is_empty()) { self.team_ids().await? } else { Vec::new() }; + // Teams come before repos, so a repo's bypass list may name a team this config adds. Every bypass list is + // checked before the first write; a team still to be created stands in with id 0 until it exists. + let gated = config.repos.iter().any(|r| !r.required_checks.is_empty()); + let mut teams = if gated { self.team_ids().await? } else { Vec::new() }; + let adds: Vec<(String, u64)> = config.teams.iter().filter(|t| !teams.iter().any(|(slug, _)| *slug == t.name)).map(|t| (t.name.clone(), 0)).collect(); + teams.extend(adds.iter().cloned()); + for repo in &config.repos { + bypass_actors(&self.org, repo, &teams)?; + } + for team in &config.teams { + info!("Processing team: {}", team.name); + self.create_team(team, dry_run).await?; + } + if gated && !adds.is_empty() && !dry_run { + teams = self.team_ids().await?; + } for repo in &config.repos { // --- Add logging just before the failing call --- info!("Processing repo: {}/{}", self.org, repo.name); @@ -1402,12 +1424,6 @@ impl GitHubClient { self.update_repo_settings(repo, ¤t, |k| k == ALLOW_AUTO_MERGE, dry_run).await?; } - // Teams - for team in &config.teams { - info!("Processing team: {}", team.name); // Add similar logging for other resources - self.create_team(team, dry_run).await?; - } - // Users for user in &config.users { info!("Processing user: {}", user.login); // Add similar logging @@ -2541,6 +2557,81 @@ assignments: assert!(writes.lock().expect("lock").is_empty(), "wrote a ruleset for an unknown team"); } + /// Org `o` with repo `r` and no rulesets, where team `release` exists only once `POST /orgs/o/teams` was sent. + /// Records every write. + async fn mock_org_creating_release(server: &mut mockito::ServerGuard, writes: &std::sync::Arc>>) -> Vec { + let created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let is_created = created.clone(); + let repo = json!({"name": "r", "private": false, "visibility": "public", "archived": false, + "allow_merge_commit": false, "allow_squash_merge": true, "allow_rebase_merge": true}); + let teams = server.mock("GET", "/orgs/o/teams?per_page=100").with_body_from_request(move |_| { + let list = if is_created.load(std::sync::atomic::Ordering::SeqCst) { r#"[{"slug": "release", "name": "release", "id": 31}]"# } else { "[]" }; + list.as_bytes().to_vec() + }); + let create = { + let writes = writes.clone(); + server.mock("POST", "/orgs/o/teams").with_body_from_request(move |req| { + created.store(true, std::sync::atomic::Ordering::SeqCst); + writes.lock().expect("lock").push(format!("POST /orgs/o/teams {}", req.utf8_lossy_body().expect("body"))); + b"{}".to_vec() + }) + }; + vec![ + teams.create_async().await, + create.create_async().await, + server.mock("GET", "/orgs/o/teams/release").with_status(404).create_async().await, + server.mock("GET", "/repos/o/r").with_body(repo.to_string()).create_async().await, + server.mock("GET", "/repos/o/r/rulesets?includes_parents=false&per_page=100").with_body("[]").create_async().await, + record(server, writes, "POST", "/repos/o/r/rulesets").await, + ] + } + + #[tokio::test] + async fn a_bypass_team_the_same_config_adds_is_created_first_and_then_used() { + let mut server = mockito::Server::new_async().await; + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let _mocks = mock_org_creating_release(&mut server, &writes).await; + let file = write_file("org: o\nteams:\n- name: release\n members: []\nrepos:\n- name: r\n required_checks: [A]\n required_checks_bypass: [{team: release, mode: pull_request}]\n"); + let path = file.path().to_str().expect("utf-8 path"); + client(&server).sync(path, true).await.expect("dry run"); + assert!(writes.lock().expect("lock").is_empty(), "a dry run wrote to GitHub"); + client(&server).sync(path, false).await.expect("sync"); + let writes = writes.lock().expect("lock"); + let [team, ruleset] = writes.as_slice() else { panic!("{writes:?}") }; + assert!(team.starts_with("POST /orgs/o/teams "), "{writes:?}"); + let sent: serde_json::Value = serde_json::from_str(ruleset.trim_start_matches("POST /repos/o/r/rulesets ")).expect("json body"); + assert_eq!(sent["bypass_actors"], json!([{"actor_id": 31, "actor_type": "Team", "bypass_mode": "pull_request"}])); + } + + #[tokio::test] + async fn a_bypass_team_nobody_creates_is_refused_before_any_write() { + let mut server = mockito::Server::new_async().await; + let _mocks = mock_org_with_teams(&mut server, &[("core", 9)], &[("a", json!({})), ("r", json!({}))], |_| json!([]), |_| Some(vec![])).await; + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let _patch = record(&mut server, &writes, "PATCH", "/repos/o/a").await; + let _post = record(&mut server, &writes, "POST", "/repos/o/a/rulesets").await; + // `a` comes first and is fine; `r` names a team neither the org nor the config has. + let file = write_file("org: o\nrepos:\n- name: a\n settings: {allow_merge_commit: true}\n required_checks: [A]\n- name: r\n required_checks: [A]\n required_checks_bypass: [{team: ghosts, mode: always}]\n"); + let err = client(&server).sync(file.path().to_str().expect("utf-8 path"), false).await.expect_err("accepted"); + assert!(err.to_string().contains("team `ghosts`") && err.to_string().contains("Repo r"), "{err}"); + assert!(writes.lock().expect("lock").is_empty(), "wrote before refusing: {:?}", writes.lock().expect("lock")); + } + + #[tokio::test] + async fn a_ruleset_requiring_no_checks_exports_a_config_that_loads() { + let mut server = mockito::Server::new_async().await; + // Someone removed the checks rule but the bypass list stayed: a config can't hold a bypass without checks. + let mut ruleset = require_a_with(5, Some(json!([{"actor_id": 9, "actor_type": "Team", "bypass_mode": "pull_request"}]))); + ruleset["rules"] = json!([]); + let _mocks = mock_org_with_teams(&mut server, &[("core", 9)], &[("r", json!({}))], |_| json!([]), |_| Some(vec![ruleset.clone()])).await; + let file = write_file("org: o\nrepos:\n- name: r\n required_checks: [A]\n required_checks_bypass: [{team: core, mode: pull_request}]\n"); + let path = file.path().to_str().expect("utf-8 path"); + client(&server).generate_config_and_write(path, false).await.expect("export"); + let config = Config::from_file_with_defaults(path, None).expect("the exported config doesn't load"); + let repo = config.repos.iter().find(|r| r.name == "r").expect("repo r"); + assert!(repo.required_checks.is_empty() && repo.required_checks_bypass.is_empty(), "{repo:?}"); + } + #[tokio::test] async fn required_checks_that_cant_be_read_keep_the_files_and_are_never_a_clean_diff() { let mut server = mockito::Server::new_async().await;