1use serde_json::Value;
11
12use crate::detect::Forge;
13use crate::error::RkError;
14use crate::setup::app_jwt::{self, AppApi};
15use crate::setup::context::Ctx;
16use crate::setup::process::{Exec, Outcome};
17use crate::setup::workflow_jobs;
18
19pub type Runner<'a> = dyn FnMut(&Exec) -> Result<Outcome, RkError> + 'a;
22
23const GITLAB_PRIVATE_REPORTING_LIMITATION: &str = "GitLab has no project-level private reporting switch; the reporter must enable confidentiality; this proves project feature access, not successful submission by every external reporter";
37
38#[derive(Debug)]
40pub enum StepState {
41 Satisfied {
44 detail: String,
46 limitation: Option<String>,
48 },
49 Unsatisfied {
51 detail: String,
53 },
54 Inapplicable {
57 detail: String,
59 },
60 Unknown {
62 detail: String,
64 },
65}
66
67impl StepState {
68 #[must_use]
70 pub const fn satisfied(&self) -> bool {
71 matches!(self, Self::Satisfied { .. })
72 }
73
74 fn ok(detail: impl Into<String>) -> Self {
75 Self::Satisfied {
76 detail: detail.into(),
77 limitation: None,
78 }
79 }
80
81 fn ok_with_limitation(detail: impl Into<String>, limitation: impl Into<String>) -> Self {
82 Self::Satisfied {
83 detail: detail.into(),
84 limitation: Some(limitation.into()),
85 }
86 }
87
88 fn not(detail: impl Into<String>) -> Self {
89 Self::Unsatisfied {
90 detail: detail.into(),
91 }
92 }
93
94 fn inapplicable(detail: impl Into<String>) -> Self {
95 Self::Inapplicable {
96 detail: detail.into(),
97 }
98 }
99
100 fn unknown(detail: impl Into<String>) -> Self {
101 Self::Unknown {
102 detail: detail.into(),
103 }
104 }
105}
106
107enum Api {
109 Ok(Value),
111 Missing,
113 Failed(String),
115}
116
117pub fn observe(ctx: &Ctx, step: &str, run: &mut Runner) -> Result<StepState, RkError> {
124 if step == "package-check" {
125 return package_check(ctx, run);
126 }
127 if step == "branch-reminder" {
128 return Ok(branch_reminder_state(ctx));
129 }
130 if step == "forge-version" {
131 return forge_version(ctx, run);
132 }
133 match ctx.forge {
134 Some(Forge::Github) => github(ctx, step, run),
135 Some(Forge::Gitlab) => gitlab(ctx, step, run),
136 None => Ok(StepState::inapplicable(
140 "the profile names no forge this release drives",
141 )),
142 }
143}
144
145const POLICY_DESTINATION: &str = "SECURITY.md";
149
150const PYTHON_LIMITATION: &str = "sdist and wheel policy inclusion is unproved: PEP 517 leaves the file set to the build backend and the two outputs can differ; inspect both before publishing";
155
156const BASH_LIMITATION: &str = "the make dist tarball is not inspected: git archive honours export-ignore, so SECURITY.md inclusion is unproved; inspect the generated tarball before publishing";
159
160fn package_check(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
169 let (program, args): (&str, &[&str]) = match ctx.tech {
170 Some("rust") => ("cargo", &["publish", "--dry-run", "--allow-dirty"]),
171 Some("python") => ("python3", &["-m", "build"]),
172 Some("bash") => {
173 return Ok(StepState::ok_with_limitation(
174 "no registry for this technology; there is nothing to package",
175 BASH_LIMITATION,
176 ));
177 }
178 Some(other) => {
179 return Ok(StepState::unknown(format!(
180 "no packaging check is defined for {other}"
181 )));
182 }
183 None => {
184 return Ok(StepState::unknown(
185 "no version file names a technology; see rk binding --list",
186 ));
187 }
188 };
189 let outcome = run(&cargo_exec(ctx, program, args))?;
190 if !outcome.success() {
191 return Ok(StepState::not(format!(
192 "the packaging check failed: {}",
193 last_line(&outcome.stderr)
194 )));
195 }
196 let built = "the package builds and passes the registry's dry run";
197 Ok(match ctx.tech {
198 Some("rust") => policy_in_the_crate(ctx, run, built)?,
199 _ => StepState::ok_with_limitation(built, PYTHON_LIMITATION),
200 })
201}
202
203fn cargo_exec(ctx: &Ctx, program: &str, args: &[&str]) -> Exec {
205 Exec {
206 program: program.into(),
207 args: args.iter().map(Into::into).collect(),
208 env: ctx.child_env("package-check"),
209 cwd: ctx.target.as_std_path().to_path_buf(),
210 stdin: None,
211 }
212}
213
214fn policy_in_the_crate(ctx: &Ctx, run: &mut Runner, built: &str) -> Result<StepState, RkError> {
225 let metadata = run(&cargo_exec(
226 ctx,
227 "cargo",
228 &["metadata", "--no-deps", "--format-version", "1"],
229 ))?;
230 if !metadata.success() {
231 return Ok(StepState::unknown(format!(
232 "{built}, and the policy check could not run: cargo metadata failed: {}",
233 last_line(&metadata.stderr)
234 )));
235 }
236 let root_manifest = ctx.target.as_std_path().join("Cargo.toml");
237 let selected = sole_root_package(&metadata.stdout, &root_manifest);
238 let Some(manifest) = selected else {
239 return Ok(StepState::ok_with_limitation(
240 built,
241 format!(
242 "{POLICY_DESTINATION} inclusion is unproved: the package check lists files only for a single default package rooted at the target, and this workspace selects a different shape; inspect the published archive before releasing"
243 ),
244 ));
245 };
246 let listing = run(&cargo_exec(
247 ctx,
248 "cargo",
249 &[
250 "package",
251 "--list",
252 "--allow-dirty",
253 "--manifest-path",
254 &manifest,
255 ],
256 ))?;
257 if !listing.success() {
258 return Ok(StepState::unknown(format!(
259 "{built}, and the policy check could not run: cargo package --list failed: {}",
260 last_line(&listing.stderr)
261 )));
262 }
263 let carried = String::from_utf8_lossy(&listing.stdout)
266 .lines()
267 .any(|line| line.trim() == POLICY_DESTINATION);
268 Ok(if carried {
269 StepState::ok(format!(
270 "{built}, and the published package carries {POLICY_DESTINATION}"
271 ))
272 } else {
273 StepState::not(format!(
274 "{built}, but the published package omits {POLICY_DESTINATION}: add /{POLICY_DESTINATION} to [package].include, remove the [package].exclude entry matching it, or stop ignoring the file"
275 ))
276 })
277}
278
279fn sole_root_package(metadata: &[u8], root_manifest: &std::path::Path) -> Option<String> {
282 let document: Value = serde_json::from_slice(metadata).ok()?;
283 let defaults: Vec<&str> = document
284 .get("workspace_default_members")?
285 .as_array()?
286 .iter()
287 .filter_map(Value::as_str)
288 .collect();
289 let [only] = defaults.as_slice() else {
290 return None;
291 };
292 let manifest = document
293 .get("packages")?
294 .as_array()?
295 .iter()
296 .find(|package| package.get("id").and_then(Value::as_str) == Some(*only))?
297 .get("manifest_path")?
298 .as_str()?;
299 let same =
302 std::fs::canonicalize(manifest).ok()? == std::fs::canonicalize(root_manifest).ok()?;
303 same.then(|| manifest.to_owned())
304}
305
306fn branch_reminder_state(ctx: &Ctx) -> StepState {
309 use crate::setup::branch_reminder::{HookState, observe_hook};
310 match observe_hook(&ctx.target) {
311 HookState::Installed => {
312 StepState::ok("the post-merge hook carries the release-kit reminder")
313 }
314 HookState::Absent => StepState::not("no post-merge hook is installed"),
315 HookState::Foreign => {
316 StepState::not("a post-merge hook exists without the release-kit marker")
317 }
318 HookState::Drifted => StepState::not("the reminder hook drifted from this binary's body"),
319 HookState::Unreadable(detail) => StepState::unknown(detail),
320 }
321}
322
323pub const GITLAB_VERSION_FLOOR: (u64, u64) = (18, 2);
330
331const GITLAB_EDITIONS: [&str; 2] = ["ee", "ce"];
334
335fn version_refusal(found: &str, prerelease: Option<&str>) -> String {
338 let (major, minor) = GITLAB_VERSION_FLOOR;
339 let mut said = vec![format!(
340 "this GitLab instance reports {found}; the convention needs {major}.{minor} or newer"
341 )];
342 if let Some(suffix) = prerelease {
343 said.push(format!(
344 "the -{suffix} suffix is a pre-release, and nothing proves the feature shipped in it, so this step fails closed"
345 ));
346 }
347 said.push(format!(
348 "the merge-request pipeline triggers a child pipeline with `strategy: mirror`, which GitLab added in {major}.{minor}"
349 ));
350 said.push(
351 "below it the child's status never reaches the parent pipeline, so a failing project job merges".to_owned(),
352 );
353 said.push(format!(
354 "upgrade the instance to {major}.{minor} or newer, or host the project on gitlab.com"
355 ));
356 said.join("; ")
357}
358
359fn forge_version(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
365 if ctx.forge == Some(Forge::Github) {
366 return Ok(StepState::ok(
367 "github.com is a rolling service and declares no version floor",
368 ));
369 }
370 let body = match api_get(ctx, run, "version")? {
371 Api::Ok(body) => body,
372 Api::Missing => {
373 return Ok(StepState::unknown(
374 "this instance answers no GET /version; the floor cannot be read. Check that glab is authenticated against it: glab auth login",
375 ));
376 }
377 Api::Failed(err) => {
378 return Ok(StepState::unknown(format!(
379 "the version could not be read: {err}. Check that glab is authenticated against this instance: glab auth login"
380 )));
381 }
382 };
383 let Some(found) = body["version"].as_str() else {
384 return Ok(StepState::unknown(
385 "the forge answer carries no version field; the floor cannot be read. Check that glab is authenticated against this instance: glab auth login",
386 ));
387 };
388 let (number, suffix) = found
389 .split_once('-')
390 .map_or((found, None), |(n, s)| (n, Some(s)));
391 let mut parts = number.split('.');
392 let parsed = parts
393 .next()
394 .and_then(|major| major.parse::<u64>().ok())
395 .zip(parts.next().and_then(|minor| minor.parse::<u64>().ok()));
396 let Some(pair) = parsed else {
397 return Ok(StepState::unknown(format!(
398 "the forge reports the version as '{found}', which names no major and minor pair; the floor cannot be read"
399 )));
400 };
401 if let Some(suffix) = suffix.filter(|s| !GITLAB_EDITIONS.contains(s)) {
402 return Ok(StepState::not(version_refusal(found, Some(suffix))));
403 }
404 if pair < GITLAB_VERSION_FLOOR {
405 return Ok(StepState::not(version_refusal(found, None)));
406 }
407 let (major, minor) = GITLAB_VERSION_FLOOR;
408 Ok(StepState::ok(format!(
409 "this instance reports {found}, at or above the {major}.{minor} floor"
410 )))
411}
412
413pub fn single_trunk_guard(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
423 let trunk = ctx.trunk();
424 for candidate in ctx.retired_branches() {
425 let candidate = candidate.as_str();
426 if candidate == trunk {
427 continue;
428 }
429 let state = match ctx.forge {
430 Some(Forge::Github) => github_candidate_guard(ctx, run, candidate)?,
431 Some(Forge::Gitlab) => gitlab_candidate_guard(ctx, run, candidate)?,
432 None => StepState::unknown("the profile names no forge this release drives"),
435 };
436 if !state.satisfied() {
437 return Ok(state);
438 }
439 }
440 Ok(StepState::ok(
441 "every candidate branch is absent, or an ancestor of the trunk",
442 ))
443}
444
445fn github_candidate_guard(
447 ctx: &Ctx,
448 run: &mut Runner,
449 candidate: &str,
450) -> Result<StepState, RkError> {
451 let trunk = ctx.trunk();
452 match api_get(
453 ctx,
454 run,
455 &format!("repos/{}/git/ref/heads/{candidate}", ctx.repo),
456 )? {
457 Api::Missing => return Ok(StepState::ok(format!("{candidate} is already gone"))),
458 Api::Failed(err) => return Ok(StepState::unknown(err)),
459 Api::Ok(_) => {}
460 }
461 match api_get(
462 ctx,
463 run,
464 &format!("repos/{}/compare/{candidate}...{trunk}", ctx.repo),
465 )? {
466 Api::Ok(body) => {
467 let status = body["status"].as_str().unwrap_or("");
468 Ok(if matches!(status, "ahead" | "identical") {
469 StepState::ok(format!("{candidate} is an ancestor of {trunk}"))
470 } else {
471 StepState::not(format!(
472 "{candidate} is not an ancestor of {trunk} ({status}); deleting it would lose work"
473 ))
474 })
475 }
476 Api::Missing => Ok(StepState::unknown("the comparison is not readable")),
477 Api::Failed(err) => Ok(StepState::unknown(err)),
478 }
479}
480
481fn gitlab_candidate_guard(
483 ctx: &Ctx,
484 run: &mut Runner,
485 candidate: &str,
486) -> Result<StepState, RkError> {
487 let trunk = ctx.trunk();
488 let project = ctx.repo.replace('/', "%2F");
489 match api_get(
490 ctx,
491 run,
492 &format!("projects/{project}/repository/branches/{candidate}"),
493 )? {
494 Api::Missing => return Ok(StepState::ok(format!("{candidate} is already gone"))),
495 Api::Failed(err) => return Ok(StepState::unknown(err)),
496 Api::Ok(_) => {}
497 }
498 match api_get(
499 ctx,
500 run,
501 &format!("projects/{project}/repository/compare?from={trunk}&to={candidate}"),
502 )? {
503 Api::Ok(body) => {
504 let ahead = body["commits"]
505 .as_array()
506 .is_some_and(|list| !list.is_empty());
507 Ok(if ahead {
508 StepState::not(format!(
509 "{candidate} carries commits {trunk} does not; deleting it would lose work"
510 ))
511 } else {
512 StepState::ok(format!("{candidate} is an ancestor of {trunk}"))
513 })
514 }
515 Api::Missing => Ok(StepState::unknown("the comparison is not readable")),
516 Api::Failed(err) => Ok(StepState::unknown(err)),
517 }
518}
519
520fn api_get(ctx: &Ctx, run: &mut Runner, path: &str) -> Result<Api, RkError> {
522 let exec = Exec {
523 program: ctx.cli.clone().into_os_string(),
524 args: vec!["api".into(), path.into()],
525 env: ctx.child_env("observe"),
526 cwd: ctx.target.as_std_path().to_path_buf(),
527 stdin: None,
528 };
529 let outcome = run(&exec)?;
530 if outcome.success() {
531 return Ok(
532 serde_json::from_slice::<Value>(&outcome.stdout).map_or_else(
533 |_| Api::Failed("the forge answer did not parse as JSON".into()),
534 Api::Ok,
535 ),
536 );
537 }
538 let stderr = String::from_utf8_lossy(&outcome.stderr).into_owned();
539 if stderr.contains("404") {
540 Ok(Api::Missing)
541 } else {
542 Ok(Api::Failed(last_line(&outcome.stderr)))
543 }
544}
545
546fn last_line(bytes: &[u8]) -> String {
548 String::from_utf8_lossy(bytes)
549 .lines()
550 .rev()
551 .find(|line| !line.trim().is_empty())
552 .unwrap_or("no output")
553 .to_owned()
554}
555
556#[allow(
557 clippy::too_many_lines,
558 reason = "one arm per setup step, so the match is what makes an unobserved step a compile error"
559)]
560fn github(ctx: &Ctx, step: &str, run: &mut Runner) -> Result<StepState, RkError> {
561 let trunk = ctx.trunk();
562 let repo = &ctx.repo;
563 match step {
564 "private-vulnerability-reporting" => {
565 let visibility_path = format!("repos/{repo}");
566 match api_get(ctx, run, &visibility_path)? {
567 Api::Ok(body) => match body["private"].as_bool() {
568 Some(true) => {
569 return Ok(StepState::inapplicable(
570 "private vulnerability reporting is available for public repositories",
571 ));
572 }
573 Some(false) => {}
574 None => {
575 return Ok(StepState::unknown(format!(
576 "{visibility_path}: repository visibility is unreadable"
577 )));
578 }
579 },
580 Api::Missing => {
581 return Ok(StepState::unknown(format!(
582 "{visibility_path}: repository visibility is unreadable (404)"
583 )));
584 }
585 Api::Failed(err) => {
586 return Ok(StepState::unknown(format!("{visibility_path}: {err}")));
587 }
588 }
589 let path = format!("repos/{repo}/private-vulnerability-reporting");
590 Ok(match api_get(ctx, run, &path)? {
591 Api::Ok(body) => match body["enabled"].as_bool() {
592 Some(true) => StepState::ok("private vulnerability reporting is enabled"),
593 Some(false) => StepState::not("private vulnerability reporting is disabled"),
594 None => StepState::unknown(format!("{path}: enabled is unreadable")),
595 },
596 Api::Missing => {
597 StepState::unknown(format!("{path}: reporting state is unreadable (404)"))
598 }
599 Api::Failed(err) => StepState::unknown(format!("{path}: {err}")),
600 })
601 }
602
603 "default-branch" => Ok(match api_get(ctx, run, &format!("repos/{repo}"))? {
604 Api::Ok(body) => {
605 let found = body["default_branch"].as_str().unwrap_or("");
606 if found == trunk {
607 StepState::ok(format!("{trunk} is the default branch"))
608 } else {
609 StepState::not(format!("the default branch is {found}"))
610 }
611 }
612 Api::Missing => StepState::not(format!("the forge does not know {repo}")),
613 Api::Failed(err) => StepState::unknown(err),
614 }),
615 "single-trunk" => {
616 for candidate in ctx.retired_branches() {
617 let candidate = candidate.as_str();
618 if candidate == trunk {
619 continue;
620 }
621 match api_get(ctx, run, &format!("repos/{repo}/git/ref/heads/{candidate}"))? {
622 Api::Missing => {}
623 Api::Ok(_) => {
624 return Ok(StepState::not(format!("a {candidate} branch still exists")));
625 }
626 Api::Failed(err) => return Ok(StepState::unknown(err)),
627 }
628 }
629 Ok(StepState::ok(
630 "no long-lived branch besides the trunk remains",
631 ))
632 }
633 "merge-cleanup" => Ok(match api_get(ctx, run, &format!("repos/{repo}"))? {
634 Api::Ok(body) => {
635 if body["delete_branch_on_merge"].as_bool().unwrap_or(false) {
636 StepState::ok("a merged branch is deleted by the forge")
637 } else {
638 StepState::not("a merged branch outlives its merge")
639 }
640 }
641 Api::Missing => StepState::not(format!("the forge does not know {repo}")),
642 Api::Failed(err) => StepState::unknown(err),
643 }),
644 "auto-merge" => Ok(match api_get(ctx, run, &format!("repos/{repo}"))? {
645 Api::Ok(body) => {
646 if body["allow_auto_merge"].as_bool().unwrap_or(false) {
647 StepState::ok("a request may merge itself once its checks pass")
648 } else {
649 StepState::not("a request cannot merge itself; the auto-merge switch is off")
650 }
651 }
652 Api::Missing => StepState::not(format!("the forge does not know {repo}")),
653 Api::Failed(err) => StepState::unknown(err),
654 }),
655 "ci-permissions" => Ok(
656 match api_get(
657 ctx,
658 run,
659 &format!("repos/{repo}/actions/permissions/workflow"),
660 )? {
661 Api::Ok(body) => {
662 let write = body["default_workflow_permissions"] == "write";
663 let approve = body["can_approve_pull_request_reviews"] == true;
664 if write && approve {
665 StepState::ok("CI may write and open requests")
666 } else {
667 StepState::not(format!(
668 "workflow permissions are {} with request approval {}",
669 body["default_workflow_permissions"],
670 body["can_approve_pull_request_reviews"]
671 ))
672 }
673 }
674 Api::Missing => StepState::not("no workflow permissions are readable"),
675 Api::Failed(err) => StepState::unknown(err),
676 },
677 ),
678 "bot-secrets" => Ok(
679 match api_get(ctx, run, &format!("repos/{repo}/actions/secrets"))? {
680 Api::Ok(body) => {
681 let names: Vec<&str> = body["secrets"]
682 .as_array()
683 .map(|list| {
684 list.iter()
685 .filter_map(|secret| secret["name"].as_str())
686 .collect()
687 })
688 .unwrap_or_default();
689 let wanted = ["RELEASE_BOT_APP_ID", "RELEASE_BOT_APP_PRIVATE_KEY"];
690 if wanted.iter().all(|name| names.contains(name)) {
691 StepState::ok("both bot secrets are stored")
692 } else if names.is_empty() {
693 StepState::not("no bot secrets are stored")
694 } else {
695 StepState::not(format!("stored secrets: {}", names.join(", ")))
696 }
697 }
698 Api::Missing => StepState::not("no secrets are readable"),
699 Api::Failed(err) => StepState::unknown(err),
700 },
701 ),
702 "protect-trunk" => github_trunk_ruleset(ctx, run),
703 "protect-tags" => github_ruleset(
704 ctx,
705 run,
706 ctx.tag_ruleset(),
707 "tag",
708 "refs/tags/v*",
709 &["deletion", "update"],
710 ),
711 "protect-release-lines" => {
712 match github_ruleset_body(ctx, run, ctx.lines_ruleset())? {
713 RulesetLookup::Absent => {
714 return Ok(StepState::inapplicable(
715 "release/* is unprotected; optional — applied only where older lines exist",
716 ));
717 }
718 RulesetLookup::Unreadable(err) => return Ok(StepState::unknown(err)),
719 RulesetLookup::Found(_) => {}
720 }
721 github_ruleset(
722 ctx,
723 run,
724 ctx.lines_ruleset(),
725 "branch",
726 "refs/heads/release/*",
727 &["deletion", "non_fast_forward"],
728 )
729 }
730 "protections-check" => {
731 let mut failures = Vec::new();
735 let mut unknowns = Vec::new();
736 let mut limitations: Vec<String> = Vec::new();
738 for owned in ["protect-trunk", "protect-tags", "protect-release-lines"] {
739 match github(ctx, owned, run)? {
740 StepState::Satisfied {
741 limitation: found, ..
742 } => limitations.extend(found),
743 StepState::Inapplicable { .. } => {}
744 StepState::Unsatisfied { detail } => {
745 failures.push(format!("{owned}: {detail}"));
746 }
747 StepState::Unknown { detail } => {
748 unknowns.push(format!("{owned}: {detail}"));
749 }
750 }
751 }
752 match api_get(ctx, run, &format!("repos/{repo}/rulesets"))? {
753 Api::Ok(body) => {
754 let owned = [
755 ctx.trunk_ruleset().to_owned(),
756 ctx.tag_ruleset().to_owned(),
757 ctx.lines_ruleset().to_owned(),
758 ];
759 for ruleset in body.as_array().into_iter().flatten() {
760 let name = ruleset["name"].as_str().unwrap_or("");
761 if !owned.iter().any(|expected| expected == name) {
762 failures.push(format!("a ruleset no step owns: {name}"));
763 }
764 }
765 }
766 Api::Missing | Api::Failed(_) => {
767 unknowns.push("the ruleset inventory is not readable".to_owned());
768 }
769 }
770 Ok(if !failures.is_empty() {
771 StepState::not(failures.join("; "))
772 } else if !unknowns.is_empty() {
773 StepState::unknown(unknowns.join("; "))
774 } else {
775 StepState::Satisfied {
776 detail: "exactly the owned protections, with those rules".into(),
777 limitation: if limitations.is_empty() {
778 None
779 } else {
780 Some(limitations.join("; "))
781 },
782 }
783 })
784 }
785 _ => Ok(StepState::unknown(format!("no observation for {step}"))),
786 }
787}
788
789#[must_use]
797pub fn github_install_bot(ctx: &Ctx, jwt: &str) -> StepState {
798 match app_jwt::api_get(ctx, jwt, &format!("repos/{}/installation", ctx.repo)) {
799 AppApi::Ok(body) => {
800 let id = body["id"].as_i64().unwrap_or_default();
801 StepState::ok(format!("installation {id} covers {}", ctx.repo))
802 }
803 AppApi::Missing => StepState::not(format!("the App is not installed on {}", ctx.repo)),
804 AppApi::Refused(detail) | AppApi::Failed(detail) => StepState::unknown(detail),
805 }
806}
807
808fn github_ruleset(
813 ctx: &Ctx,
814 run: &mut Runner,
815 name: &str,
816 target: &str,
817 include: &str,
818 rules: &[&str],
819) -> Result<StepState, RkError> {
820 let detail = match github_ruleset_body(ctx, run, name)? {
821 RulesetLookup::Found(detail) => detail,
822 RulesetLookup::Absent => {
823 return Ok(StepState::not(format!("no ruleset named {name}")));
824 }
825 RulesetLookup::Unreadable(err) => return Ok(StepState::unknown(err)),
826 };
827 if detail["enforcement"] != "active" {
828 return Ok(StepState::not(format!("{name} is not active")));
829 }
830 if detail["target"] != target {
833 return Ok(StepState::not(format!(
834 "{name} does not target {target} refs"
835 )));
836 }
837 if detail["conditions"]["ref_name"]["include"] != serde_json::json!([include]) {
838 return Ok(StepState::not(format!(
839 "{name} does not cover {include} alone"
840 )));
841 }
842 if detail["conditions"]["ref_name"]["exclude"] != serde_json::json!([]) {
843 return Ok(StepState::not(format!(
844 "{name} excludes refs from its own coverage"
845 )));
846 }
847 let mut held: Vec<&str> = detail["rules"]
848 .as_array()
849 .map(|list| {
850 list.iter()
851 .filter_map(|rule| rule["type"].as_str())
852 .collect()
853 })
854 .unwrap_or_default();
855 held.sort_unstable();
856 let mut expected: Vec<&str> = rules.to_vec();
857 expected.sort_unstable();
858 if held == expected {
859 Ok(StepState::ok(format!(
860 "{name} is active with exactly its rules"
861 )))
862 } else {
863 Ok(StepState::not(format!(
864 "{name} carries the rules [{}] where the setup owns [{}]",
865 held.join(", "),
866 expected.join(", ")
867 )))
868 }
869}
870
871fn unowned_rule_faults(rules: &[Value], owned: &[String]) -> Vec<String> {
886 rules
887 .iter()
888 .filter_map(|rule| rule["type"].as_str())
889 .filter(|kind| !owned.iter().any(|name| name == kind))
890 .map(|kind| {
891 if kind == "merge_queue" {
892 MERGE_QUEUE_FAULT.to_owned()
893 } else {
894 format!("an unowned rule is present: {kind}")
895 }
896 })
897 .collect()
898}
899
900fn github_trunk_ruleset(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
901 let trunk = ctx.trunk();
902 let name = ctx.trunk_ruleset().to_owned();
903 let detail = match github_ruleset_body(ctx, run, &name)? {
904 RulesetLookup::Found(detail) => detail,
905 RulesetLookup::Absent => {
906 return Ok(StepState::not(format!("no ruleset named {name}")));
907 }
908 RulesetLookup::Unreadable(err) => return Ok(StepState::unknown(err)),
909 };
910 let rules = detail["rules"].as_array().cloned().unwrap_or_default();
911 let has = |kind: &str| rules.iter().any(|rule| rule["type"] == kind);
912 let mut faults = Vec::new();
913 if detail["enforcement"] != "active" {
914 faults.push(format!("{name} is not active"));
915 }
916 if detail["target"] != "branch" {
920 faults.push(format!("{name} does not target branches"));
921 }
922 let expected_ref = serde_json::json!([format!("refs/heads/{trunk}")]);
923 if detail["conditions"]["ref_name"]["include"] != expected_ref {
924 faults.push(format!("{name} does not cover refs/heads/{trunk} alone"));
925 }
926 if detail["conditions"]["ref_name"]["exclude"] != serde_json::json!([]) {
929 faults.push(format!("{name} excludes refs from its own coverage"));
930 }
931 if !detail["bypass_actors"].as_array().is_none_or(Vec::is_empty) {
932 faults.push("a bypass actor is named".to_owned());
933 }
934 for required in &ctx.protection().owned_trunk_rules {
935 if !has(required) {
936 faults.push(format!("the {required} rule is missing"));
937 }
938 }
939 faults.extend(unowned_rule_faults(
940 &rules,
941 &ctx.protection().owned_trunk_rules,
942 ));
943 if let Some(request) = rules.iter().find(|rule| rule["type"] == "pull_request")
944 && request["parameters"]["allowed_merge_methods"]
945 != serde_json::json!(ctx.protection().allowed_merge_methods)
946 {
947 faults.push("the merge method is not exactly a squash merge".to_owned());
948 }
949 if let Some(checks) = rules
950 .iter()
951 .find(|rule| rule["type"] == "required_status_checks")
952 {
953 if checks["parameters"]["strict_required_status_checks_policy"]
954 != ctx.protection().strict_required_status_checks
955 {
956 faults.push(STALE_MERGE_FAULT.to_owned());
957 }
958 let contexts: Vec<&str> = checks["parameters"]["required_status_checks"]
959 .as_array()
960 .map(|list| {
961 list.iter()
962 .filter_map(|check| check["context"].as_str())
963 .collect()
964 })
965 .unwrap_or_default();
966 if contexts.is_empty() {
971 faults.push("no status check is required".to_owned());
972 } else if let Some(expected) = &ctx.required_check {
973 let mut held = contexts.clone();
974 held.sort_unstable();
975 let title_check = ctx.title_check();
976 let mut owned_contexts = [expected.as_str(), title_check];
977 owned_contexts.sort_unstable();
978 if held != owned_contexts {
979 faults.push(format!(
980 "the required checks are [{}] where the setup owns [{}]",
981 contexts.join(", "),
982 owned_contexts.join(", ")
983 ));
984 }
985 } else if !contexts.contains(&ctx.title_check()) {
986 faults.push(format!("the {} check is not required", ctx.title_check()));
987 }
988 }
989 match squash_merge_sources(ctx, run)? {
990 MergeSources::Owned => {}
991 MergeSources::Faults(proven) => faults.extend(proven),
992 MergeSources::Unreadable(err) => {
996 if faults.is_empty() {
997 return Ok(StepState::unknown(err));
998 }
999 }
1000 }
1001 if let Some(shape) = gate_faults(ctx) {
1002 faults.push(shape);
1003 }
1004 if !faults.is_empty() {
1005 return Ok(StepState::not(faults.join("; ")));
1006 }
1007 Ok(StepState::ok(format!(
1008 "{name} holds the release-merge shape"
1009 )))
1010}
1011
1012fn gate_faults(ctx: &Ctx) -> Option<String> {
1022 let check = ctx.required_check.as_deref()?;
1023 workflow_jobs::faults(
1024 &workflow_jobs::read_gate(&ctx.target, check, ctx.trunk()),
1025 check,
1026 ctx.trunk(),
1027 )
1028}
1029
1030enum MergeSources {
1032 Owned,
1034 Faults(Vec<String>),
1036 Unreadable(String),
1038}
1039
1040fn squash_merge_sources(ctx: &Ctx, run: &mut Runner) -> Result<MergeSources, RkError> {
1047 Ok(match api_get(ctx, run, &format!("repos/{}", ctx.repo))? {
1048 Api::Ok(body) => {
1049 let mut faults = Vec::new();
1050 let owned_title = ctx.protection().github.squash_title_source.as_str();
1051 let owned_body = ctx.protection().github.squash_body_source.as_str();
1052 if body["squash_merge_commit_title"] != owned_title {
1053 faults.push(format!(
1054 "the squash title source is {} where the setup owns {owned_title}",
1055 body["squash_merge_commit_title"]
1056 ));
1057 }
1058 if body["squash_merge_commit_message"] != owned_body {
1059 faults.push(format!(
1060 "the squash message source is {} where the setup owns {owned_body}",
1061 body["squash_merge_commit_message"]
1062 ));
1063 }
1064 if faults.is_empty() {
1065 MergeSources::Owned
1066 } else {
1067 MergeSources::Faults(faults)
1068 }
1069 }
1070 Api::Missing => MergeSources::Faults(vec![format!("the forge does not know {}", ctx.repo)]),
1071 Api::Failed(err) => MergeSources::Unreadable(err),
1072 })
1073}
1074
1075enum RulesetLookup {
1078 Found(Value),
1080 Absent,
1083 Unreadable(String),
1085}
1086
1087fn github_ruleset_body(ctx: &Ctx, run: &mut Runner, name: &str) -> Result<RulesetLookup, RkError> {
1089 let list = match api_get(ctx, run, &format!("repos/{}/rulesets", ctx.repo))? {
1093 Api::Ok(body) => body,
1094 Api::Missing => {
1095 return Ok(RulesetLookup::Unreadable(
1096 "the ruleset inventory is not readable".into(),
1097 ));
1098 }
1099 Api::Failed(err) => return Ok(RulesetLookup::Unreadable(err)),
1100 };
1101 let id = list
1102 .as_array()
1103 .into_iter()
1104 .flatten()
1105 .find(|ruleset| ruleset["name"] == name)
1106 .and_then(|ruleset| ruleset["id"].as_i64());
1107 let Some(id) = id else {
1108 return Ok(RulesetLookup::Absent);
1109 };
1110 match api_get(ctx, run, &format!("repos/{}/rulesets/{id}", ctx.repo))? {
1111 Api::Ok(body) => Ok(RulesetLookup::Found(body)),
1112 Api::Missing => Ok(RulesetLookup::Unreadable(format!(
1116 "the {name} detail is not readable"
1117 ))),
1118 Api::Failed(err) => Ok(RulesetLookup::Unreadable(err)),
1119 }
1120}
1121
1122const GITLAB_AUTO_MERGE_LIMITATION: &str = "the forge offers no project-level auto-merge switch: availability follows the pipeline requirement protect-trunk asserts, and turning that requirement off removes auto-merge with nothing here reporting it";
1126
1127const GITLAB_TAG_LIMITATION: &str =
1129 "an Owner or Maintainer can still delete a protected tag through the UI or API";
1130
1131const MERGE_QUEUE_FAULT: &str = "a merge queue is enabled on the trunk; this convention lands no workflow that triggers on merge_group, so the queue waits on a required check that never reports and drops the request when its CI timeout expires. rk setup step protect-trunk --apply rewrites the ruleset without it";
1136
1137const STALE_MERGE_FAULT: &str = "the trunk permits a merge from a branch that does not carry the trunk's tip; an armed release request can therefore ship a version computed against a trunk that moved. rk setup step protect-trunk --apply rewrites the ruleset with the freshness requirement";
1139
1140const GITLAB_TITLE_LIMITATION: &str = "the title gate stops accident, not authority: a merge request runs its own CI configuration, and a title edit starts no new pipeline";
1143
1144#[allow(
1145 clippy::too_many_lines,
1146 reason = "one arm per setup step, so the match is what makes an unobserved step a compile error"
1147)]
1148fn gitlab(ctx: &Ctx, step: &str, run: &mut Runner) -> Result<StepState, RkError> {
1149 let trunk = ctx.trunk();
1150 let project = ctx.repo.replace('/', "%2F");
1151 match step {
1152 "private-vulnerability-reporting" => {
1153 let path = format!("projects/{project}");
1154 Ok(match api_get(ctx, run, &path)? {
1155 Api::Ok(body) => {
1156 let access = body["issues_access_level"].as_str();
1157 if !matches!(access, Some("enabled" | "private" | "disabled")) {
1158 StepState::unknown("issue intake access is unreadable")
1159 } else if body
1160 .get("issues_enabled")
1161 .is_some_and(|flag| !flag.is_boolean())
1162 {
1163 StepState::unknown("legacy issue intake flag is unreadable")
1164 } else if body["issues_enabled"] == false || access == Some("disabled") {
1165 StepState::not("issue intake is disabled; see setup guide step 3g")
1166 } else if access == Some("private") {
1167 StepState::not("issue intake is restricted; see setup guide step 3g")
1168 } else {
1169 StepState::ok_with_limitation(
1170 "issue intake is enabled",
1171 GITLAB_PRIVATE_REPORTING_LIMITATION,
1172 )
1173 }
1174 }
1175 Api::Missing => {
1176 StepState::unknown(format!("{path}: issue intake is unreadable (404)"))
1177 }
1178 Api::Failed(err) => StepState::unknown(format!("{path}: {err}")),
1179 })
1180 }
1181
1182 "default-branch" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1183 Api::Ok(body) => {
1184 let found = body["default_branch"].as_str().unwrap_or("");
1185 if found == trunk {
1186 StepState::ok(format!("{trunk} is the default branch"))
1187 } else {
1188 StepState::not(format!("the default branch is {found}"))
1189 }
1190 }
1191 Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1192 Api::Failed(err) => StepState::unknown(err),
1193 }),
1194 "single-trunk" => {
1195 for candidate in ctx.retired_branches() {
1196 let candidate = candidate.as_str();
1197 if candidate == trunk {
1198 continue;
1199 }
1200 match api_get(
1201 ctx,
1202 run,
1203 &format!("projects/{project}/repository/branches/{candidate}"),
1204 )? {
1205 Api::Missing => {}
1206 Api::Ok(_) => {
1207 return Ok(StepState::not(format!("a {candidate} branch still exists")));
1208 }
1209 Api::Failed(err) => return Ok(StepState::unknown(err)),
1210 }
1211 }
1212 Ok(StepState::ok(
1213 "no long-lived branch besides the trunk remains",
1214 ))
1215 }
1216 "merge-cleanup" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1217 Api::Ok(body) => {
1218 if body["remove_source_branch_after_merge"]
1219 .as_bool()
1220 .unwrap_or(false)
1221 {
1222 StepState::ok("a merged branch is deleted by the forge")
1223 } else {
1224 StepState::not("a merged branch outlives its merge")
1225 }
1226 }
1227 Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1228 Api::Failed(err) => StepState::unknown(err),
1229 }),
1230 "auto-merge" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1231 Api::Ok(body) => {
1232 if body["only_allow_merge_if_pipeline_succeeds"]
1233 .as_bool()
1234 .unwrap_or(false)
1235 {
1236 StepState::ok_with_limitation(
1237 "a request may merge itself once its pipeline passes",
1238 GITLAB_AUTO_MERGE_LIMITATION,
1239 )
1240 } else {
1241 StepState::not(
1242 "the pipeline requirement auto-merge rides on is off; protect-trunk asserts it",
1243 )
1244 }
1245 }
1246 Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1247 Api::Failed(err) => StepState::unknown(err),
1248 }),
1249 "ci-permissions" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1250 Api::Ok(body) => {
1251 if body["jobs_enabled"] == true {
1252 StepState::ok("pipelines are enabled")
1253 } else {
1254 StepState::not("pipelines are disabled")
1255 }
1256 }
1257 Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1258 Api::Failed(err) => StepState::unknown(err),
1259 }),
1260 "install-bot" => {
1261 let mut active = false;
1267 let mut exhausted = false;
1268 for page in 1..=10u32 {
1269 let path = format!(
1270 "projects/{project}/access_tokens?state=active&per_page=100&page={page}"
1271 );
1272 let list = match api_get(ctx, run, &path)? {
1273 Api::Ok(body) => body.as_array().cloned().unwrap_or_default(),
1274 Api::Missing => Vec::new(),
1275 Api::Failed(err) => return Ok(StepState::unknown(err)),
1276 };
1277 active = active
1278 || list.iter().any(|token| {
1279 token["name"] == "release-bot"
1280 && token["revoked"] == false
1281 && token["active"] != false
1282 });
1283 if list.len() < 100 {
1284 exhausted = true;
1285 }
1286 if active || exhausted {
1287 break;
1288 }
1289 }
1290 if !active {
1291 return Ok(if exhausted {
1292 StepState::not("no active release-bot token exists")
1293 } else {
1294 StepState::unknown(
1295 "the token listing did not exhaust within ten pages; nothing was decided",
1296 )
1297 });
1298 }
1299 Ok(
1303 match api_get(
1304 ctx,
1305 run,
1306 &format!("projects/{project}/variables/RELEASE_BOT_TOKEN"),
1307 )? {
1308 Api::Ok(_) => StepState::ok(
1309 "an active release-bot token exists and its variable is stored",
1310 ),
1311 Api::Missing => StepState::not(
1312 "an active release-bot token exists with no stored variable; a rerun revokes and replaces it",
1313 ),
1314 Api::Failed(err) => StepState::unknown(err),
1315 },
1316 )
1317 }
1318 "bot-secrets" => Ok(
1319 match api_get(
1320 ctx,
1321 run,
1322 &format!("projects/{project}/variables/RELEASE_BOT_TOKEN"),
1323 )? {
1324 Api::Ok(_) => StepState::ok("RELEASE_BOT_TOKEN is stored"),
1325 Api::Missing => StepState::not("RELEASE_BOT_TOKEN is not stored"),
1326 Api::Failed(err) => StepState::unknown(err),
1327 },
1328 ),
1329 "protect-trunk" => {
1330 let protection = match api_get(
1331 ctx,
1332 run,
1333 &format!("projects/{project}/protected_branches/{trunk}"),
1334 )? {
1335 Api::Ok(body) => body,
1336 Api::Missing => {
1337 return Ok(StepState::not(format!("{trunk} is not protected")));
1338 }
1339 Api::Failed(err) => return Ok(StepState::unknown(err)),
1340 };
1341 let grants = protection["push_access_levels"]
1345 .as_array()
1346 .cloned()
1347 .unwrap_or_default();
1348 let policy = ctx.protection();
1349 let no_push =
1350 grants.len() == 1 && grants[0]["access_level"] == policy.gitlab.push_access_level;
1351 let merges = protection["merge_access_levels"]
1355 .as_array()
1356 .cloned()
1357 .unwrap_or_default();
1358 let can_merge =
1359 merges.len() == 1 && merges[0]["access_level"] == policy.gitlab.merge_access_level;
1360 let settings = match api_get(ctx, run, &format!("projects/{project}"))? {
1361 Api::Ok(body) => body,
1362 Api::Missing | Api::Failed(_) => Value::Null,
1363 };
1364 let mut faults = Vec::new();
1365 if !no_push {
1366 faults.push(format!(
1367 "{trunk} still takes a direct push: the forge honors the most permissive of {} push grants",
1368 grants.len()
1369 ));
1370 }
1371 if !can_merge {
1372 faults.push(format!(
1373 "{trunk} merge grants are not exactly the one owned maintainer level"
1374 ));
1375 }
1376 if protection["allow_force_push"] != false {
1377 faults.push(format!("{trunk} allows force pushes"));
1378 }
1379 if settings["only_allow_merge_if_pipeline_succeeds"] != true {
1380 faults.push("the pipeline requirement is off".to_owned());
1381 }
1382 if settings["merge_method"] != policy.gitlab.merge_method.as_str() {
1383 faults.push("the merge method is not fast-forward".to_owned());
1384 }
1385 if settings["squash_option"] != policy.gitlab.squash_option.as_str() {
1386 faults.push("merge requests do not always squash".to_owned());
1387 }
1388 if settings["squash_commit_template"] != policy.gitlab.squash_commit_template.as_str() {
1389 faults.push("the squash template is not the merge request's title".to_owned());
1390 }
1391 Ok(if faults.is_empty() {
1392 StepState::ok_with_limitation(
1393 format!("{trunk} holds the release-merge shape"),
1394 GITLAB_TITLE_LIMITATION,
1395 )
1396 } else {
1397 StepState::not(faults.join("; "))
1398 })
1399 }
1400 "protect-tags" => Ok(
1401 match api_get(ctx, run, &format!("projects/{project}/protected_tags/v%2A"))? {
1402 Api::Ok(_) => {
1403 StepState::ok_with_limitation("v* is protected", GITLAB_TAG_LIMITATION)
1404 }
1405 Api::Missing => StepState::not("v* is not protected"),
1406 Api::Failed(err) => StepState::unknown(err),
1407 },
1408 ),
1409 "protect-release-lines" => Ok(
1410 match api_get(
1411 ctx,
1412 run,
1413 &format!("projects/{project}/protected_branches/release%2F%2A"),
1414 )? {
1415 Api::Ok(body) => {
1416 let level_ok = |levels: &Value| {
1417 levels
1418 .as_array()
1419 .is_some_and(|list| list.len() == 1 && list[0]["access_level"] == 40)
1420 };
1421 if body["allow_force_push"] != false {
1422 StepState::not("release/* allows force pushes")
1423 } else if !level_ok(&body["push_access_levels"])
1424 || !level_ok(&body["merge_access_levels"])
1425 {
1426 StepState::not(
1430 "release/* grants are not exactly the owned maintainer levels",
1431 )
1432 } else {
1433 StepState::ok("release/* refuses force pushes and deletion by git clients")
1434 }
1435 }
1436 Api::Missing => StepState::inapplicable(
1437 "release/* is unprotected; optional — applied only where older lines exist",
1438 ),
1439 Api::Failed(err) => StepState::unknown(err),
1440 },
1441 ),
1442 "protections-check" => {
1443 let mut failures = Vec::new();
1446 let mut unknowns = Vec::new();
1447 let mut limitations: Vec<String> = Vec::new();
1450 for owned in ["protect-trunk", "protect-tags", "protect-release-lines"] {
1451 match gitlab(ctx, owned, run)? {
1452 StepState::Satisfied {
1453 limitation: found, ..
1454 } => limitations.extend(found),
1455 StepState::Inapplicable { .. } => {}
1456 StepState::Unsatisfied { detail } => {
1457 failures.push(format!("{owned}: {detail}"));
1458 }
1459 StepState::Unknown { detail } => {
1460 unknowns.push(format!("{owned}: {detail}"));
1461 }
1462 }
1463 }
1464 Ok(if !failures.is_empty() {
1465 StepState::not(failures.join("; "))
1466 } else if !unknowns.is_empty() {
1467 StepState::unknown(unknowns.join("; "))
1468 } else {
1469 StepState::Satisfied {
1470 detail: "the protections hold, as far as this forge enforces them".into(),
1471 limitation: if limitations.is_empty() {
1472 None
1473 } else {
1474 Some(limitations.join("; "))
1475 },
1476 }
1477 })
1478 }
1479 _ => Ok(StepState::unknown(format!("no observation for {step}"))),
1480 }
1481}