1use std::ffi::OsString;
12use std::fs;
13use std::path::PathBuf;
14use std::time::Instant;
15
16use zeroize::Zeroizing;
17
18use crate::cli::setup::{SetupAction, SetupArgs};
19use crate::detect::Forge;
20use crate::diagnostic::{Diagnostic, Reason};
21use crate::digest::Digest;
22use crate::embedded;
23use crate::error::RkError;
24use crate::events::{ChildStream, Event, EventKind};
25use crate::output::Output;
26use crate::setup::app_jwt::{self, AppApi};
27use crate::setup::context::{Ctx, SECRET_VARS};
28use crate::setup::journal::Journal;
29use crate::setup::observe::{self, StepState};
30use crate::setup::process::{self, Exec, Outcome};
31use crate::setup::secrets;
32use crate::setup::steps::{Mutates, STEPS, StepSpec, spec};
33
34pub fn run(args: &SetupArgs) -> Result<(), RkError> {
40 match &args.action {
41 Some(SetupAction::Script { name, forge }) => script(name, forge.as_deref()),
42 Some(SetupAction::Check {
43 target,
44 repo,
45 forge,
46 required_check,
47 json,
48 }) => {
49 let ctx = Ctx::resolve(
50 target,
51 repo.as_deref(),
52 forge.as_deref(),
53 required_check.as_deref(),
54 )?;
55 reject_check_flag_on_gitlab(&ctx)?;
56 check(Output::new(*json), ctx)
57 }
58 Some(SetupAction::Step {
59 name,
60 target,
61 repo,
62 forge,
63 required_check,
64 apply,
65 json,
66 }) => {
67 let selected = spec(name).ok_or_else(|| {
68 RkError::Usage(format!("unknown step '{name}'; rk setup --list names them"))
69 })?;
70 let ctx = Ctx::resolve(
71 target,
72 repo.as_deref(),
73 forge.as_deref(),
74 required_check.as_deref(),
75 )?;
76 reject_check_flag_on_gitlab(&ctx)?;
77 if *apply {
78 require_check_for(&ctx, &[selected])?;
79 execute(Output::new(*json), ctx, &[selected], "setup step")
80 } else {
81 preview(Output::new(*json), &ctx, &[selected])
82 }
83 }
84 None if args.list => list(args.forge.as_deref()),
85 None => {
86 let target = args.target.clone().ok_or_else(|| {
87 RkError::Usage("name a --target, or pass --list to see the steps".into())
88 })?;
89 let ctx = Ctx::resolve(
90 &target,
91 args.repo.as_deref(),
92 args.forge.as_deref(),
93 args.required_check.as_deref(),
94 )?;
95 reject_check_flag_on_gitlab(&ctx)?;
96 let all: Vec<&StepSpec> = STEPS.iter().collect();
97 if args.apply {
98 require_check_for(&ctx, &all)?;
99 execute(Output::new(args.json), ctx, &all, "setup")
100 } else {
101 preview(Output::new(args.json), &ctx, &all)
102 }
103 }
104 }
105}
106
107fn reject_check_flag_on_gitlab(ctx: &Ctx) -> Result<(), RkError> {
111 if ctx.forge == Forge::Gitlab && ctx.required_check.is_some() {
112 return Err(RkError::Usage(
113 "--required-check is refused on gitlab: the forge requires the whole pipeline and names no individual check".into(),
114 ));
115 }
116 Ok(())
117}
118
119fn require_check_for(ctx: &Ctx, steps: &[&StepSpec]) -> Result<(), RkError> {
124 let needs = ctx.forge == Forge::Github
125 && ctx.required_check.is_none()
126 && steps.iter().any(|step| step.name == "protect-trunk");
127 if needs {
128 return Err(RkError::refusal(
129 Diagnostic::new(
130 Reason::PrerequisiteUnmet,
131 "protect-trunk refuses without --required-check, and nothing was written",
132 )
133 .expected("the name of the CI check the release merge must pass")
134 .action(format!(
135 "pass --required-check <name>; gh api repos/{}/commits/HEAD/check-runs lists the project's check names",
136 ctx.repo
137 ))
138 .step("protect-trunk"),
139 ));
140 }
141 Ok(())
142}
143
144fn list(forge: Option<&str>) -> Result<(), RkError> {
148 let forge = forge
149 .map(|name| {
150 Forge::parse(name).ok_or_else(|| {
151 RkError::Usage(format!(
152 "unknown forge '{name}'; the forges are: github, gitlab"
153 ))
154 })
155 })
156 .transpose()?;
157 let out = Output::human();
158 for (idx, step) in STEPS.iter().enumerate() {
159 let mut line = format!(
160 "{:2}. {} [{}] proves: {}",
161 idx + 1,
162 step.name,
163 step.chapter,
164 step.proves
165 );
166 if step.name == "protect-trunk" && forge != Some(Forge::Gitlab) {
167 line.push_str(" (needs --required-check on github)");
168 }
169 if step.destructive {
170 line.push_str(" (destructive)");
171 }
172 if step.optional {
173 line.push_str(" (optional; a full apply skips it)");
174 }
175 out.result_line(line);
176 }
177 out.next(&[
178 "rk setup --target . previews every step".to_owned(),
179 "rk setup script <name> prints one embedded script".to_owned(),
180 ]);
181 Ok(())
182}
183
184fn script(name: &str, forge: Option<&str>) -> Result<(), RkError> {
187 if name == "package-check" {
188 return Err(RkError::Usage(
189 "package-check reads its command from the technology binding and has no script".into(),
190 ));
191 }
192 if name == "branch-reminder" {
193 return Err(RkError::Usage(
194 "branch-reminder writes an embedded hook body and has no script; rk setup step branch-reminder previews the write".into(),
195 ));
196 }
197 if name == "forge-version" {
198 return Err(RkError::Usage(
199 "forge-version reads the forge's own version and has no script; rk setup step forge-version previews the read".into(),
200 ));
201 }
202 let forge = match forge {
203 Some(value) => Forge::parse(value).ok_or_else(|| {
204 RkError::Usage(format!(
205 "unknown forge '{value}'; the forges are: github, gitlab"
206 ))
207 })?,
208 None => Forge::Github,
209 };
210 let path = format!("{}/{name}", forge.as_str());
211 let file = embedded::SETUP.get_file(&path).ok_or(RkError::NotFound {
212 kind: "setup step",
213 name: name.to_owned(),
214 })?;
215 Output::human().result_raw(&String::from_utf8_lossy(file.contents()));
216 Ok(())
217}
218
219struct Engine {
222 out: Output,
223 ctx: Ctx,
224 journal: Option<Journal>,
225 secrets: Vec<Zeroizing<Vec<u8>>>,
226 key: Option<secrets::KeyFile>,
228 app_jwt: Option<String>,
230 seq: u64,
231 command: &'static str,
232 run_id: String,
233}
234
235impl Engine {
236 fn open(
241 out: Output,
242 ctx: Ctx,
243 command: &'static str,
244 journal_required: bool,
245 ) -> Result<Self, RkError> {
246 secrets::refuse_legacy_key()?;
249 let journal =
250 match Journal::create(command, ctx.target.as_str(), ctx.forge.as_str(), &ctx.repo) {
251 Ok(journal) => Some(journal),
252 Err(source) if journal_required => {
253 return Err(RkError::refusal(
254 Diagnostic::new(
255 Reason::JournalUnavailable,
256 format!("the run journal cannot be created: {source}"),
257 )
258 .expected("a writable state root for the journal")
259 .target_state("nothing was run and nothing changed"),
260 ));
261 }
262 Err(source) => {
263 out.warn(format!("no run journal for this run: {source}"));
264 None
265 }
266 };
267 let run_id = journal
268 .as_ref()
269 .map_or_else(|| "unjournaled".to_owned(), |j| j.run_id().to_owned());
270 let mut engine = Self {
271 out,
272 ctx,
273 journal,
274 secrets: Ctx::secret_values(),
275 key: None,
276 app_jwt: None,
277 seq: 0,
278 command,
279 run_id,
280 };
281 let opening = Event::opening(
282 engine.next_seq(),
283 crate::applog::now_utc(),
284 engine.run_id.clone(),
285 engine.command,
286 );
287 engine.emit(&opening);
288 if engine.ctx.self_hosted_gitlab() {
289 engine.out.warn(
290 "this remote is a self-hosted GitLab: registry trusted publishing covers GitLab.com only, so the OIDC invariant cannot be satisfied here",
291 );
292 }
293 Ok(engine)
294 }
295
296 const fn next_seq(&mut self) -> u64 {
297 let seq = self.seq;
298 self.seq += 1;
299 seq
300 }
301
302 fn event(&mut self, kind: EventKind, step: Option<&str>) -> Event {
303 let mut event = Event::opening(
304 self.next_seq(),
305 crate::applog::now_utc(),
306 self.run_id.clone(),
307 self.command,
308 );
309 event.kind = kind;
310 event.step = step.map(str::to_owned);
311 event
312 }
313
314 fn emit(&mut self, event: &Event) {
315 self.out.event(event);
316 if let Some(journal) = &mut self.journal {
317 if let Ok(line) = serde_json::to_string(event) {
318 journal.event_line(&line);
319 }
320 }
321 }
322
323 fn exec(&mut self, exec: &Exec, passthrough: bool) -> Result<Outcome, RkError> {
326 let echo = exec.echo();
327 self.out.frame(&echo);
328 if let Some(journal) = &mut self.journal {
329 journal.transcript(echo.as_bytes());
330 journal.transcript(b"\n");
331 }
332 let secrets = std::mem::take(&mut self.secrets);
333 let step_name: Option<String> = None;
334 let mut chunks: Vec<(ChildStream, Vec<u8>)> = Vec::new();
335 let spawned = process::run(exec, |stream, chunk| {
336 chunks.push((stream, process::redact(chunk, &secrets)));
337 });
338 self.secrets = secrets;
339 for (stream, chunk) in chunks {
340 if passthrough {
341 self.out.child_passthrough(stream, &chunk);
342 }
343 let event = self.event(EventKind::ChildOutput, step_name.as_deref());
344 let event = event.child_output(stream, &chunk);
345 self.emit(&event);
346 if let Some(journal) = &mut self.journal {
347 journal.transcript(&chunk);
348 }
349 }
350 spawned.map_err(|source| {
351 RkError::refusal(
352 Diagnostic::new(
353 Reason::SubprocessSpawn,
354 format!("{} did not spawn: {source}", exec.program.to_string_lossy()),
355 )
356 .expected("a POSIX sh and the forge CLI on PATH")
357 .run(self.run_path()),
358 )
359 })
360 }
361
362 fn run_path(&self) -> String {
363 self.journal.as_ref().map_or_else(
364 || "no journal was written".to_owned(),
365 |j| j.dir.display().to_string(),
366 )
367 }
368
369 fn finish(&mut self, exit_code: i32, reason: Option<&str>) {
370 let mut event = self.event(EventKind::RunFinished, None);
371 event.exit_code = Some(exit_code);
372 event.status = Some(if exit_code == 0 {
373 "ok".into()
374 } else {
375 "failed".into()
376 });
377 self.emit(&event);
378 if let Some(journal) = &mut self.journal {
379 journal.finish(exit_code, reason);
380 }
381 }
382}
383
384fn fail(engine: &mut Engine, error: RkError) -> RkError {
386 let error = match error {
387 RkError::Refusal(mut diagnostic) => {
388 diagnostic.run.get_or_insert_with(|| engine.run_path());
389 RkError::Refusal(diagnostic)
390 }
391 RkError::Subprocess(mut diagnostic) => {
392 diagnostic.run.get_or_insert_with(|| engine.run_path());
393 RkError::Subprocess(diagnostic)
394 }
395 RkError::CheckFailed(mut diagnostic) => {
396 diagnostic.run.get_or_insert_with(|| engine.run_path());
397 RkError::CheckFailed(diagnostic)
398 }
399 other => other,
400 };
401 engine.finish(i32::from(error.exit_code()), Some(error.reason().as_str()));
402 error
403}
404
405fn preview(out: Output, ctx: &Ctx, steps: &[&StepSpec]) -> Result<(), RkError> {
411 let mut engine = Engine::open(out, clone_ctx(ctx), "setup preview", false)?;
412 out.result_line(format!(
413 "DRY RUN: rk setup would run these steps against {} on {}; re-run with --apply",
414 engine.ctx.repo,
415 engine.ctx.forge.as_str()
416 ));
417 for (idx, step) in steps.iter().enumerate() {
418 out.result_line(format!(
419 "step {}/{} {} — proves {}",
420 idx + 1,
421 steps.len(),
422 step.name,
423 step.proves
424 ));
425 if step.name == "bot-secrets" && engine.ctx.forge == Forge::Github {
429 secrets::resolve_key_file(&engine.ctx.target)?;
430 }
431 out.result_line(format!(" {}", render_invocation(&engine.ctx, step)));
432 if step.name == "protect-trunk"
433 && engine.ctx.forge == Forge::Github
434 && engine.ctx.required_check.is_none()
435 {
436 out.result_line(" needs: --required-check <name> before apply");
437 }
438 if step.optional && steps.len() > 1 {
439 out.result_line(format!(
440 " optional: a full apply skips it; rk setup step {} --apply runs it",
441 step.name
442 ));
443 }
444 let mut event = engine.event(EventKind::StepFinished, Some(step.name));
445 event.status = Some("previewed".into());
446 engine.emit(&event);
447 }
448 let next = next_for_apply(&engine.ctx, steps);
449 out.next(&[
450 next,
451 "rk setup check --target . proves what is already true".to_owned(),
452 ]);
453 engine.finish(0, None);
454 Ok(())
455}
456
457fn render_invocation(ctx: &Ctx, step: &StepSpec) -> String {
460 match step.name {
461 "branch-reminder" => {
462 "would write: the post-merge reminder hook at $(git rev-parse --git-path hooks)/post-merge".to_owned()
463 }
464 "package-check" => match ctx.tech {
465 Some("rust") => "would run: cargo publish --dry-run --allow-dirty".to_owned(),
466 Some("python") => "would run: python3 -m build".to_owned(),
467 Some("bash") => "nothing to run: no registry for this technology".to_owned(),
468 _ => "needs: a version file naming the technology".to_owned(),
469 },
470 "forge-version" => {
471 let (major, minor) = observe::GITLAB_VERSION_FLOOR;
472 match ctx.forge {
473 Forge::Github => {
474 "nothing to read: github.com is a rolling service and declares no version floor"
475 .to_owned()
476 }
477 Forge::Gitlab => format!(
478 "would read: GET /version, and compare it against the {major}.{minor} floor; nothing is written"
479 ),
480 }
481 }
482 name => {
483 let check = ctx
484 .required_check
485 .as_ref()
486 .filter(|_| ctx.forge == Forge::Github && name == "protect-trunk")
487 .map(|value| format!(" RK_REQUIRED_CHECK={value}"))
488 .unwrap_or_default();
489 format!(
490 "would run: sh <embedded setup/{}/{name}> with RK_REPO={} RK_TRUNK_BRANCH=master{check}",
491 ctx.forge.as_str(),
492 ctx.repo
493 )
494 }
495 }
496}
497
498fn next_for_apply(ctx: &Ctx, steps: &[&StepSpec]) -> String {
499 let check = ctx
500 .required_check
501 .as_ref()
502 .map(|value| format!(" --required-check {value}"))
503 .unwrap_or_default();
504 if steps.len() == 1 {
505 format!(
506 "rk setup step {} --target {} --apply{check}",
507 steps[0].name, ctx.target
508 )
509 } else {
510 format!("rk setup --target {} --apply{check}", ctx.target)
511 }
512}
513
514fn clone_ctx(ctx: &Ctx) -> Ctx {
516 Ctx {
517 target: ctx.target.clone(),
518 repo: ctx.repo.clone(),
519 forge: ctx.forge,
520 host: ctx.host.clone(),
521 required_check: ctx.required_check.clone(),
522 cli: ctx.cli.clone(),
523 tech: ctx.tech,
524 }
525}
526
527fn execute(
529 out: Output,
530 ctx: Ctx,
531 steps: &[&StepSpec],
532 command: &'static str,
533) -> Result<(), RkError> {
534 guard_sh()?;
535 let mut engine = Engine::open(out, ctx, command, true)?;
536 let mut done: Vec<(String, String)> = Vec::new();
537 for (idx, step) in steps.iter().enumerate() {
538 if step.optional && steps.len() > 1 {
541 engine.out.frame(format!(
542 "step {}/{} {} — skipped (optional; rk setup step {} --apply runs it)",
543 idx + 1,
544 steps.len(),
545 step.name,
546 step.name
547 ));
548 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
549 finished.status = Some("skipped".into());
550 engine.emit(&finished);
551 done.push((step.name.to_owned(), "skipped".to_owned()));
552 continue;
553 }
554 engine.out.frame(format!(
555 "step {}/{} {} — {}",
556 idx + 1,
557 steps.len(),
558 step.name,
559 step.proves
560 ));
561 let mut started = engine.event(EventKind::StepStarted, Some(step.name));
562 started.status = Some("running".into());
563 engine.emit(&started);
564 let clock = Instant::now();
565 let status = match apply_step(&mut engine, step) {
566 Ok(status) => status,
567 Err(error) => {
568 let error = attach_progress(error, &done, step, steps);
569 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
570 finished.status = Some("failed".into());
571 finished.reason = Some(error.reason());
572 finished.duration_ms = Some(elapsed_ms(clock));
573 engine.emit(&finished);
574 return Err(fail(&mut engine, error));
575 }
576 };
577 engine
578 .out
579 .frame(format!("ok {}: {}", step.name, status.line()));
580 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
581 finished.status = Some(status.wire().into());
582 finished.exit_code = Some(0);
583 finished.duration_ms = Some(elapsed_ms(clock));
584 engine.emit(&finished);
585 done.push((step.name.to_owned(), status.wire().to_owned()));
586 }
587 engine.out.result_line(format!(
588 "setup: {} completed against {}",
589 step_count(done.len()),
590 engine.ctx.repo
591 ));
592 for (name, status) in &done {
593 engine.out.result_line(format!(" {status} {name}"));
594 }
595 engine.out.next(&[
596 format!("rk setup check --target {}", engine.ctx.target),
597 "rk guide setup orders what no command performs".to_owned(),
598 ]);
599 engine.finish(0, None);
600 Ok(())
601}
602
603fn step_count(count: usize) -> String {
606 format!("{count} {}", if count == 1 { "step" } else { "steps" })
607}
608
609fn elapsed_ms(clock: Instant) -> u64 {
610 u64::try_from(clock.elapsed().as_millis()).unwrap_or(u64::MAX)
611}
612
613enum Done {
615 Satisfied(String),
617 Changed(String, Option<String>),
619 Passed(String),
621}
622
623impl Done {
624 const fn wire(&self) -> &'static str {
625 match self {
626 Self::Satisfied(_) => "satisfied",
627 Self::Changed(..) => "applied",
628 Self::Passed(_) => "passed",
629 }
630 }
631
632 fn line(&self) -> String {
633 match self {
634 Self::Satisfied(detail) | Self::Passed(detail) => detail.clone(),
635 Self::Changed(detail, limitation) => limitation.as_ref().map_or_else(
636 || detail.clone(),
637 |limit| format!("{detail} (limitation: {limit})"),
638 ),
639 }
640 }
641}
642
643#[allow(clippy::too_many_lines)]
645fn apply_step(engine: &mut Engine, step: &StepSpec) -> Result<Done, RkError> {
646 for prereq in step.prereqs {
649 let state = observe_with(engine, prereq)?;
650 if !state.satisfied() {
651 return Err(RkError::refusal(
652 Diagnostic::new(
653 Reason::PrerequisiteUnmet,
654 format!(
655 "{} requires {prereq} first: {}",
656 step.name,
657 state_detail(&state)
658 ),
659 )
660 .expected(format!("{prereq} satisfied before {}", step.name))
661 .action(format!(
662 "rk setup step {prereq} --target {} --apply",
663 engine.ctx.target
664 ))
665 .step(step.name),
666 ));
667 }
668 }
669 match step.name {
670 "package-check" => {
671 if engine.ctx.tech.is_none() {
672 return Err(RkError::Usage(
673 "no version file names a technology; rk binding --list names the bindings"
674 .into(),
675 ));
676 }
677 let state = observe_with(engine, "package-check")?;
678 match state {
679 StepState::Satisfied { detail, .. } => Ok(Done::Passed(detail)),
680 StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
681 Err(RkError::subprocess(
682 Diagnostic::new(
683 Reason::SubprocessFailed,
684 format!("package-check failed: {detail}"),
685 )
686 .expected(step.proves.to_owned())
687 .step(step.name),
688 ))
689 }
690 StepState::Unknown { detail } => Err(RkError::subprocess(
691 Diagnostic::new(
692 Reason::SubprocessFailed,
693 format!("package-check could not run: {detail}"),
694 )
695 .step(step.name),
696 )),
697 }
698 }
699 "forge-version" => match observe_with(engine, "forge-version")? {
705 StepState::Satisfied { detail, .. } => Ok(Done::Satisfied(detail)),
706 StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
707 Err(RkError::refusal(
708 Diagnostic::new(Reason::PrerequisiteUnmet, detail)
709 .expected(step.proves.to_owned())
710 .action("upgrade the instance, or host the project on gitlab.com")
711 .target_state("unchanged")
712 .step(step.name),
713 ))
714 }
715 StepState::Unknown { detail } => Err(RkError::refusal(
716 Diagnostic::new(Reason::ForgeTemporary, detail)
717 .expected("a readable forge version")
718 .action("glab auth login, then rerun")
719 .target_state("unchanged")
720 .step(step.name),
721 )),
722 },
723 "branch-reminder" => {
724 use crate::setup::branch_reminder::{HookState, hook_body, hook_path, observe_hook};
725 match observe_hook(&engine.ctx.target) {
726 HookState::Installed => Ok(Done::Satisfied(
727 "the post-merge reminder hook is installed".into(),
728 )),
729 HookState::Foreign => Err(RkError::refusal(
730 Diagnostic::new(
731 Reason::StateDrift,
732 "a foreign post-merge hook exists; the reminder is never written over it",
733 )
734 .expected("no post-merge hook, or one carrying the release-kit marker")
735 .action(
736 "merge by hand: guard each call behind its own capability probe inside the existing hook — `rk branches prune --help >/dev/null 2>&1` before `rk branches prune --quiet || :`, and the same pair for `rk worktree prune`",
737 )
738 .target_state("unchanged")
739 .step(step.name),
740 )),
741 HookState::Unreadable(detail) => Err(RkError::refusal(
742 Diagnostic::new(
743 Reason::StateDrift,
744 format!("the post-merge hook cannot be read: {detail}"),
745 )
746 .target_state("unchanged")
747 .step(step.name),
748 )),
749 HookState::Absent | HookState::Drifted => {
750 let path = hook_path(&engine.ctx.target).map_err(|detail| {
751 RkError::refusal(
752 Diagnostic::new(
753 Reason::PrerequisiteUnmet,
754 format!("the hooks directory cannot be resolved: {detail}"),
755 )
756 .expected("a git repository whose hooks directory git can name")
757 .step(step.name),
758 )
759 })?;
760 crate::atomic::write(&path, hook_body())?;
761 #[cfg(unix)]
762 {
763 use std::os::unix::fs::PermissionsExt as _;
764 std::fs::set_permissions(
765 &path,
766 std::fs::Permissions::from_mode(0o755),
767 )?;
768 }
769 Ok(Done::Changed(
770 "wrote the post-merge reminder hook".into(),
771 None,
772 ))
773 }
774 }
775 }
776 "single-trunk" => {
777 let guard = {
778 let ctx = clone_ctx(&engine.ctx);
779 let mut runner = |exec: &Exec| engine.exec(exec, false);
780 observe::single_trunk_guard(&ctx, &mut runner)?
781 };
782 match &guard {
785 StepState::Satisfied { .. } => {}
786 StepState::Unsatisfied { detail }
787 | StepState::Inapplicable { detail }
788 | StepState::Unknown { detail } => {
789 return Err(RkError::refusal(
790 Diagnostic::new(
791 Reason::DestructiveRefusal,
792 format!("single-trunk refuses: {detail}"),
793 )
794 .expected(
795 "proof that every candidate branch is absent, or an ancestor of the trunk",
796 )
797 .step(step.name),
798 ));
799 }
800 }
801 run_forge_step(engine, step)
802 }
803 "bot-secrets" => {
804 let key = match engine.ctx.forge {
810 Forge::Github => key_file_for(engine)?.map(|key| key.bytes.clone()),
814 Forge::Gitlab => None,
815 };
816 let provided = match engine.ctx.forge {
817 Forge::Github => secrets::value_of("RK_BOT_APP_ID").is_some() && key.is_some(),
820 Forge::Gitlab => secrets::value_of("RK_BOT_TOKEN").is_some(),
821 };
822 let state = observe_with(engine, step.name)?;
823 if !provided {
824 if state.satisfied() {
825 return Ok(Done::Satisfied(state_detail(&state)));
826 }
827 let wanted = match engine.ctx.forge {
828 Forge::Github => {
829 "export RK_BOT_APP_ID and RK_BOT_PRIVATE_KEY_FILE, the second naming the .pem; rk forge github carries the walkthrough"
830 }
831 Forge::Gitlab => {
832 "rk setup step install-bot --apply stores the token, or export RK_BOT_TOKEN to rotate one"
833 }
834 };
835 return Err(RkError::refusal(
836 Diagnostic::new(
837 Reason::PrerequisiteUnmet,
838 "bot-secrets has no credentials to store",
839 )
840 .expected("the bot credentials in the environment, the key as a path")
841 .action(wanted.to_owned())
842 .step(step.name),
843 ));
844 }
845 if let Some(journal) = &mut engine.journal {
846 for name in SECRET_VARS {
847 if secrets::value_of(name).is_some() {
848 journal.record_secret(name, true, "environment");
849 }
850 }
851 if key.is_some() {
852 journal.record_secret(secrets::PRIVATE_KEY_FILE, true, "file");
853 }
854 }
855 let stdin = key;
859 run_forge_step_with(engine, step, stdin, Vec::new())
860 }
861 "protections-check" => {
862 let (outcome, _) = run_script(engine, step)?;
863 if !outcome.success() {
864 return Err(classify_failure(engine, step, &outcome));
865 }
866 match observe_with(engine, step.name)? {
870 StepState::Satisfied { detail, limitation } => {
871 Ok(Done::Passed(limitation.map_or_else(
872 || detail.clone(),
873 |limit| format!("{detail} (limitation: {limit})"),
874 )))
875 }
876 StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
877 Err(RkError::refusal(
878 Diagnostic::new(
879 Reason::StateDrift,
880 format!("protections-check passed its script and the observation disagrees: {detail}"),
881 )
882 .expected(step.proves.to_owned())
883 .step(step.name),
884 ))
885 }
886 StepState::Unknown { detail } => Err(RkError::refusal(
889 Diagnostic::new(
890 Reason::ForgeTemporary,
891 format!(
892 "protections-check passed its script and the readback could not confirm it: {detail}"
893 ),
894 )
895 .expected(step.proves.to_owned())
896 .action("check authentication and connectivity, then rerun")
897 .step(step.name),
898 )),
899 }
900 }
901 "install-bot" if engine.ctx.forge == Forge::Github => {
907 match observe_with(engine, step.name)? {
908 StepState::Satisfied { detail, .. } => {
909 return Ok(Done::Satisfied(detail));
910 }
911 StepState::Unsatisfied { .. } | StepState::Inapplicable { .. } => {}
912 StepState::Unknown { detail } => {
913 return Err(RkError::refusal(
914 Diagnostic::new(
915 Reason::ForgeTemporary,
916 format!("{} cannot observe the current state: {detail}", step.name),
917 )
918 .expected("a readable forge answer before anything mutates")
919 .action("check the App credentials and connectivity, then rerun")
920 .step(step.name),
921 ));
922 }
923 }
924 let installation = github_installation_id(engine, step)?;
925 run_forge_step_with(
926 engine,
927 step,
928 None,
929 vec![("RK_BOT_INSTALLATION".into(), installation.into())],
930 )
931 }
932 _ => {
933 if step.mutates == Mutates::Forge {
934 match observe_with(engine, step.name)? {
939 StepState::Satisfied { detail, .. } => {
940 return Ok(Done::Satisfied(detail));
941 }
942 StepState::Unsatisfied { .. } | StepState::Inapplicable { .. } => {}
943 StepState::Unknown { detail } => {
944 return Err(RkError::refusal(
945 Diagnostic::new(
946 Reason::ForgeTemporary,
947 format!("{} cannot observe the current state: {detail}", step.name),
948 )
949 .expected("a readable forge answer before anything mutates")
950 .action("check authentication and connectivity, then rerun")
951 .step(step.name),
952 ));
953 }
954 }
955 }
956 run_forge_step(engine, step)
957 }
958 }
959}
960
961fn github_installation_id(engine: &mut Engine, step: &StepSpec) -> Result<String, RkError> {
969 let refuse = |message: String, action: &str| {
970 RkError::refusal(
971 Diagnostic::new(Reason::PrerequisiteUnmet, message)
972 .expected("the App installed on the repository's owner")
973 .action(action.to_owned())
974 .step(step.name),
975 )
976 };
977 let jwt = match app_jwt_for(engine)? {
978 Ok(jwt) => jwt,
979 Err(detail) => {
980 return Err(refuse(
981 format!("install-bot has no App token: {detail}"),
982 app_jwt::REMEDIATION,
983 ));
984 }
985 };
986 let owner = engine
987 .ctx
988 .repo
989 .split('/')
990 .next()
991 .unwrap_or_default()
992 .to_owned();
993 let ctx = clone_ctx(&engine.ctx);
994 for path in [
995 format!("users/{owner}/installation"),
996 format!("orgs/{owner}/installation"),
997 ] {
998 match app_jwt::api_get(&ctx, &jwt, &path) {
999 AppApi::Ok(body) => {
1000 return body["id"].as_i64().map(|id| id.to_string()).ok_or_else(|| {
1001 refuse(
1002 format!("the forge answered {path} without an installation id"),
1003 "check RK_BOT_APP_ID and the key file name the same App",
1004 )
1005 });
1006 }
1007 AppApi::Missing => {}
1008 AppApi::Refused(detail) => {
1009 return Err(refuse(
1010 detail,
1011 "check RK_BOT_APP_ID and the key file name the same App",
1012 ));
1013 }
1014 AppApi::Failed(detail) => {
1015 return Err(RkError::refusal(
1016 Diagnostic::new(
1017 Reason::ForgeTemporary,
1018 format!("install-bot cannot read the App's installation: {detail}"),
1019 )
1020 .action("check connectivity, then rerun")
1021 .step(step.name),
1022 ));
1023 }
1024 }
1025 }
1026 Err(refuse(
1027 format!("the App has no installation on {owner}"),
1028 "install the App on the account first; the setup guide's step 5 walks it",
1029 ))
1030}
1031
1032fn run_forge_step(engine: &mut Engine, step: &StepSpec) -> Result<Done, RkError> {
1034 run_forge_step_with(engine, step, None, Vec::new())
1035}
1036
1037fn run_forge_step_with(
1040 engine: &mut Engine,
1041 step: &StepSpec,
1042 stdin: Option<Zeroizing<Vec<u8>>>,
1043 extra_env: Vec<(OsString, OsString)>,
1044) -> Result<Done, RkError> {
1045 let (outcome, _) = run_script_with(engine, step, stdin, extra_env)?;
1046 if !outcome.success() {
1047 return Err(classify_failure(engine, step, &outcome));
1048 }
1049 let state = observe_with(engine, step.name)?;
1050 match state {
1051 StepState::Satisfied { detail, limitation } => Ok(Done::Changed(detail, limitation)),
1052 StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
1053 Err(RkError::refusal(
1054 Diagnostic::new(
1055 Reason::StateDrift,
1056 format!(
1057 "{} ran and its postcondition does not hold: {detail}",
1058 step.name
1059 ),
1060 )
1061 .expected(step.proves.to_owned())
1062 .step(step.name),
1063 ))
1064 }
1065 StepState::Unknown { detail } => Err(RkError::refusal(
1069 Diagnostic::new(
1070 Reason::ForgeTemporary,
1071 format!(
1072 "{} ran and the readback could not confirm it: {detail}",
1073 step.name
1074 ),
1075 )
1076 .expected(step.proves.to_owned())
1077 .action(format!(
1078 "rk setup step {} --target {} --apply re-asserts and re-proves it",
1079 step.name, engine.ctx.target
1080 ))
1081 .step(step.name),
1082 )),
1083 }
1084}
1085
1086fn observe_with(engine: &mut Engine, step: &str) -> Result<StepState, RkError> {
1093 if step == "install-bot" && engine.ctx.forge == Forge::Github {
1094 let jwt = match app_jwt_for(engine)? {
1095 Ok(jwt) => jwt,
1096 Err(detail) => return Ok(StepState::Unknown { detail }),
1097 };
1098 return Ok(observe::github_install_bot(&engine.ctx, &jwt));
1099 }
1100 let ctx = clone_ctx(&engine.ctx);
1101 let mut runner = |exec: &Exec| engine.exec(exec, false);
1102 observe::observe(&ctx, step, &mut runner)
1103}
1104
1105fn key_file_for(engine: &mut Engine) -> Result<Option<&secrets::KeyFile>, RkError> {
1111 if engine.key.is_none() {
1112 engine.key = secrets::resolve_key_file(&engine.ctx.target)?;
1113 if let Some(key) = &engine.key {
1114 engine.secrets.push(key.bytes.clone());
1115 }
1116 }
1117 Ok(engine.key.as_ref())
1118}
1119
1120fn app_jwt_for(engine: &mut Engine) -> Result<Result<String, String>, RkError> {
1130 if let Some(jwt) = &engine.app_jwt {
1131 return Ok(Ok(jwt.clone()));
1132 }
1133 let app_id = app_jwt::app_id()?;
1134 let key_bytes = key_file_for(engine)?.map(|key| key.bytes.clone());
1135 let (Some(app_id), Some(key_bytes)) = (app_id, key_bytes) else {
1136 return Ok(Err(format!(
1137 "the installation is readable only to the App itself; {}",
1138 app_jwt::REMEDIATION
1139 )));
1140 };
1141 let credentials = app_jwt::AppCredentials { app_id, key_bytes };
1142 let ctx = clone_ctx(&engine.ctx);
1143 Ok(match app_jwt::mint(&ctx, &credentials) {
1144 Ok(jwt) => {
1145 engine
1146 .secrets
1147 .push(Zeroizing::new(jwt.clone().into_bytes()));
1148 if let Some(signature) = jwt.rsplit('.').next() {
1149 engine
1150 .secrets
1151 .push(Zeroizing::new(signature.as_bytes().to_vec()));
1152 }
1153 engine.app_jwt = Some(jwt.clone());
1154 Ok(jwt)
1155 }
1156 Err(detail) => Err(detail),
1157 })
1158}
1159
1160fn state_detail(state: &StepState) -> String {
1161 match state {
1162 StepState::Satisfied { detail, .. }
1163 | StepState::Unsatisfied { detail }
1164 | StepState::Inapplicable { detail }
1165 | StepState::Unknown { detail } => detail.clone(),
1166 }
1167}
1168
1169fn run_script(engine: &mut Engine, step: &StepSpec) -> Result<(Outcome, PathBuf), RkError> {
1172 run_script_with(engine, step, None, Vec::new())
1173}
1174
1175fn run_script_with(
1181 engine: &mut Engine,
1182 step: &StepSpec,
1183 stdin: Option<Zeroizing<Vec<u8>>>,
1184 extra_env: Vec<(OsString, OsString)>,
1185) -> Result<(Outcome, PathBuf), RkError> {
1186 let rel = format!("{}/{}", engine.ctx.forge.as_str(), step.name);
1187 let bytes = embedded::SETUP
1188 .get_file(&rel)
1189 .map(include_dir::File::contents)
1190 .ok_or_else(|| RkError::Other(anyhow::anyhow!("no embedded script at setup/{rel}")))?;
1191 let journal = engine
1192 .journal
1193 .as_mut()
1194 .ok_or_else(|| RkError::Other(anyhow::anyhow!("an apply always has a journal")))?;
1195 let dir = journal.scripts_dir().join(engine.ctx.forge.as_str());
1196 fs::create_dir_all(&dir)?;
1197 restrict(&dir, 0o700);
1198 let path = dir.join(step.name);
1199 fs::write(&path, bytes)?;
1200 restrict(&path, 0o600);
1201 let written = fs::read(&path)?;
1202 let digest = Digest::of(&written);
1203 if digest != Digest::of(bytes) {
1204 return Err(RkError::Other(anyhow::anyhow!(
1205 "the materialized script at {} differs from the embedded bytes",
1206 path.display()
1207 )));
1208 }
1209 journal.record_script(format!("scripts/{rel}"), digest.to_string());
1210 let mut env = engine.ctx.child_env(step.name);
1211 env.extend(extra_env);
1212 let exec = Exec {
1213 program: crate::probes::sh_bin(),
1214 args: vec![path.clone().into_os_string()],
1215 env,
1216 cwd: engine.ctx.target.as_std_path().to_path_buf(),
1217 stdin,
1218 };
1219 let outcome = engine.exec(&exec, true)?;
1220 Ok((outcome, path))
1221}
1222
1223fn classify_failure(engine: &Engine, step: &StepSpec, outcome: &Outcome) -> RkError {
1228 let stderr = String::from_utf8_lossy(&outcome.stderr);
1229 let last = if outcome.exit_code >= 128 {
1233 format!("killed by signal {}", outcome.exit_code - 128)
1234 } else {
1235 stderr
1236 .lines()
1237 .rev()
1238 .find(|line| !line.trim().is_empty())
1239 .unwrap_or("no output")
1240 .to_owned()
1241 };
1242 let reason = if (engine.ctx.forge == Forge::Github && outcome.exit_code == 4)
1243 || stderr.contains("HTTP 401")
1244 {
1245 Reason::ForgeAuthentication
1246 } else if stderr.contains("HTTP 403") {
1247 Reason::ForgePermission
1248 } else if stderr.contains("HTTP 429") || stderr.contains("rate limit") {
1249 Reason::ForgeRateLimit
1250 } else {
1251 Reason::SubprocessFailed
1252 };
1253 let diagnostic = Diagnostic::new(reason, format!("the forge refused '{}': {last}", step.name))
1254 .expected(step.proves.to_owned())
1255 .action(format!(
1256 "rk setup step {} --target {} --apply",
1257 step.name, engine.ctx.target
1258 ))
1259 .step(step.name);
1260 let diagnostic = match reason {
1261 Reason::ForgePermission => diagnostic.expected(format!(
1262 "repository administration write on {} for the authenticated account",
1263 engine.ctx.repo
1264 )),
1265 _ => diagnostic,
1266 };
1267 match reason {
1268 Reason::SubprocessFailed => RkError::subprocess(diagnostic),
1269 _ => RkError::refusal(diagnostic),
1270 }
1271}
1272
1273fn attach_progress(
1276 error: RkError,
1277 done: &[(String, String)],
1278 failed: &StepSpec,
1279 steps: &[&StepSpec],
1280) -> RkError {
1281 let remaining = steps.len().saturating_sub(done.len() + 1);
1282 let state = format!(
1283 "{} completed; {} failed; {remaining} not attempted",
1284 step_count(done.len()),
1285 failed.name
1286 );
1287 match error {
1288 RkError::Refusal(mut diagnostic) => {
1289 diagnostic.target_state.get_or_insert(state);
1290 RkError::Refusal(diagnostic)
1291 }
1292 RkError::Subprocess(mut diagnostic) => {
1293 diagnostic.target_state.get_or_insert(state);
1294 RkError::Subprocess(diagnostic)
1295 }
1296 other => other,
1297 }
1298}
1299
1300fn check(out: Output, ctx: Ctx) -> Result<(), RkError> {
1304 let mut engine = Engine::open(out, ctx, "setup check", false)?;
1305 let mut unsatisfied = 0usize;
1306 let mut unverifiable = 0usize;
1307 for step in &STEPS {
1308 let clock = Instant::now();
1309 let state = observe_with(&mut engine, step.name)?;
1310 let (label, wire) = match &state {
1311 StepState::Satisfied { .. } => ("ok", "satisfied"),
1312 StepState::Inapplicable { .. } => ("skipped", "skipped"),
1315 StepState::Unsatisfied { .. } => {
1316 unsatisfied += 1;
1317 ("unsatisfied", "unsatisfied")
1318 }
1319 StepState::Unknown { .. } => {
1322 unverifiable += 1;
1323 ("unknown", "unknown")
1324 }
1325 };
1326 let mut line = format!("{label} {} — {}", step.name, state_detail(&state));
1327 if let StepState::Satisfied {
1328 limitation: Some(limit),
1329 ..
1330 } = &state
1331 {
1332 use std::fmt::Write as _;
1333 let _ = write!(line, " (limitation: {limit})");
1334 }
1335 engine.out.result_line(line);
1336 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
1337 finished.status = Some(wire.into());
1338 finished.duration_ms = Some(elapsed_ms(clock));
1339 engine.emit(&finished);
1340 }
1341 if unsatisfied > 0 || unverifiable > 0 {
1342 let error = RkError::check_failed(
1343 Diagnostic::new(
1344 Reason::StateDrift,
1345 format!(
1346 "{} {} not satisfied and {unverifiable} could not be verified",
1347 step_count(unsatisfied),
1348 if unsatisfied == 1 { "is" } else { "are" }
1349 ),
1350 )
1351 .expected("every step's proof column to hold and to be readable")
1352 .action(format!(
1353 "rk setup --target {} --apply re-asserts them",
1354 engine.ctx.target
1355 )),
1356 );
1357 return Err(fail(&mut engine, error));
1358 }
1359 engine
1360 .out
1361 .next(&["rk guide release orders the first release".to_owned()]);
1362 engine.finish(0, None);
1363 Ok(())
1364}
1365
1366fn restrict(path: &std::path::Path, mode: u32) {
1369 #[cfg(unix)]
1370 {
1371 use std::os::unix::fs::PermissionsExt as _;
1372 let _ = fs::set_permissions(path, fs::Permissions::from_mode(mode));
1373 }
1374 #[cfg(not(unix))]
1375 let _ = (path, mode);
1376}
1377
1378fn guard_sh() -> Result<(), RkError> {
1381 let ok = std::process::Command::new(crate::probes::sh_bin())
1382 .args(["-c", "exit 0"])
1383 .status()
1384 .is_ok_and(|status| status.success());
1385 if ok {
1386 Ok(())
1387 } else {
1388 Err(RkError::refusal(
1389 Diagnostic::new(Reason::PrerequisiteUnmet, "no POSIX sh runs on this host")
1390 .expected("a working sh on PATH; every step spawns through it")
1391 .action("install a POSIX shell, then rerun")
1392 .target_state("nothing was run and nothing changed"),
1393 ))
1394 }
1395}
1396
1397#[cfg(test)]
1398mod tests {
1399 #[test]
1402 fn a_step_count_carries_a_noun_that_agrees_with_it() {
1403 assert_eq!(super::step_count(0), "0 steps");
1404 assert_eq!(super::step_count(1), "1 step");
1405 assert_eq!(super::step_count(2), "2 steps");
1406 }
1407}