Skip to main content

max / makenotwork

149.0 KB · 3554 lines History Blame Raw
1 //! Rhai recipe engine + host-function API.
2 //!
3 //! A `(app, target)` resolves to a `.rhai` recipe composed from a shared step
4 //! vocabulary. The daemon embeds Rhai and registers the host functions recipes
5 //! call; the recipe is the orchestration, the host functions are the
6 //! privileged primitives (run a command, read a secret, collect artifacts,
7 //! publish). Recipes are otherwise sandboxed — no arbitrary FS/network except
8 //! through these functions — matching the Balanced Breakfast plugin model.
9 //!
10 //! Rhai is synchronous; the engine runs each recipe on a blocking thread
11 //! (`spawn_blocking`, see [`crate::runner`]) and host functions bridge to async
12 //! work via `Handle::block_on`. That is sound only off a runtime worker thread,
13 //! which `spawn_blocking` guarantees.
14
15 use crate::config::Config;
16 use crate::domain::{AppId, Status, Step, StepRunId, Target, Version};
17 use crate::events::{self, Event, EventTx};
18 use crate::ota::{OtaRegistry, PublishAuthority, Release};
19 use crate::state::ExecutorMap;
20 use crate::topology::{DeployTarget, Kind};
21 use anyhow::{Context as _, Result};
22 use ops_core::live_log::LiveLog;
23 use ops_exec::{Action, Executor, ObserveKind, Step as OpStep, SyncOpts};
24 use rhai::{Engine, EvalAltResult, Map};
25 use sha2::{Digest, Sha256};
26 use sqlx::SqlitePool;
27 use std::collections::HashMap;
28 use std::path::{Path, PathBuf};
29 use std::sync::atomic::{AtomicBool, Ordering};
30 use std::sync::{Arc, Mutex};
31 use tokio::runtime::Handle;
32 use tokio::sync::Mutex as AsyncMutex;
33
34 /// The capability label for a command, derived from the open recipe step. A
35 /// recipe's `sh("mbp", …)` under `step("sign")` becomes an `Action::Sign`, gated
36 /// by the mac host's `sign` grant — so recipes stay unchanged while every command
37 /// is capability-checked at its transport. `Verify` is read-only (an observe).
38 /// The capability a step's commands are gated on.
39 ///
40 /// `Verify` depends on what is being released, which is the one place this is
41 /// not a property of the step alone. An app's verify is a Gatekeeper check on a
42 /// signed bundle, and the `gatekeeper` observe is granted implicitly to hosts
43 /// that can `sign` (`CapabilitySet::from_tokens`) precisely so that pairing
44 /// holds. A library's verify is a crate preflight: it runs `cargo` on the build
45 /// host and asks the registry a question. Gating that on Gatekeeper asks a Linux
46 /// host for a macOS code-signing capability it can never honestly hold, and the
47 /// only way to satisfy it would be to declare the capability falsely.
48 fn action_for(step: Step, kind: Kind) -> Action {
49 match step {
50 Step::Checkout | Step::Prebuild | Step::Build => Action::Build,
51 Step::Sign => Action::Sign,
52 Step::Notarize => Action::Notarize,
53 Step::Staple => Action::Staple,
54 Step::Package => Action::Package,
55 Step::Verify => match kind {
56 Kind::App => Action::Observe(ObserveKind::Custom("gatekeeper".into())),
57 // Running the build toolchain to inspect a crate or a service
58 // binary, which is what `build` means on a host. Neither has a
59 // bundle for Gatekeeper to have an opinion about.
60 Kind::Library | Kind::Service => Action::Build,
61 },
62 // Publish/Collect/Handoff run on the daemon, not through a host
63 // executor; this label only applies if a recipe runs a bare `sh` while
64 // one is open. `handoff` is the daemon's own post-recipe motion and no
65 // recipe should open it at all — naming it here costs nothing and beats
66 // a wildcard that would silently absorb the next step somebody adds.
67 Step::Publish | Step::Collect | Step::Handoff => Action::Package,
68 // The one step that dispatches to a host OUTSIDE the build topology.
69 // Every command a recipe runs while `deploy` is open — the install, the
70 // restart, the health assertion — carries this action, so it reaches the
71 // service host only through the deploy grant and reaches a build host
72 // not at all (no build host is granted `deploy`).
73 Step::Deploy => Action::Deploy,
74 }
75 }
76
77 /// The currently-open step within a recipe run: its DB row id, which step it
78 /// is, and the live-log sink that `sh`/`log` stream into.
79 struct StepState {
80 run_id: StepRunId,
81 step: Step,
82 log: Arc<AsyncMutex<LiveLog>>,
83 /// Set when something in the step recorded a hard failure the recipe did
84 /// not abort on (e.g. `verify_gatekeeper` rejected the artifact but the
85 /// recipe ignored the bool). Forces the step's recorded status to `Failed`
86 /// and bars `publish` (the step-success ledger).
87 failed: bool,
88 /// Wall-clock deadline for this step. A command that runs past it fails the
89 /// step (and unwinds the recipe) rather than wedging under the old
90 /// whole-build guillotine, which a legitimate 5-target fan-out plus notary
91 /// queueing could trip — mismarking every target failed while the blocking
92 /// recipe bodies kept signing.
93 deadline: std::time::Instant,
94 }
95
96 /// Per-step wall-clock budget: a generous ceiling that catches a wedged command
97 /// (a hung ssh, a stuck notary poll) without killing legitimately slow work.
98 /// The old design bounded the whole build at 2h; this bounds each step so one
99 /// slow step can't be blamed on another and a fan-out of slow-but-fine targets
100 /// isn't guillotined. `Config::step_timeout_secs` overrides these per-kind
101 /// defaults for every step; see [`RecipeCtx::step_budget`].
102 fn default_step_budget(step: Step) -> std::time::Duration {
103 use std::time::Duration;
104 let mins = match step {
105 Step::Checkout => 10,
106 // clippy + full test suite, cold, on a workspace.
107 Step::Prebuild => 45,
108 // cargo tauri build, cold, universal bundles.
109 Step::Build => 90,
110 Step::Sign => 15,
111 // Apple's notary queue + this step's bounded retries.
112 Step::Notarize => 60,
113 Step::Staple => 10,
114 Step::Package => 30,
115 Step::Verify => 10,
116 // rsync of multi-GiB artifacts off the build host.
117 Step::Collect => 30,
118 Step::Publish => 20,
119 // A binary push, an install, a unit restart, and a health poll. Minutes
120 // of work; the ceiling is for a wedged transport, not slow work.
121 Step::Deploy => 15,
122 // Unused by any recipe — the daemon runs the handoff itself, outside a
123 // step's clock — and matched to `collect`, since it moves the same
124 // bytes the same way and would wedge for the same reasons.
125 Step::Handoff => 30,
126 };
127 Duration::from_secs(mins * 60)
128 }
129
130 /// Where a service's binary is staged on the host that will run it, before the
131 /// privileged installer moves it into place.
132 ///
133 /// A fixed, unguessable-by-accident path rather than a recipe-chosen one,
134 /// because the installer refuses any source outside it. That refusal is the
135 /// only thing standing between the NOPASSWD sudo grant and `install`-as-root to
136 /// an arbitrary path, so both ends have to name the same constant. `/var/tmp`
137 /// rather than `/tmp` so a staged binary survives a `PrivateTmp` unit and a
138 /// systemd tmpfiles sweep between staging and install.
139 pub const DEPLOY_STAGING_ROOT: &str = "/var/tmp/bento-deploy";
140
141 /// Everything a recipe's host functions need, shared (Arc) into each closure.
142 pub struct RecipeCtx {
143 pub app: AppId,
144 pub version: Version,
145 pub target: Target,
146 /// Name of the host this target builds on (resolved from the topology by the
147 /// runner). Recipes read it via `build_host()` so one per-platform recipe can
148 /// dispatch to the right host across arches (linux x86_64 -> fw13, aarch64 ->
149 /// astra) without hard-coding a host name.
150 pub build_host: String,
151 /// The build host's SSH destination (topology `ssh`), as opposed to its
152 /// name. Deploy compares it against the service host's to tell "build and
153 /// run on the same box" from "two hosts that need a transfer" — a question
154 /// the host NAMES cannot answer, since a build host and a deploy
155 /// destination are declared in different files and need not agree on one.
156 pub build_host_ssh: String,
157 /// This release's git tag, rendered from the app's `tag_format`. Held here
158 /// rather than derived from the version because a repo holding several
159 /// products spells it per product (`pom-v0.4.1`), and the recipe, the
160 /// preflight barrier and the failure message all have to agree on it.
161 pub tag: String,
162 /// The app's default checkout path (topology `repo`, `~`-prefixed). Read it
163 /// through [`RecipeCtx::repo_for`] for anything that runs on a build host;
164 /// this field alone is the daemon-local answer.
165 pub repo: String,
166 /// Per-host checkout overrides (topology `repo_by_host`). Empty for every app
167 /// that has not declared one, which is all of them but the Windows-shipping
168 /// ones.
169 pub repo_by_host: HashMap<String, String>,
170 /// Cargo features this app's release builds enable (topology `features`).
171 /// Recipes read it via `feature_flags()`.
172 pub features: Vec<String>,
173 /// App or library. Decides which capability a `verify` step is gated on;
174 /// see [`action_for`].
175 pub kind: Kind,
176 pub target_run_id: i64,
177 /// Capability-scoped executor per build host. Recipe commands dispatch
178 /// through these — the transport (local / ssh / in-session agent) and the
179 /// capability gate are the executor's, not the engine's.
180 pub execs: Arc<ExecutorMap>,
181 /// Sync transport per build host, used only by `collect` to pull artifacts
182 /// back. Never the agent, even for an agent host — see `state::build_sync`.
183 /// Not an execution path.
184 pub syncs: Arc<ExecutorMap>,
185 /// Where this target installs, for a `kind = "service"` app. `None` for an
186 /// app or a library, which makes every deploy host function fail with that
187 /// as the reason rather than with a missing-host error.
188 ///
189 /// The runner resolves it from the app manifest's `[[deploy]]` table and
190 /// registers its executor into `execs` under the destination's host string,
191 /// so `sh_ok(deploy_host(), ...)` reaches the service host through the same
192 /// capability gate as everything else.
193 pub deploy: Option<DeployTarget>,
194 pub pool: SqlitePool,
195 pub events: EventTx,
196 pub cfg: Arc<Config>,
197 pub ota: Arc<OtaRegistry>,
198 pub rt: Handle,
199 current: Mutex<Option<StepState>>,
200 /// Gatekeeper verdict recorded by `verify_gatekeeper`: `None` = never run,
201 /// `Some(false)` = ran and rejected, `Some(true)` = accepted. `publish`
202 /// requires `Some(true)` for a macOS/iOS artifact (the proof it is signed +
203 /// notarized).
204 gatekeeper_ok: Mutex<Option<bool>>,
205 /// Steps finalized as `Failed` during this run. A non-empty ledger bars
206 /// `publish` — an artifact is never shipped after a step failed, even if the
207 /// recipe ignored the failure and ran on.
208 failed_steps: Mutex<Vec<Step>>,
209 /// Set when a newer build supersedes this run. Checked at step boundaries
210 /// and before publish so a superseded recipe stops promptly rather than
211 /// running to completion (the blocking Rhai body can't be `abort()`ed).
212 cancel: Arc<AtomicBool>,
213 /// The all-targets-green publish gate (topology `require_all_targets`).
214 /// `Some(declared)` ⇒ `publish` refuses unless every one of `declared` has a
215 /// successful latest run for this `(app, version)`. `None` ⇒ gate off, each
216 /// target publishes independently.
217 all_green_required: Option<Vec<Target>>,
218 /// sha256 of each artifact hashed at `collect`, keyed by file name. `publish`
219 /// reads it to record `releases.artifact_hash` for the bytes it ships, so the
220 /// hash is the one computed when the artifact landed rather than a re-read
221 /// that could see a different file. Absent ⇒ `publish` hashes on demand.
222 artifact_hashes: Mutex<HashMap<String, String>>,
223 }
224
225 impl RecipeCtx {
226 /// Versions of `name` already on crates.io. A network failure yields an
227 /// empty list: preflight then cannot claim a version is a duplicate, and
228 /// `cargo publish` still refuses one, so the check degrades to advisory
229 /// rather than blocking a release on registry availability.
230 fn published_versions(name: &str) -> Vec<String> {
231 let url = format!("https://crates.io/api/v1/crates/{name}");
232 let Ok(out) = std::process::Command::new("curl")
233 .args([
234 "-sS",
235 "--max-time",
236 "15",
237 "-H",
238 "User-Agent: bento-preflight",
239 &url,
240 ])
241 .output()
242 else {
243 return Vec::new();
244 };
245 let Ok(v) = serde_json::from_slice::<serde_json::Value>(&out.stdout) else {
246 return Vec::new();
247 };
248 v.get("versions")
249 .and_then(|x| x.as_array())
250 .map(|a| {
251 a.iter()
252 .filter_map(|x| x.get("num").and_then(|n| n.as_str()).map(str::to_string))
253 .collect()
254 })
255 .unwrap_or_default()
256 }
257
258 #[allow(clippy::too_many_arguments)]
259 pub fn new(
260 app: AppId,
261 version: Version,
262 target: Target,
263 build_host: String,
264 build_host_ssh: String,
265 tag: String,
266 repo: String,
267 features: Vec<String>,
268 kind: Kind,
269 target_run_id: i64,
270 execs: Arc<ExecutorMap>,
271 syncs: Arc<ExecutorMap>,
272 deploy: Option<DeployTarget>,
273 pool: SqlitePool,
274 events: EventTx,
275 cfg: Arc<Config>,
276 ota: Arc<OtaRegistry>,
277 rt: Handle,
278 cancel: Arc<AtomicBool>,
279 all_green_required: Option<Vec<Target>>,
280 ) -> Self {
281 Self {
282 app,
283 version,
284 target,
285 build_host,
286 build_host_ssh,
287 tag,
288 repo,
289 repo_by_host: HashMap::new(),
290 features,
291 kind,
292 target_run_id,
293 execs,
294 syncs,
295 deploy,
296 pool,
297 events,
298 cfg,
299 ota,
300 rt,
301 current: Mutex::new(None),
302 gatekeeper_ok: Mutex::new(None),
303 failed_steps: Mutex::new(Vec::new()),
304 cancel,
305 all_green_required,
306 artifact_hashes: Mutex::new(HashMap::new()),
307 }
308 }
309
310 /// Declare the app's per-host checkout overrides (topology `repo_by_host`).
311 ///
312 /// Separate from `new` because it is empty for every app that has not opted
313 /// in, and `new` already carries twenty arguments no test wants a
314 /// twenty-first of.
315 #[must_use]
316 pub fn with_repo_by_host(mut self, repo_by_host: HashMap<String, String>) -> Self {
317 self.repo_by_host = repo_by_host;
318 self
319 }
320
321 /// Where this app is checked out on `host` (topology `AppConfig::repo_for`).
322 ///
323 /// Every git command a recipe or the engine runs on a build host goes
324 /// through this. The bare `repo` field is the daemon-local path.
325 pub fn repo_for(&self, host: &str) -> &str {
326 self.repo_by_host
327 .get(host)
328 .map_or(self.repo.as_str(), String::as_str)
329 }
330
331 /// Whether a newer build has superseded this run.
332 fn is_cancelled(&self) -> bool {
333 self.cancel.load(Ordering::SeqCst)
334 }
335
336 fn now() -> String {
337 chrono::Utc::now().to_rfc3339()
338 }
339
340 /// `<logs_root>/<app>/<version>/<target-with-slash-as-dash>/<step>.<run_id>.log`.
341 ///
342 /// The run id is in the filename because the rest of the key is not unique:
343 /// re-running an app at a version it already built (a retry, or a rebuild of
344 /// an already-published release) reopens the same path, and the old file
345 /// appended to shows two runs' output with nothing marking the boundary. The
346 /// step ledger records a run id per step, so keying the file on it makes a
347 /// ledger row resolve to exactly one file and keeps the earlier run readable.
348 fn log_path(&self, step: Step, run_id: StepRunId) -> PathBuf {
349 self.log_dir()
350 .join(format!("{}.{}.log", step.as_str(), run_id.0))
351 }
352
353 /// `<logs_root>/<app>/<version>/<target-with-slash-as-dash>/`.
354 fn log_dir(&self) -> PathBuf {
355 let target_dir = self.target.to_string().replace('/', "-");
356 self.cfg
357 .logs_root
358 .join(self.app.as_str())
359 .join(self.version.to_string())
360 .join(target_dir)
361 }
362
363 /// Close the previous step (as `Ok`), open a new one: insert its DB row,
364 /// open a live log whose chunks broadcast `StepLogChunk`, emit `StepStart`.
365 fn begin_step(self: &Arc<Self>, step: Step) -> Result<()> {
366 anyhow::ensure!(
367 !self.is_cancelled(),
368 "build superseded by a newer request; aborting before `{}`",
369 step.as_str()
370 );
371 self.finish_step(Status::Ok)?;
372 let me = self.clone();
373 let started = Self::now();
374 let started_for_header = started.clone();
375 let run_id = self.rt.block_on(async move {
376 // The step row and the target's current_step pointer are one logical
377 // state — write them atomically so a failure can't leave a `running`
378 // step row while current_step still names the previous step.
379 let mut tx = me.pool.begin().await.context("begin step tx")?;
380 // log_ref names the run id, which only exists once the row does, so
381 // the path is written back inside the same transaction rather than
382 // guessed beforehand.
383 let id: i64 = sqlx::query_scalar(
384 "INSERT INTO step_runs (target_run_id, step, status, started_at)
385 VALUES (?, ?, 'running', ?) RETURNING id",
386 )
387 .bind(me.target_run_id)
388 .bind(step.as_str())
389 .bind(&started)
390 .fetch_one(&mut *tx)
391 .await
392 .context("insert step_run")?;
393 let log_ref = me
394 .log_path(step, StepRunId(id))
395 .to_string_lossy()
396 .into_owned();
397 sqlx::query("UPDATE step_runs SET log_ref = ? WHERE id = ?")
398 .bind(&log_ref)
399 .bind(id)
400 .execute(&mut *tx)
401 .await
402 .context("set step_run log_ref")?;
403 sqlx::query("UPDATE target_runs SET current_step = ? WHERE id = ?")
404 .bind(step.as_str())
405 .bind(me.target_run_id)
406 .execute(&mut *tx)
407 .await
408 .context("update current_step")?;
409 tx.commit().await.context("commit step tx")?;
410 anyhow::Ok(StepRunId(id))
411 })?;
412
413 // Live log: each chunk fans out as a StepLogChunk event keyed by run_id.
414 let events = self.events.clone();
415 let cb_run_id = run_id;
416 let mut log = self.rt.block_on(LiveLog::open(
417 self.log_path(step, run_id),
418 Box::new(move |seq, text| {
419 events::emit(
420 &events,
421 Event::StepLogChunk {
422 run_id: cb_run_id,
423 seq,
424 text: text.to_string(),
425 },
426 );
427 }),
428 ));
429
430 events::emit(
431 &self.events,
432 Event::StepStart {
433 run_id,
434 app: self.app.clone(),
435 version: self.version.clone(),
436 target: self.target,
437 step,
438 },
439 );
440
441 // A log that names its own run: reading one tells you which ledger row
442 // it belongs to without going back to the DB, and a file that somehow
443 // does get appended to still shows where the second run began. Written
444 // after `StepStart` so its chunk event cannot precede the step it
445 // belongs to.
446 let header = format!(
447 "=== bento {app} {version} {target} step={step} run_id={run_id} started={started_for_header} ===\n",
448 app = self.app.as_str(),
449 version = self.version,
450 target = self.target,
451 step = step.as_str(),
452 );
453 self.rt.block_on(async {
454 use ops_core::remote::LogSink as _;
455 log.write_chunk(header.as_bytes()).await;
456 });
457
458 *self.current.lock().unwrap() = Some(StepState {
459 run_id,
460 step,
461 log: Arc::new(AsyncMutex::new(log)),
462 failed: false,
463 deadline: std::time::Instant::now() + self.step_budget(step),
464 });
465 Ok(())
466 }
467
468 /// This build's budget for `step`: the `Config` override if set, else the
469 /// per-kind default.
470 fn step_budget(&self, step: Step) -> std::time::Duration {
471 self.cfg
472 .step_timeout_secs
473 .map_or_else(|| default_step_budget(step), std::time::Duration::from_secs)
474 }
475
476 /// The current step's wall-clock deadline (or a default if no step is open,
477 /// which only happens before the first `step()` — commands then run under an
478 /// implicit `Build` step opened by `ensure_step`).
479 fn step_deadline(&self) -> std::time::Instant {
480 self.current.lock().unwrap().as_ref().map_or_else(
481 || std::time::Instant::now() + self.step_budget(Step::Build),
482 |s| s.deadline,
483 )
484 }
485
486 /// Drive `fut` on the runtime, but stop early on two conditions the recipe
487 /// bodies otherwise cannot observe (they run synchronously on a blocking
488 /// thread): the current step's deadline, and supersession by a newer build.
489 /// Either turns into an error that fails the step and unwinds the recipe, so
490 /// a wedged command no longer runs unbounded and a superseded build stops
491 /// mid-step instead of only at the next step boundary.
492 fn run_bounded<F, T>(&self, what: &str, fut: F) -> Result<T>
493 where
494 F: std::future::Future<Output = Result<T>>,
495 {
496 let deadline = self.step_deadline();
497 let cancel = self.cancel.clone();
498 self.rt.block_on(async move {
499 tokio::pin!(fut);
500 let watch = async {
501 // Poll the cooperative cancel flag; the finalizer and a
502 // superseding build both set it. Cheap next to a build step.
503 while !cancel.load(Ordering::SeqCst) {
504 tokio::time::sleep(std::time::Duration::from_millis(250)).await;
505 }
506 };
507 tokio::select! {
508 r = &mut fut => r,
509 () = tokio::time::sleep_until(deadline.into()) => {
510 Err(anyhow::anyhow!("`{what}` exceeded its per-step deadline"))
511 }
512 () = watch => {
513 Err(anyhow::anyhow!("build superseded by a newer request; aborting `{what}`"))
514 }
515 }
516 })
517 }
518
519 /// Flag the currently-open step as failed (no-op if none is open). Forces
520 /// its recorded status to `Failed` at `finish_step` and adds it to the
521 /// publish-barring ledger, even though the recipe kept running.
522 fn fail_current_step(&self) {
523 if let Some(st) = self.current.lock().unwrap().as_mut() {
524 st.failed = true;
525 }
526 }
527
528 /// Finalize the open step (if any): close its log, stamp the DB row, emit
529 /// `StepDone`. Idempotent when no step is open. A step flagged via
530 /// [`fail_current_step`] is recorded `Failed` regardless of the requested
531 /// status, and added to the ledger `publish` consults.
532 pub fn finish_step(self: &Arc<Self>, status: Status) -> Result<()> {
533 let st = self.current.lock().unwrap().take();
534 let Some(st) = st else { return Ok(()) };
535 let status = if st.failed { Status::Failed } else { status };
536 if status == Status::Failed {
537 self.failed_steps.lock().unwrap().push(st.step);
538 }
539 let me = self.clone();
540 self.rt.block_on(async move {
541 // Drop all log refs so the sink can be owned + flushed.
542 if let Ok(m) = Arc::try_unwrap(st.log) {
543 m.into_inner().close().await;
544 }
545 if let Err(e) = sqlx::query(
546 "UPDATE step_runs SET status = ?, finished_at = ? WHERE id = ?",
547 )
548 .bind(status.as_str())
549 .bind(Self::now())
550 .bind(st.run_id.0)
551 .execute(&me.pool)
552 .await
553 {
554 tracing::error!(step = st.step.as_str(), error = %e, "could not stamp step_run status");
555 }
556 });
557 events::emit(
558 &self.events,
559 Event::StepDone {
560 run_id: st.run_id,
561 app: self.app.clone(),
562 target: self.target,
563 step: st.step,
564 status,
565 },
566 );
567 Ok(())
568 }
569
570 /// Ensure a step is open; default to `Build` if a recipe runs a command
571 /// before declaring one.
572 fn ensure_step(self: &Arc<Self>) -> Result<Arc<AsyncMutex<LiveLog>>> {
573 if self.current.lock().unwrap().is_none() {
574 self.begin_step(Step::Build)?;
575 }
576 Ok(self.current.lock().unwrap().as_ref().unwrap().log.clone())
577 }
578
579 /// The step currently open, or `Build` as a default for failure
580 /// attribution before any step was declared.
581 pub fn current_step(&self) -> Step {
582 self.current
583 .lock()
584 .unwrap()
585 .as_ref()
586 .map_or(Step::Build, |s| s.step)
587 }
588
589 /// The capability-scoped executor for `name`, or an error if the host isn't
590 /// in the topology.
591 fn exec(&self, name: &str) -> Result<Arc<dyn ops_exec::Executor>> {
592 self.execs
593 .get(name)
594 .cloned()
595 .ok_or_else(|| anyhow::anyhow!("unknown build host `{name}` (not in topology)"))
596 }
597
598 /// The ssh string for `name` (for `collect`'s remote scp source).
599 /// The transport that moves artifacts off `name`. Distinct from
600 /// [`RecipeCtx::exec_for`]'s executor: an agent host signs over `AgentRpc`
601 /// but is collected from over ssh (`state::build_sync`).
602 fn host_sync(&self, name: &str) -> Result<Arc<dyn Executor>> {
603 self.syncs
604 .get(name)
605 .cloned()
606 .ok_or_else(|| anyhow::anyhow!("unknown build host `{name}` (not in topology)"))
607 }
608
609 /// Run `cmd` on `host` through its capability-scoped executor, streaming into
610 /// the current step's log. The command's [`Action`] is derived from the open
611 /// step (see [`action_for`]) and gated at the transport before dispatch — so a
612 /// `build` step on a host without the `build` grant is denied, and the macOS
613 /// sign steps ride the in-session `AgentRpc` transport automatically. Returns
614 /// exit code + a tail of stdout for the recipe to branch on.
615 fn run(self: &Arc<Self>, host: &str, cmd: &str) -> Result<(i32, String)> {
616 // The service host is addressed as a service host whatever step is open.
617 // Deriving the action from the step is right for a build host, where the
618 // step IS the work; on a service host it would ask for `build` during a
619 // `verify` and be denied for a reason unrelated to what was attempted.
620 let action = match &self.deploy {
621 Some(d) if d.host == host => Action::Deploy,
622 _ => action_for(self.current_step(), self.kind),
623 };
624 self.run_as(host, cmd, action)
625 }
626
627 /// `run`, with the [`Action`] stated rather than resolved. Used where the
628 /// caller already knows which plane it is on.
629 fn run_as(self: &Arc<Self>, host: &str, cmd: &str, action: Action) -> Result<(i32, String)> {
630 let sink = self.ensure_step()?;
631 let exec = self.exec(host)?;
632 let cur = self.current_step();
633 let step = OpStep::shell(action, cmd.to_string());
634 // Echo the command before running it. Without this a log says what
635 // happened but not what was asked, and a gate that prints nothing when
636 // it passes (`cargo fmt --all --check`) is indistinguishable from a gate
637 // that never ran.
638 let echo = format!("$ [{host}] {cmd}\n");
639 // Bounded by the step's deadline and interruptible on supersession, so a
640 // hung command fails its step instead of running unbounded, and a
641 // superseded build stops mid-step rather than only at the next boundary.
642 let label = format!("{cur} command on `{host}`");
643 let out = self.run_bounded(&label, async move {
644 use ops_core::remote::LogSink as _;
645 let mut guard = sink.lock().await;
646 guard.write_chunk(echo.as_bytes()).await;
647 exec.run_streaming(&step, &mut *guard).await
648 })?;
649 let code = out.status.code().unwrap_or(-1);
650 let stdout = String::from_utf8_lossy(&out.stdout);
651 let tail: String = stdout
652 .chars()
653 .rev()
654 .take(2000)
655 .collect::<Vec<_>>()
656 .into_iter()
657 .rev()
658 .collect();
659 Ok((code, tail))
660 }
661
662 /// Pin `host` to the release tag `v<version>` and return the commit it now
663 /// has checked out. Fetch + checkout stream into the current step's log;
664 /// the sha comes from a separate `rev-parse` so its stdout is only the sha.
665 fn checkout_sha(self: &Arc<Self>, host: &str) -> Result<String> {
666 // Every command below runs ON `host`, so the path is that host's, not the
667 // daemon's. Windows is why: its checkout is at `C:/Users/me/Code/...`.
668 let repo = self.repo_for(host).to_string();
669 // A failing mirror is not a failing release: fetch is advisory, and only
670 // the checkout decides. Its output still streams into the step log, so an
671 // unreachable remote stays visible without being fatal.
672 let _ = self.run(host, &git_fetch_cmd(&repo))?;
673 let (code, _) = self.run(host, &git_checkout_tag_cmd(&repo, &self.tag))?;
674 if code != 0 {
675 let (probe, _) = self.run(host, &git_tag_exists_cmd(&repo, &self.tag))?;
676 // Ask the whole repository what is dirty, not just this app's
677 // directory: the checkout that failed was repo-wide, so the file
678 // holding it up need not be one this app would have compiled.
679 let (_, status) = self.run(host, &git_repo_dirty_cmd(&repo))?;
680 let (_, prefix) = self.run(host, &git_repo_prefix_cmd(&repo))?;
681 let blocking = dirty_paths_blocking_checkout(&status, &prefix);
682 anyhow::bail!(
683 "checkout of {} failed on `{host}`: {}",
684 self.tag,
685 checkout_failure_reason(&self.tag, probe == 0, blocking.as_deref())
686 );
687 }
688 let (code, tail) = self.run(host, &git_rev_parse_cmd(&repo))?;
689 anyhow::ensure!(code == 0, "rev-parse failed on `{host}`");
690 Ok(tail.trim().to_string())
691 }
692
693 /// Every artifact this run collected, `file name -> sha256`.
694 ///
695 /// Already computed at `collect`, which is the only moment the bytes are
696 /// known to be the ones that landed.
697 pub fn artifact_hashes(&self) -> HashMap<String, String> {
698 self.artifact_hashes.lock().unwrap().clone()
699 }
700
701 /// Resolve `glob` on `host` to the single artifact it names. The `for` loop
702 /// lists each existing match on its own line (and prints nothing — rather
703 /// than a literal unexpanded pattern — when the glob matches no file), so
704 /// the count is unambiguous. `required` controls whether zero matches is an
705 /// error; more than one always is. See `resolve_artifact_match`.
706 fn resolve_artifact(
707 self: &Arc<Self>,
708 host: &str,
709 glob: &str,
710 required: bool,
711 ) -> Result<String> {
712 ensure_glob_safe(glob)?;
713 // `[ -e ]` guards against a non-matching glob surviving as its literal
714 // self, and lists one path per line for the count.
715 let cmd = format!("for __f in {glob}; do [ -e \"$__f\" ] && printf '%s\\n' \"$__f\"; done");
716 let (code, tail) = self.run(host, &cmd)?;
717 anyhow::ensure!(
718 code == 0,
719 "resolving artifact glob `{glob}` on `{host}` exited {code}"
720 );
721 resolve_artifact_match(&tail, glob, required)
722 }
723 }
724
725 // ----- error bridging: anyhow -> Rhai runtime error -----
726
727 // Rhai host functions return `Result<_, Box<EvalAltResult>>` by convention, so
728 // this bridge must yield the boxed form to be usable with `.map_err(rhai_err)`.
729 #[allow(
730 clippy::unnecessary_box_returns,
731 reason = "rhai's error type is used boxed throughout its host-function API"
732 )]
733 fn rhai_err(e: impl std::fmt::Display) -> Box<EvalAltResult> {
734 Box::new(EvalAltResult::ErrorRuntime(
735 e.to_string().into(),
736 rhai::Position::NONE,
737 ))
738 }
739
740 /// A crate's publish-relevant metadata, read from `cargo metadata`.
741 #[derive(Debug, Clone)]
742 pub struct CrateMeta {
743 pub name: String,
744 pub version: String,
745 pub repository: Option<String>,
746 pub description: Option<String>,
747 pub licensed: bool,
748 }
749
750 /// Parse the fields that matter for publishing out of `cargo metadata` JSON.
751 pub fn crate_meta_from_json(raw: &str) -> Result<CrateMeta> {
752 let v: serde_json::Value = serde_json::from_str(raw).context("parsing cargo metadata")?;
753 let p = v
754 .get("packages")
755 .and_then(|p| p.as_array())
756 .and_then(|a| a.first())
757 .context("cargo metadata reported no package")?;
758 let str_field = |k: &str| {
759 p.get(k)
760 .and_then(|x| x.as_str())
761 .filter(|s| !s.is_empty())
762 .map(str::to_string)
763 };
764 Ok(CrateMeta {
765 name: str_field("name").context("package has no name")?,
766 version: str_field("version").context("package has no version")?,
767 repository: str_field("repository"),
768 description: str_field("description"),
769 licensed: str_field("license").is_some() || str_field("license_file").is_some(),
770 })
771 }
772
773 /// Everything wrong with a crate's metadata, as messages. Empty means publishable.
774 ///
775 /// Checks only what crates.io records permanently. A published version cannot
776 /// be edited, only yanked, and yanking does not correct a wrong URL — so these
777 /// are the last moment any of it can be fixed.
778 pub fn crate_publish_problems(
779 meta: &CrateMeta,
780 repo_clonable: bool,
781 published: &[String],
782 credentials_present: bool,
783 ) -> Vec<String> {
784 let mut out = Vec::new();
785 if !credentials_present {
786 out.push(
787 "no crates.io credentials on the publishing host: `cargo login` there first. \
788 Checked now rather than at the upload, so this fails in seconds instead of \
789 after a full build and verify."
790 .to_string(),
791 );
792 }
793 match &meta.repository {
794 None => out.push(
795 "no `repository` field: the crates.io page will show no source link, permanently"
796 .to_string(),
797 ),
798 Some(url) if !repo_clonable => out.push(format!(
799 "`repository` is not publicly clonable: {url} \
800 (wrong URL, or the repo is private)"
801 )),
802 Some(_) => {}
803 }
804 if meta.description.is_none() {
805 out.push("no `description`: crates.io requires one".to_string());
806 }
807 if !meta.licensed {
808 out.push("no `license` or `license-file`".to_string());
809 }
810 if published.iter().any(|v| v == &meta.version) {
811 out.push(format!(
812 "version {} is already published; bump it",
813 meta.version
814 ));
815 }
816 out
817 }
818
819 /// Read the app's version from its checkout on the daemon host. With
820 /// `version_path` set (topology `version_path`), read exactly that file — a
821 /// `.json` as a Tauri config, anything else as a `Cargo.toml`. Unset (the Tauri
822 /// default), try `src-tauri/tauri.conf.json` then the root `Cargo.toml`. Used by
823 /// the runner's default-version path.
824 pub fn version_from_repo(repo: &str, version_path: Option<&str>) -> Result<Version> {
825 let root = expand_tilde(repo);
826 if let Some(vp) = version_path {
827 let path = root.join(vp);
828 let raw = std::fs::read_to_string(&path)
829 .with_context(|| format!("reading version file {}", path.display()))?;
830 let ver = if std::path::Path::new(vp)
831 .extension()
832 .is_some_and(|e| e.eq_ignore_ascii_case("json"))
833 {
834 version_from_tauri_json(&raw)?
835 } else {
836 version_from_cargo_toml(&raw)?
837 };
838 return Version::parse(&ver).map_err(|e| anyhow::anyhow!(e));
839 }
840 let tauri_conf = root.join("src-tauri").join("tauri.conf.json");
841 if tauri_conf.exists() {
842 let raw = std::fs::read_to_string(&tauri_conf)
843 .with_context(|| format!("reading {}", tauri_conf.display()))?;
844 return Version::parse(&version_from_tauri_json(&raw)?).map_err(|e| anyhow::anyhow!(e));
845 }
846 let cargo_toml = root.join("Cargo.toml");
847 let raw = std::fs::read_to_string(&cargo_toml).with_context(|| {
848 format!(
849 "reading {} (no tauri.conf.json either)",
850 cargo_toml.display()
851 )
852 })?;
853 Version::parse(&version_from_cargo_toml(&raw)?).map_err(|e| anyhow::anyhow!(e))
854 }
855
856 /// Extract `version` from raw `tauri.conf.json` text.
857 fn version_from_tauri_json(raw: &str) -> Result<String> {
858 let v: serde_json::Value = serde_json::from_str(raw).context("parsing tauri.conf.json")?;
859 v.get("version")
860 .and_then(|x| x.as_str())
861 .map(str::to_owned)
862 .context("no `version` in tauri.conf.json")
863 }
864
865 /// Extract the version from raw `Cargo.toml` text — `[package].version` (a leaf
866 /// crate) or `[workspace.package].version` (a workspace that sets it).
867 fn version_from_cargo_toml(raw: &str) -> Result<String> {
868 let doc: toml::Value = toml::from_str(raw).context("parsing Cargo.toml")?;
869 doc.get("package")
870 .and_then(|p| p.get("version"))
871 .or_else(|| {
872 doc.get("workspace")
873 .and_then(|w| w.get("package"))
874 .and_then(|p| p.get("version"))
875 })
876 .and_then(|v| v.as_str())
877 .map(str::to_owned)
878 .context("no `[package].version` or `[workspace.package].version` in Cargo.toml")
879 }
880
881 /// Cross-check every version source in a repo and confirm they all agree with
882 /// the version being built, before a single host pulls or compiles.
883 ///
884 /// `version_from_repo` reads exactly one file, so a `tauri.conf.json` at 0.5.0
885 /// and a root `Cargo.toml` still at 0.4.0 build happily and file artifacts under
886 /// whichever the runner happened to read. This reads every source present —
887 /// `version_path` (when set), `src-tauri/tauri.conf.json`, and the root
888 /// `Cargo.toml` — and fails loudly when any disagree, naming each file and its
889 /// version. A source that is absent is skipped (a library crate with only a
890 /// `Cargo.toml` has nothing to disagree with); the check never invents drift.
891 ///
892 /// Scope: the JSON/TOML sources bentod itself reads. The iOS `gen/apple/project.yml`
893 /// path (rewritten by a build-time `sed`) is out of scope here — it is asserted at
894 /// its own build step — but the same drift class motivated this guard.
895 pub fn check_version_consistency(
896 repo: &str,
897 version_path: Option<&str>,
898 expected: &Version,
899 ) -> Result<()> {
900 let root = expand_tilde(repo);
901 // (human-readable source label, parsed version) for every source present.
902 let mut found: Vec<(String, Version)> = Vec::new();
903
904 let mut consider = |rel: &str, raw: &str, as_json: bool| -> Result<()> {
905 let ver = if as_json {
906 version_from_tauri_json(raw)
907 } else {
908 version_from_cargo_toml(raw)
909 }?;
910 let parsed = Version::parse(&ver).map_err(|e| anyhow::anyhow!(e))?;
911 found.push((rel.to_string(), parsed));
912 Ok(())
913 };
914
915 if let Some(vp) = version_path {
916 let path = root.join(vp);
917 let raw = std::fs::read_to_string(&path)
918 .with_context(|| format!("reading version file {}", path.display()))?;
919 let is_json = std::path::Path::new(vp)
920 .extension()
921 .is_some_and(|e| e.eq_ignore_ascii_case("json"));
922 consider(vp, &raw, is_json)?;
923 }
924 let tauri_conf = root.join("src-tauri").join("tauri.conf.json");
925 if version_path != Some("src-tauri/tauri.conf.json") && tauri_conf.exists() {
926 let raw = std::fs::read_to_string(&tauri_conf)
927 .with_context(|| format!("reading {}", tauri_conf.display()))?;
928 consider("src-tauri/tauri.conf.json", &raw, true)?;
929 }
930 let cargo_toml = root.join("Cargo.toml");
931 if version_path != Some("Cargo.toml") && cargo_toml.exists() {
932 // A Cargo.toml with neither `[package].version` nor
933 // `[workspace.package].version` (a pure virtual workspace) carries no
934 // version to check — skip it rather than fail.
935 if let Ok(raw) = std::fs::read_to_string(&cargo_toml)
936 && version_from_cargo_toml(&raw).is_ok()
937 {
938 consider("Cargo.toml", &raw, false)?;
939 }
940 }
941
942 let disagree: Vec<&(String, Version)> = found.iter().filter(|(_, v)| v != expected).collect();
943 anyhow::ensure!(
944 disagree.is_empty(),
945 "version drift in {repo}: building {expected} but {}",
946 disagree
947 .iter()
948 .map(|(src, v)| format!("{src} says {v}"))
949 .collect::<Vec<_>>()
950 .join(", ")
951 );
952 Ok(())
953 }
954
955 /// Every `X.Y.Z`-shaped version embedded in an artifact file name. Each maximal
956 /// run of digits-and-dots contributes its first three numeric fields:
957 /// `GoingsOn_0.5.0_aarch64.dmg` and `demo-9.9.9.bin` both yield one version (the
958 /// trailing `.bin`/`.dmg` dot is tolerated), while `latest.json` yields `[]` and
959 /// the `64` in `x86_64` is not three fields. Only the `major.minor.patch` core is
960 /// taken; a prerelease/build suffix is separated by `-`/`+` and not needed here.
961 fn versions_in_filename(name: &str) -> Vec<Version> {
962 name.split(|c: char| !(c.is_ascii_digit() || c == '.'))
963 .filter_map(|run| {
964 let f: Vec<&str> = run.split('.').filter(|s| !s.is_empty()).collect();
965 if f.len() >= 3 && f[..3].iter().all(|s| s.chars().all(|c| c.is_ascii_digit())) {
966 Version::parse(&format!("{}.{}.{}", f[0], f[1], f[2])).ok()
967 } else {
968 None
969 }
970 })
971 .collect()
972 }
973
974 /// Fail when a collected file's name embeds a version whose `major.minor.patch`
975 /// is not the one being built. This is the guard against a stale checked-in
976 /// artifact winning a glob: `ls -t <glob>` once let
977 /// `AudioFiles-0.4.0-x86_64.AppImage` ship against 0.5.0. A file whose name
978 /// carries no version (an updater `latest.json`, a `.sig`) is not asserted —
979 /// there is nothing to compare. Compared on the core so a prerelease build's
980 /// plain `X.Y.Z` in the filename still matches.
981 fn assert_artifact_version(name: &str, expected: &Version) -> Result<()> {
982 let versions = versions_in_filename(name);
983 anyhow::ensure!(
984 versions.is_empty() || versions.iter().any(|v| v.core() == expected.core()),
985 "collected artifact `{name}` carries version {} but the build is {expected}; \
986 a stale artifact was left in the output dir — clean it so only {expected} remains",
987 versions
988 .iter()
989 .map(ToString::to_string)
990 .collect::<Vec<_>>()
991 .join("/"),
992 );
993 Ok(())
994 }
995
996 /// sha256 of a file, lowercase hex. Streams in 64 KiB chunks so a multi-GiB
997 /// bundle never lands in memory whole.
998 fn sha256_file(path: &Path) -> Result<String> {
999 let mut file =
1000 std::fs::File::open(path).with_context(|| format!("hashing {}", path.display()))?;
1001 let mut hasher = Sha256::new();
1002 std::io::copy(&mut file, &mut hasher)
1003 .with_context(|| format!("reading {} to hash", path.display()))?;
1004 Ok(hex_lower(&hasher.finalize()))
1005 }
1006
1007 /// Every regular file under `root`, as `(path relative to root, absolute path)`,
1008 /// sorted by the relative path.
1009 ///
1010 /// **This walk has to match `bundle::digest_dir` in sando, file for file.** That
1011 /// function re-hashes an incoming bundle and refuses it when the bytes disagree
1012 /// with the manifest they arrived with, so a producer that walks differently
1013 /// produces a manifest the consumer will reject for an artifact nothing is wrong
1014 /// with. Three properties carry that agreement, and none is incidental:
1015 ///
1016 /// - **Recursive.** A bundle may carry a directory (migrations, resources), and
1017 /// a top-level-only listing would omit its contents from the manifest while
1018 /// the verifier hashed them.
1019 /// - **Symlinks are not followed, and not recorded.** Following one would let
1020 /// content from outside the bundle into its identity; recording the link
1021 /// itself would name a file the verifier does not hash.
1022 /// - **Relative paths, `/`-separated, sorted.** Readdir order is not guaranteed,
1023 /// so an unsorted manifest would differ run to run on one machine, never mind
1024 /// between two.
1025 fn collected_files(root: &Path) -> std::io::Result<Vec<(String, PathBuf)>> {
1026 fn walk(dir: &Path, root: &Path, out: &mut Vec<(String, PathBuf)>) -> std::io::Result<()> {
1027 for entry in std::fs::read_dir(dir)? {
1028 let entry = entry?;
1029 let ft = entry.file_type()?;
1030 let path = entry.path();
1031 if ft.is_dir() {
1032 walk(&path, root, out)?;
1033 } else if ft.is_file() {
1034 let rel = path
1035 .strip_prefix(root)
1036 .unwrap_or(&path)
1037 .components()
1038 .map(|c| c.as_os_str().to_string_lossy())
1039 .collect::<Vec<_>>()
1040 .join("/");
1041 out.push((rel, path));
1042 }
1043 // Symlinks and other special files are intentionally ignored,
1044 // matching the verifier.
1045 }
1046 Ok(())
1047 }
1048 let mut out = Vec::new();
1049 walk(root, root, &mut out)?;
1050 out.sort_by(|a, b| a.0.cmp(&b.0));
1051 Ok(out)
1052 }
1053
1054 /// Lowercase-hex encode without pulling in a hex crate.
1055 fn hex_lower(bytes: &[u8]) -> String {
1056 use std::fmt::Write as _;
1057 let mut s = String::with_capacity(bytes.len() * 2);
1058 for b in bytes {
1059 let _ = write!(s, "{b:02x}");
1060 }
1061 s
1062 }
1063
1064 /// Refresh every remote's refs and tags, so the tag a release names is present
1065 /// locally however it was pushed. No branch/upstream assumptions — a bare
1066 /// `git pull --ff-only` needs a tracking branch the release path shouldn't
1067 /// depend on.
1068 ///
1069 /// Best-effort on purpose. `fetch --all` exits non-zero if ANY remote fails, and
1070 /// the library repos carry three (`astra`, `mnw`, `srht`), so chaining this into
1071 /// the checkout with `&&` meant one unreachable mirror aborted the release and
1072 /// reported it as a missing tag. The checkout below is the step allowed to fail;
1073 /// this one only has to try. See [`git_checkout_tag_cmd`].
1074 ///
1075 /// `repo` is interpolated UNQUOTED so a leading `~` is expanded by the remote
1076 /// host's shell (the checkout path is trusted topology config, not user input),
1077 /// matching how the recipes `cd` into it.
1078 pub fn git_fetch_cmd(repo: &str) -> String {
1079 format!("git -C {repo} fetch --all --tags --prune")
1080 }
1081
1082 /// Pin the host's checkout to the release tag. Runs after [`git_fetch_cmd`], and
1083 /// is the operation whose exit code decides whether the release proceeds.
1084 pub fn git_checkout_tag_cmd(repo: &str, tag: &str) -> String {
1085 format!("git -C {repo} checkout \"{tag}\"")
1086 }
1087
1088 /// Does `tag` resolve to a commit in this checkout? Run only when the checkout
1089 /// has already failed, to say WHY: an absent tag is an untagged or unpushed
1090 /// release, while a tag that resolves fine means the checkout was refused for a
1091 /// local reason (a dirty tree, most often) and the operator needs to hear that
1092 /// instead.
1093 pub fn git_tag_exists_cmd(repo: &str, tag: &str) -> String {
1094 format!("git -C {repo} rev-parse -q --verify \"refs/tags/{tag}^{{commit}}\"")
1095 }
1096
1097 /// The operator-facing explanation for a failed tag checkout, given whether the
1098 /// tag turned out to exist locally and what [`dirty_paths_blocking_checkout`]
1099 /// found in the working tree.
1100 ///
1101 /// With the file list in hand there is nothing left to guess at, so the
1102 /// speculative "uncommitted changes?" is dropped in favour of naming them. It
1103 /// stays for the case where the repository is clean and the checkout failed for
1104 /// some other reason, because then a guess is all there is.
1105 pub fn checkout_failure_reason(tag: &str, tag_exists: bool, blocking: Option<&str>) -> String {
1106 match (tag_exists, blocking) {
1107 (true, Some(paths)) => format!(
1108 "tag {tag} exists but could not be checked out. `git checkout` acts on the whole \
1109 repository, and these tracked files have local changes:\n {paths}\nCommit, stash \
1110 or discard them before releasing."
1111 ),
1112 (true, None) => format!(
1113 "tag {tag} exists but could not be checked out \
1114 (uncommitted changes in the checkout?)"
1115 ),
1116 (false, _) => format!("tag {tag} does not exist there (is it created and pushed?)"),
1117 }
1118 }
1119
1120 /// Uncommitted changes to tracked files across the WHOLE repository, not just
1121 /// the app's own directory.
1122 ///
1123 /// The gate is [`git_dirty_cmd`] and stays app-scoped for the reason given
1124 /// there. This is diagnosis, run only once a checkout has already failed:
1125 /// `git checkout <tag>` acts on the whole repository, so the file that blocked
1126 /// it can sit outside the app entirely — at which point the app-scoped gate has
1127 /// already reported a clean tree and the operator has nothing to go on. That is
1128 /// what happened on pom's first hand-off release, where astra carried a
1129 /// locally-resolved `server/Cargo.lock` and pom's own tree was spotless.
1130 pub fn git_repo_dirty_cmd(repo: &str) -> String {
1131 format!("git -C {repo} status --porcelain --untracked-files=no")
1132 }
1133
1134 /// The app's path relative to the repository root — `pom/` inside MNW, empty for
1135 /// a repo holding one product. Porcelain status paths are repo-root relative,
1136 /// so this is what decides whether a blocking file is the app's own.
1137 pub fn git_repo_prefix_cmd(repo: &str) -> String {
1138 format!("git -C {repo} rev-parse --show-prefix")
1139 }
1140
1141 /// Render the tracked files whose local changes block a repo-wide checkout, one
1142 /// per line, marking the ones outside the app's own directory.
1143 ///
1144 /// `status` is [`git_repo_dirty_cmd`] output and `prefix` is
1145 /// [`git_repo_prefix_cmd`] output. `None` when the repository is clean: then the
1146 /// checkout failed for some other reason, and inventing a file to blame would be
1147 /// worse than saying nothing.
1148 pub fn dirty_paths_blocking_checkout(status: &str, prefix: &str) -> Option<String> {
1149 let prefix = prefix.trim();
1150 let lines: Vec<String> = status
1151 .lines()
1152 .filter_map(|l| {
1153 // `XY path`, or `XY old -> new` for a rename. The destination is the
1154 // path that exists in the working tree, so it is the one to name.
1155 let path = l.get(3..)?.trim();
1156 let path = path.rsplit(" -> ").next()?.trim();
1157 if path.is_empty() {
1158 return None;
1159 }
1160 if !prefix.is_empty() && !path.starts_with(prefix) {
1161 return Some(format!("{path} (outside {prefix}, not part of this app)"));
1162 }
1163 Some(path.to_string())
1164 })
1165 .collect();
1166 (!lines.is_empty()).then(|| lines.join("\n "))
1167 }
1168
1169 /// Uncommitted changes to TRACKED files, one `XY path` line each, empty when the
1170 /// tree is clean.
1171 ///
1172 /// `--untracked-files=no` on purpose: an untracked file is not built into the
1173 /// binary and a build host accumulates them (editor scratch, stray logs), so
1174 /// failing a release on one would be noise. A modified tracked file is the
1175 /// opposite — it is exactly what `cargo build` would pick up instead of the
1176 /// tagged content.
1177 ///
1178 /// Scoped to `repo` with `-- .` rather than asking about the whole repository,
1179 /// which matters only for the repos holding more than one product. `repo` for
1180 /// pom is `~/Code/MNW/pom` inside the MNW monorepo, and an edit in `server/` is
1181 /// not something pom's build can compile. Refusing pom's release for it would be
1182 /// a gate that fires on unrelated work, which is how a gate gets bypassed. For a
1183 /// single-product repo `repo` is the root and this is the whole tree, unchanged.
1184 pub fn git_dirty_cmd(repo: &str) -> String {
1185 format!("git -C {repo} status --porcelain --untracked-files=no -- .")
1186 }
1187
1188 /// The branch a host's checkout is on, empty (and non-zero) on a detached HEAD.
1189 /// Read BEFORE the release pins the tag, so the checkout can be put back
1190 /// afterwards — see [`git_restore_branch_cmd`].
1191 pub fn git_current_branch_cmd(repo: &str) -> String {
1192 format!("git -C {repo} symbolic-ref -q --short HEAD")
1193 }
1194
1195 /// Put a checkout back on the branch it was on before the release pinned it to
1196 /// the tag.
1197 ///
1198 /// The pin itself is correct and deliberate: a release must build the tagged
1199 /// commit, not the branch tip. What was missing is the other half. Leaving the
1200 /// tree detached is invisible — git does not warn, and commits made afterwards
1201 /// succeed normally while belonging to no branch. makeover shipped 2.3.0 from
1202 /// exactly that state on 2026-07-28: three commits, including the published one,
1203 /// existed only as a detached HEAD on one machine, on no branch and no remote.
1204 pub fn git_restore_branch_cmd(repo: &str, branch: &str) -> String {
1205 format!("git -C {repo} checkout \"{branch}\"")
1206 }
1207
1208 /// The command a host runs to report the commit it has checked out, for the
1209 /// release preflight barrier.
1210 pub fn git_rev_parse_cmd(repo: &str) -> String {
1211 format!("git -C {repo} rev-parse HEAD")
1212 }
1213
1214 /// Expand a leading `~/` to `$HOME`. Paths in the topology are written with `~`.
1215 pub fn expand_tilde(p: &str) -> PathBuf {
1216 if let Some(rest) = p.strip_prefix("~/")
1217 && let Ok(home) = std::env::var("HOME")
1218 {
1219 return Path::new(&home).join(rest);
1220 }
1221 PathBuf::from(p)
1222 }
1223
1224 /// Reject a glob that carries shell command metacharacters. Path and wildcard
1225 /// characters (`/ . * ? [ ] ~` etc.) are fine — the pattern reaches a login
1226 /// shell to be expanded — but a `;` or `$(...)` must not ride along and run.
1227 /// Not a privilege boundary (a recipe already runs arbitrary shell via `sh_ok`)
1228 /// but it keeps a malformed pattern from turning into a command. Shared by
1229 /// `collect` and `resolve_artifact`.
1230 fn ensure_glob_safe(glob: &str) -> Result<()> {
1231 anyhow::ensure!(
1232 !glob.chars().any(|c| matches!(
1233 c,
1234 ';' | '&' | '|' | '$' | '`' | '\'' | '"' | '\\' | ' ' | '\n' | '(' | ')' | '<' | '>'
1235 )),
1236 "glob `{glob}` contains shell metacharacters"
1237 );
1238 Ok(())
1239 }
1240
1241 /// Decide the single artifact a glob resolves to from a newline-separated
1242 /// listing of the paths that matched it.
1243 ///
1244 /// The recipes used to select an artifact with `ls -t <glob> | head -1` and
1245 /// guard only on an empty string, so a non-zero `ls` slipped past quietly and a
1246 /// stale newest-by-mtime file could win. This is the strict replacement: it
1247 /// demands exactly one match. Zero matches fail when `required` (return `""`
1248 /// when optional); more than one is always an error rather than an arbitrary
1249 /// newest-wins pick, because an ambiguous match means the build left stale
1250 /// artifacts behind and the wrong one could ship.
1251 fn resolve_artifact_match(listing: &str, glob: &str, required: bool) -> Result<String> {
1252 let matches: Vec<&str> = listing
1253 .lines()
1254 .map(str::trim)
1255 .filter(|l| !l.is_empty())
1256 .collect();
1257 match matches.as_slice() {
1258 [] if required => anyhow::bail!("no artifact matched glob `{glob}`"),
1259 [] => Ok(String::new()),
1260 [one] => Ok((*one).to_string()),
1261 many => anyhow::bail!(
1262 "glob `{glob}` is ambiguous: {} artifacts matched ({}). \
1263 The build left more than one behind; clean stale artifacts so exactly one remains.",
1264 many.len(),
1265 many.join(", ")
1266 ),
1267 }
1268 }
1269
1270 /// Build a Rhai engine with the host API bound to `ctx`. Sandboxed: recipes
1271 /// touch the outside world only through these functions.
1272 pub fn build_engine(ctx: &Arc<RecipeCtx>) -> Engine {
1273 let mut engine = Engine::new();
1274 // Defensive caps — recipes are first-party but bound the blast radius.
1275 engine.set_max_operations(5_000_000);
1276 engine.set_max_call_levels(64);
1277 engine.set_max_string_size(0);
1278
1279 // --- step(name) ---
1280 {
1281 let ctx = ctx.clone();
1282 engine.register_fn(
1283 "step",
1284 move |name: &str| -> Result<(), Box<EvalAltResult>> {
1285 let step: Step = name.parse().map_err(rhai_err)?;
1286 ctx.begin_step(step).map_err(rhai_err)
1287 },
1288 );
1289 }
1290
1291 // --- sh(host, cmd) -> #{ code, stdout_tail } ---
1292 //
1293 // The branch-on-exit-code primitive: the recipe OWNS the outcome. A non-zero
1294 // exit is returned, not raised, and does NOT fail the step or bar publish —
1295 // use this only when the recipe inspects `code` and decides. For a command
1296 // that must succeed (build/sign/etc.), use `sh_ok`, which fails the step (and
1297 // therefore bars publish via the failed-step ledger) on a non-zero exit.
1298 {
1299 let ctx = ctx.clone();
1300 engine.register_fn(
1301 "sh",
1302 move |host: &str, cmd: &str| -> Result<Map, Box<EvalAltResult>> {
1303 let (code, tail) = ctx.run(host, cmd).map_err(rhai_err)?;
1304 let mut m = Map::new();
1305 m.insert("code".into(), (code as i64).into());
1306 m.insert("stdout_tail".into(), tail.into());
1307 Ok(m)
1308 },
1309 );
1310 }
1311
1312 // --- sh_ok(host, cmd): run + assert exit 0 (the must-succeed primitive) ---
1313 //
1314 // A non-zero exit fails the current step (added to the publish-barring
1315 // ledger) and aborts the recipe, so an artifact is never shipped after a
1316 // must-succeed command failed.
1317 {
1318 let ctx = ctx.clone();
1319 engine.register_fn(
1320 "sh_ok",
1321 move |host: &str, cmd: &str| -> Result<(), Box<EvalAltResult>> {
1322 let (code, _) = ctx.run(host, cmd).map_err(rhai_err)?;
1323 if code != 0 {
1324 // Attribute the failure to the current step explicitly so the
1325 // ledger bars publish even if a future caller swallowed the error.
1326 ctx.fail_current_step();
1327 return Err(rhai_err(format!(
1328 "command on `{host}` exited {code}: {cmd}"
1329 )));
1330 }
1331 Ok(())
1332 },
1333 );
1334 }
1335
1336 // --- resolve_artifact(host, glob) -> path: the ONE artifact matching glob ---
1337 //
1338 // The artifact-selection primitive. Replaces `sh(host, "ls -t <glob> | head
1339 // -1").stdout_tail.trim()` guarded on an empty string, which let a non-zero
1340 // `ls` pass quietly and a stale newest-by-mtime file win. This resolves the
1341 // glob on the host and demands exactly one match: zero matches or more than
1342 // one both throw (an ambiguous match means the build left stale artifacts,
1343 // and silently picking the newest is how the wrong bytes ship). Use
1344 // `resolve_artifact_opt` for an artifact that may legitimately be absent.
1345 {
1346 let ctx = ctx.clone();
1347 engine.register_fn(
1348 "resolve_artifact",
1349 move |host: &str, glob: &str| -> Result<String, Box<EvalAltResult>> {
1350 ctx.resolve_artifact(host, glob, true).map_err(rhai_err)
1351 },
1352 );
1353 }
1354
1355 // --- resolve_artifact_opt(host, glob) -> path | "": zero-or-one match ---
1356 //
1357 // Same strict resolution as `resolve_artifact` but tolerates zero matches
1358 // (returns ""); more than one is still an error. For optional outputs like a
1359 // `.deb` or an updater bundle a recipe collects only when present.
1360 {
1361 let ctx = ctx.clone();
1362 engine.register_fn(
1363 "resolve_artifact_opt",
1364 move |host: &str, glob: &str| -> Result<String, Box<EvalAltResult>> {
1365 ctx.resolve_artifact(host, glob, false).map_err(rhai_err)
1366 },
1367 );
1368 }
1369
1370 // --- log(msg): operator-visible line into the current step's tail ---
1371 {
1372 let ctx = ctx.clone();
1373 engine.register_fn("log", move |msg: &str| -> Result<(), Box<EvalAltResult>> {
1374 let sink = ctx.ensure_step().map_err(rhai_err)?;
1375 let line = format!("[recipe] {msg}\n");
1376 ctx.rt.block_on(async {
1377 use ops_core::remote::LogSink;
1378 sink.lock().await.write_chunk(line.as_bytes()).await;
1379 });
1380 Ok(())
1381 });
1382 }
1383
1384 // --- version_of(app) -> string ---
1385 {
1386 let ctx = ctx.clone();
1387 engine.register_fn(
1388 "version_of",
1389 move |app: &str| -> Result<String, Box<EvalAltResult>> {
1390 // Only the current app is in scope; cross-app reads aren't needed.
1391 if app != ctx.app.as_str() {
1392 return Err(rhai_err(format!(
1393 "version_of: `{app}` is not the app being built"
1394 )));
1395 }
1396 Ok(ctx.version.to_string())
1397 },
1398 );
1399 }
1400
1401 // --- version() -> string: the version being built (no-arg form) ---
1402 {
1403 let ctx = ctx.clone();
1404 engine.register_fn("version", move || -> String { ctx.version.to_string() });
1405 }
1406
1407 // --- build_host() -> string: the host this target builds on ---
1408 {
1409 let ctx = ctx.clone();
1410 engine.register_fn("build_host", move || -> String { ctx.build_host.clone() });
1411 }
1412
1413 // --- repo() -> string: the app's checkout path on this target's build host
1414 // (`~`-prefixed on a unix host). Host-correct rather than one path per
1415 // app, so a recipe for a host whose checkout is elsewhere still calls
1416 // this instead of hard-coding the path — which is what kept the Windows
1417 // recipes off `checkout_sha`. ---
1418 {
1419 let ctx = ctx.clone();
1420 engine.register_fn("repo", move || -> String {
1421 ctx.repo_for(&ctx.build_host).to_string()
1422 });
1423 }
1424
1425 // --- checkout_sha(host) -> sha: pin this host to the release tag and report
1426 // its commit. Replaces a recipe's `git pull --ff-only`, which builds
1427 // whatever `main` is at pull time; the daemon also runs the same pin as
1428 // a cross-host preflight barrier before any target builds. ---
1429 {
1430 let ctx = ctx.clone();
1431 engine.register_fn(
1432 "checkout_sha",
1433 move |host: &str| -> Result<String, Box<EvalAltResult>> {
1434 ctx.checkout_sha(host).map_err(rhai_err)
1435 },
1436 );
1437 }
1438
1439 // --- crate_preflight() -> string: verify this crate is safe to publish,
1440 // or abort the run. Everything it checks is immutable once published:
1441 // crates.io versions can be yanked but never edited, so a wrong
1442 // repository URL is permanent. pter 0.1.0 shipped with a dead one. ---
1443 {
1444 let ctx = ctx.clone();
1445 engine.register_fn(
1446 "crate_preflight",
1447 move || -> Result<String, Box<EvalAltResult>> {
1448 // `repo`, not `repo_for(...)`: `cargo metadata` runs on the
1449 // daemon's own box, so this is the one checkout that is always
1450 // the local one. It is not a missed call site.
1451 let repo = expand_tilde(&ctx.repo);
1452
1453 let out = std::process::Command::new("cargo")
1454 .args(["metadata", "--no-deps", "--format-version", "1"])
1455 .current_dir(&repo)
1456 .output()
1457 .map_err(|e| format!("running cargo metadata in {}: {e}", repo.display()))?;
1458 if !out.status.success() {
1459 return Err(format!(
1460 "cargo metadata failed in {}: {}",
1461 repo.display(),
1462 String::from_utf8_lossy(&out.stderr).trim()
1463 )
1464 .into());
1465 }
1466 let meta = crate_meta_from_json(&String::from_utf8_lossy(&out.stdout))
1467 .map_err(|e| e.to_string())?;
1468
1469 // The real question is not whether a page renders but whether a
1470 // stranger with no credentials can fetch the source, so ask git.
1471 let clonable = meta.repository.as_ref().is_some_and(|url| {
1472 std::process::Command::new("git")
1473 .args(["ls-remote", url])
1474 .env("GIT_TERMINAL_PROMPT", "0")
1475 .output()
1476 .is_ok_and(|o| o.status.success())
1477 });
1478
1479 // Ask the publishing host whether cargo has credentials, rather
1480 // than moving the token anywhere. It stays in cargo's own 0600
1481 // store; a shell line carrying it would be visible in `ps`.
1482 // An exit code answers "are there credentials"; an Err answers
1483 // "the question could not be asked". Collapsing the second into
1484 // the first reported a capability denial as "no crates.io
1485 // credentials", which sent a real diagnosis three rounds the
1486 // wrong way. A check that cannot run is not a failed check.
1487 let creds =
1488 ctx.run(
1489 &ctx.build_host.clone(),
1490 "cargo login --help >/dev/null 2>&1 && \
1491 test -s \"${CARGO_HOME:-$HOME/.cargo}/credentials.toml\" \
1492 || test -s \"${CARGO_HOME:-$HOME/.cargo}/credentials\"",
1493 )
1494 .map_err(|e| {
1495 format!(
1496 "could not check crates.io credentials on `{}`: {e}",
1497 ctx.build_host
1498 )
1499 })?
1500 .0 == 0;
1501
1502 let published = RecipeCtx::published_versions(&meta.name);
1503 let problems = crate_publish_problems(&meta, clonable, &published, creds);
1504 if !problems.is_empty() {
1505 return Err(format!(
1506 "{} {} is not safe to publish:\n - {}",
1507 meta.name,
1508 meta.version,
1509 problems.join("\n - ")
1510 )
1511 .into());
1512 }
1513 Ok(format!("{} {} passed preflight", meta.name, meta.version))
1514 },
1515 );
1516 }
1517
1518 // --- feature_flags() -> string: `--features a,b`, or "" when the app
1519 // declares none. Returns the whole flag rather than a bare list so an
1520 // app with no features cannot produce a dangling `--features`. ---
1521 {
1522 let ctx = ctx.clone();
1523 engine.register_fn("feature_flags", move || -> String {
1524 if ctx.features.is_empty() {
1525 String::new()
1526 } else {
1527 format!("--features {}", ctx.features.join(","))
1528 }
1529 });
1530 }
1531
1532 // --- target() / platform() / arch(): the target axis, for one per-platform
1533 // recipe to branch on arch (bundle paths differ between x86_64/aarch64). ---
1534 {
1535 let ctx = ctx.clone();
1536 engine.register_fn("target", move || -> String { ctx.target.to_string() });
1537 }
1538 {
1539 let ctx = ctx.clone();
1540 engine.register_fn("platform", move || -> String {
1541 ctx.target.platform.as_str().to_string()
1542 });
1543 }
1544 {
1545 let ctx = ctx.clone();
1546 engine.register_fn("arch", move || -> String {
1547 ctx.target.arch.as_str().to_string()
1548 });
1549 }
1550
1551 // --- secret(key) -> string (file under secrets_root; never logged) ---
1552 {
1553 let ctx = ctx.clone();
1554 engine.register_fn("secret", move |key: &str| -> Result<String, Box<EvalAltResult>> {
1555 // Guard against traversal out of secrets_root. Require every path
1556 // component to be `Normal` (rejects `..`, `.`, absolute roots and
1557 // drive prefixes) and forbid backslashes (a literal filename char on
1558 // Linux, but a separator elsewhere) — the per-component strength of
1559 // Sando's `safe()`. A multi-segment key like `app/token` is still
1560 // allowed; `foo..bar` (a legit filename) is no longer falsely blocked.
1561 let safe = !key.is_empty()
1562 && !key.contains('\\')
1563 && std::path::Path::new(key)
1564 .components()
1565 .all(|c| matches!(c, std::path::Component::Normal(_)));
1566 if !safe {
1567 return Err(rhai_err(
1568 "secret key must be a relative path under secrets_root (no `..`, `.`, absolute paths, or backslashes)",
1569 ));
1570 }
1571 let path = ctx.cfg.secrets_root.join(key);
1572 std::fs::read_to_string(&path)
1573 .map(|s| s.trim_end().to_string())
1574 .map_err(|e| rhai_err(format!("secret `{key}`: {e}")))
1575 });
1576 }
1577
1578 // --- env(host, key) -> string ---
1579 {
1580 let ctx = ctx.clone();
1581 engine.register_fn(
1582 "env",
1583 move |host: &str, key: &str| -> Result<String, Box<EvalAltResult>> {
1584 // The key is interpolated into a `${...}` shell expansion, so it must
1585 // be a bare shell identifier — anything else (quotes, `}`, `$`, `;`)
1586 // could break out and run arbitrary commands on the host. Validate
1587 // before building the command; this is the one env read that can't
1588 // sh-quote its argument (a quoted var name doesn't expand).
1589 if key.is_empty()
1590 || !key
1591 .chars()
1592 .next()
1593 .is_some_and(|c| c == '_' || c.is_ascii_alphabetic())
1594 || !key.chars().all(|c| c == '_' || c.is_ascii_alphanumeric())
1595 {
1596 return Err(rhai_err(format!(
1597 "env name `{key}` must be a shell identifier ([A-Za-z_][A-Za-z0-9_]*)"
1598 )));
1599 }
1600 // Read via the shell so it works on remote hosts too.
1601 let (code, tail) = ctx
1602 .run(host, &format!("printf '%s' \"${{{key}}}\""))
1603 .map_err(rhai_err)?;
1604 if code != 0 {
1605 return Err(rhai_err(format!("env `{key}` on `{host}` failed")));
1606 }
1607 Ok(tail.trim().to_string())
1608 },
1609 );
1610 }
1611
1612 // --- collect(host, glob, app, version): pull artifacts to dist_root ---
1613 {
1614 let ctx = ctx.clone();
1615 engine.register_fn(
1616 "collect",
1617 move |host: &str,
1618 glob: &str,
1619 app: &str,
1620 version: &str|
1621 -> Result<(), Box<EvalAltResult>> {
1622 ctx.collect(host, glob, app, version).map_err(rhai_err)
1623 },
1624 );
1625 }
1626
1627 // --- publish(channel, app, target, version, artifact, meta) ---
1628 {
1629 let ctx = ctx.clone();
1630 engine.register_fn(
1631 "publish",
1632 move |channel: &str,
1633 app: &str,
1634 target: &str,
1635 version: &str,
1636 artifact: &str,
1637 meta: Map|
1638 -> Result<String, Box<EvalAltResult>> {
1639 ctx.publish(channel, app, target, version, artifact, &meta)
1640 .map_err(rhai_err)
1641 },
1642 );
1643 }
1644
1645 // --- deploy(binary) -> summary: install a service binary and restart its
1646 // unit. The terminal step for `kind = "service"`, the counterpart of
1647 // `publish` for something that is run rather than distributed.
1648 //
1649 // Takes only the binary's path on the build host: where it lands, on
1650 // which machine, and which unit restarts all come from the `[[deploy]]`
1651 // entry for the target already being built. A recipe cannot deploy the
1652 // aarch64 binary to the x86_64 box by naming the wrong host, because it
1653 // never names a host at all.
1654 {
1655 let ctx = ctx.clone();
1656 engine.register_fn(
1657 "deploy",
1658 move |binary: &str| -> Result<String, Box<EvalAltResult>> {
1659 ctx.deploy(binary).map_err(rhai_err)
1660 },
1661 );
1662 }
1663
1664 // --- deploy_host() -> string: the service host's ssh destination, so a
1665 // recipe can run its own assertions there (`sh_ok(deploy_host(), ...)`).
1666 // Commands run through it while the `deploy` step is open, so they are
1667 // gated on the deploy grant like the install itself. ---
1668 {
1669 let ctx = ctx.clone();
1670 engine.register_fn(
1671 "deploy_host",
1672 move || -> Result<String, Box<EvalAltResult>> {
1673 ctx.deploy_target()
1674 .map(|d| d.host.clone())
1675 .map_err(rhai_err)
1676 },
1677 );
1678 }
1679
1680 // --- service_name() / install_path() / health_url(): the rest of the
1681 // `[[deploy]]` entry, so a recipe asserts against the configured values
1682 // rather than repeating them as literals that can drift. `health_url`
1683 // is "" when unset. ---
1684 {
1685 let ctx = ctx.clone();
1686 engine.register_fn(
1687 "service_name",
1688 move || -> Result<String, Box<EvalAltResult>> {
1689 ctx.deploy_target()
1690 .map(|d| d.service.clone())
1691 .map_err(rhai_err)
1692 },
1693 );
1694 }
1695 {
1696 let ctx = ctx.clone();
1697 engine.register_fn(
1698 "install_path",
1699 move || -> Result<String, Box<EvalAltResult>> {
1700 ctx.deploy_target()
1701 .map(|d| d.install_path.clone())
1702 .map_err(rhai_err)
1703 },
1704 );
1705 }
1706 {
1707 let ctx = ctx.clone();
1708 engine.register_fn(
1709 "health_url",
1710 move || -> Result<String, Box<EvalAltResult>> {
1711 ctx.deploy_target()
1712 .map(|d| d.health_url.clone().unwrap_or_default())
1713 .map_err(rhai_err)
1714 },
1715 );
1716 }
1717
1718 // --- glibc_check(binary) -> string: assert the build host did not produce
1719 // a binary the service host's glibc is too old to exec. Aborts the run
1720 // if it did; returns "needs X, host has Y" for the log if it did not. ---
1721 {
1722 let ctx = ctx.clone();
1723 engine.register_fn(
1724 "glibc_check",
1725 move |binary: &str| -> Result<String, Box<EvalAltResult>> {
1726 let (needs, has) = ctx.glibc_check(binary).map_err(rhai_err)?;
1727 Ok(format!(
1728 "glibc: binary needs {needs}, service host has {has}"
1729 ))
1730 },
1731 );
1732 }
1733
1734 // --- macOS signing helpers. They dispatch through the named host's
1735 // executor like any other step; when that host is the mac (transport =
1736 // "agent"), codesign/notarize/staple ride the in-session `AgentRpc`
1737 // transport — the only security session where the Developer ID key is
1738 // usable (design §7 "THE WALL"). Capability-gated by the host's `sign`
1739 // grant. ---
1740 register_macos_fns(&mut engine, ctx);
1741
1742 engine
1743 }
1744
1745 /// Highest `GLIBC_x.y` version referenced by a built binary, and the glibc a
1746 /// host actually has, both parsed from the text the commands print.
1747 ///
1748 /// Native-per-architecture builds remove the cross-compile hazard `deploy.sh`
1749 /// was written against, but not this one: fw13 tracks a newer glibc than the
1750 /// Ubuntu 24.04 box in Hetzner, so a binary built here can reference a symbol
1751 /// version that box does not have and fail at exec — after the unit has already
1752 /// been restarted onto it. Comparing the two before the install is what makes
1753 /// that a failed step instead of a downed service.
1754 fn max_glibc_symbol(objdump_out: &str) -> Option<(u64, u64)> {
1755 objdump_out
1756 .split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '_' || c.is_ascii_alphabetic()))
1757 .filter_map(|tok| tok.strip_prefix("GLIBC_"))
1758 .filter_map(parse_glibc_version)
1759 .max()
1760 }
1761
1762 /// Parse `2.39` (or `2.39.1`, keeping major/minor) into a comparable pair.
1763 fn parse_glibc_version(s: &str) -> Option<(u64, u64)> {
1764 let mut parts = s.split('.');
1765 let major = parts.next()?.parse().ok()?;
1766 let minor = parts.next()?.parse().ok()?;
1767 Some((major, minor))
1768 }
1769
1770 /// The glibc version out of `ldd --version`'s first line, whose tail is the
1771 /// version however the distro decorates the rest (`ldd (Ubuntu GLIBC
1772 /// 2.39-0ubuntu8.8) 2.39`).
1773 fn glibc_from_ldd(ldd_out: &str) -> Option<(u64, u64)> {
1774 let first = ldd_out.lines().find(|l| !l.trim().is_empty())?;
1775 parse_glibc_version(first.split_whitespace().last()?)
1776 }
1777
1778 impl RecipeCtx {
1779 /// This target's install destination, or an error naming why there is none.
1780 fn deploy_target(&self) -> Result<&DeployTarget> {
1781 self.deploy.as_ref().ok_or_else(|| {
1782 anyhow::anyhow!(
1783 "no deploy destination for {} {}: the app is `kind = \"{}\"`, and only a \
1784 service declares [[deploy]] entries",
1785 self.app,
1786 self.target,
1787 match self.kind {
1788 Kind::App => "app",
1789 Kind::Library => "library",
1790 Kind::Service => "service",
1791 }
1792 )
1793 })
1794 }
1795
1796 /// Compare the built binary's glibc requirement against the service host's.
1797 /// Returns the two versions for the recipe to log.
1798 fn glibc_check(self: &Arc<Self>, binary: &str) -> Result<(String, String)> {
1799 let d = self.deploy_target()?.clone();
1800 // `objdump -T` on the build host; no symbols at all (a static binary)
1801 // means nothing to check, which is a pass rather than a failure.
1802 let (code, out) = self.run(
1803 &self.build_host.clone(),
1804 &format!(
1805 "objdump -T {binary} 2>/dev/null | grep -o 'GLIBC_[0-9.]*' | sort -uV || true"
1806 ),
1807 )?;
1808 anyhow::ensure!(code == 0, "reading glibc symbols from {binary} failed");
1809 let Some(needs) = max_glibc_symbol(&out) else {
1810 return Ok(("none".into(), "n/a".into()));
1811 };
1812 let (code, ldd) = self.run(&d.host, "ldd --version")?;
1813 anyhow::ensure!(
1814 code == 0,
1815 "could not read glibc version on service host `{}`",
1816 d.host
1817 );
1818 let has = glibc_from_ldd(&ldd).ok_or_else(|| {
1819 anyhow::anyhow!(
1820 "could not parse glibc version from `ldd --version` on `{}`",
1821 d.host
1822 )
1823 })?;
1824 anyhow::ensure!(
1825 needs <= has,
1826 "binary needs glibc {}.{} but `{}` has {}.{} — it would fail to exec after the \
1827 unit restarted onto it. Build on a host no newer than the service host.",
1828 needs.0,
1829 needs.1,
1830 d.host,
1831 has.0,
1832 has.1,
1833 );
1834 Ok((
1835 format!("{}.{}", needs.0, needs.1),
1836 format!("{}.{}", has.0, has.1),
1837 ))
1838 }
1839
1840 /// Install `binary` (a path on the BUILD host) onto the service host and
1841 /// restart its unit, via the privileged installer the host holds a scoped
1842 /// sudo grant for.
1843 ///
1844 /// Bento never runs the install itself. It stages the bytes and calls a
1845 /// root script whose arguments are re-checked on the far side — the same
1846 /// shape as Sando's `install-companion.sh`, and for the same reason: the
1847 /// sudoers grant is then ONE auditable script rather than a broad
1848 /// `install`+`systemctl` grant on a production box.
1849 ///
1850 /// Only the binary moves. Config is deliberately untouched: pom's
1851 /// `pom-astra.toml` / `pom-hetzner.toml` differ per instance, and prod's
1852 /// carried a `[targets.mnw.tests]` block the repo did not have. A deploy
1853 /// that copies config over is how that block gets silently deleted.
1854 fn deploy(self: &Arc<Self>, binary: &str) -> Result<String> {
1855 anyhow::ensure!(
1856 !self.is_cancelled(),
1857 "build superseded by a newer request; refusing to deploy"
1858 );
1859 // A failed earlier step bars a deploy exactly as it bars a publish. An
1860 // artifact that failed its gates must not reach a production host just
1861 // because the recipe kept running.
1862 let failed = self.failed_steps.lock().unwrap().clone();
1863 anyhow::ensure!(
1864 failed.is_empty(),
1865 "refusing to deploy {} {}: {} failed earlier in this run",
1866 self.app,
1867 self.version,
1868 failed
1869 .iter()
1870 .map(ToString::to_string)
1871 .collect::<Vec<_>>()
1872 .join(", "),
1873 );
1874 let d = self.deploy_target()?.clone();
1875 ensure_glob_safe(binary)?;
1876
1877 // Stage under a fixed root the installer also insists on, so "what was
1878 // checked" and "what is installed" cannot drift apart.
1879 let staged = format!("{DEPLOY_STAGING_ROOT}/{}", self.app);
1880 let staged_bin = format!("{staged}/{}", self.app);
1881 let deploy_exec = self.exec(&d.host)?;
1882 anyhow::ensure!(
1883 deploy_exec.capabilities().permits(&Action::Deploy),
1884 "service host `{}` is not granted the `deploy` capability",
1885 d.host
1886 );
1887
1888 self.run_ok(&d.host, &format!("mkdir -p {staged}"))?;
1889 if self.build_host_ssh == d.host {
1890 // Same box: the binary is already there. Routing it through the
1891 // daemon would be two transfers to end up where it started. This is
1892 // pom's aarch64 leg — astra builds it and astra runs it.
1893 self.run_ok(&d.host, &format!("cp -f {binary} {staged_bin}"))?;
1894 } else {
1895 // Build host -> daemon -> service host. Two hops because an executor
1896 // reaches one host; a direct host-to-host transport would mean the
1897 // build host holding a credential for the production box.
1898 let tmp = tempfile::tempdir().context("staging dir for deploy")?;
1899 let local = tmp.path().join(self.app.as_str());
1900 self.pull_for_deploy(binary, &local)?;
1901 let (dest, opts) = (PathBuf::from(&staged), SyncOpts::default());
1902 let dir = tmp.path().to_path_buf();
1903 self.run_bounded(&format!("stage {} on `{}`", self.app, d.host), async move {
1904 deploy_exec.push_dir(&dir, &dest, &opts).await
1905 })
1906 .with_context(|| format!("staging {} onto `{}`", self.app, d.host))?;
1907 }
1908
1909 // The privileged half. Every argument is re-validated by the script,
1910 // which is the thing actually holding the sudo grant.
1911 self.run_ok(
1912 &d.host,
1913 &format!(
1914 "{} {staged_bin} {} {}",
1915 self.cfg.deploy_installer, d.install_path, d.service
1916 ),
1917 )?;
1918 Ok(format!(
1919 "{} {} installed at {} on `{}`; {} restarted",
1920 self.app, self.version, d.install_path, d.host, d.service
1921 ))
1922 }
1923
1924 /// Fetch one file off a host into a daemon-local path for re-pushing.
1925 ///
1926 /// A local build host is read directly: `fw13` is the daemon's own box, so
1927 /// the file is already on this filesystem. Routing it through the
1928 /// artifact-pull gate instead would demand a `pull_root` covering every repo
1929 /// a service could be built in — today that is `~/Code/Apps`, and pom lives
1930 /// in `~/Code/MNW`. Widening it to `~/Code` would put `_private`, the
1931 /// secrets root, inside the collectable tree. This is pom's x86_64 leg.
1932 fn pull_for_deploy(self: &Arc<Self>, remote: &str, local: &Path) -> Result<()> {
1933 let host = self.build_host.clone();
1934 let remote_path = expand_tilde(remote);
1935 if self.build_host_ssh == "local" || self.build_host_ssh.is_empty() {
1936 std::fs::copy(&remote_path, local).with_context(|| {
1937 format!("staging {} from the daemon host", remote_path.display())
1938 })?;
1939 return Ok(());
1940 }
1941 let sync = self.host_sync(&host)?;
1942 let (src, dst, opts) = (remote_path, local.to_path_buf(), SyncOpts::default());
1943 self.run_bounded(&format!("fetch {remote} from `{host}`"), async move {
1944 sync.pull_file(&src, &dst, &opts).await
1945 })
1946 .with_context(|| format!("fetching {remote} from `{host}` to deploy"))
1947 }
1948
1949 /// `run`, failing the step on a non-zero exit. The Rust-side twin of the
1950 /// recipe's `sh_ok`, for commands the deploy machinery issues itself.
1951 fn run_ok(self: &Arc<Self>, host: &str, cmd: &str) -> Result<String> {
1952 let (code, tail) = self.run(host, cmd)?;
1953 if code != 0 {
1954 self.fail_current_step();
1955 anyhow::bail!("command on `{host}` exited {code}: {cmd}\n{tail}");
1956 }
1957 Ok(tail)
1958 }
1959
1960 /// Where this run's collected files land locally.
1961 ///
1962 /// Per target, not per version. Every target used to share one
1963 /// `dist_root/<app>/<version>/`, so the hash loop below (which lists the
1964 /// directory) attributed a sibling's AppImage to the mac build's artifact
1965 /// record. It is also the layout the archive uses, and the two have to agree
1966 /// or the local copy and the deposited one are different shapes.
1967 fn collect_dest(&self, app: &str, version: &str) -> PathBuf {
1968 self.cfg
1969 .dist_root
1970 .join(app)
1971 .join(version)
1972 .join(crate::archive::target_slug(self.target))
1973 }
1974
1975 fn collect(self: &Arc<Self>, host: &str, glob: &str, app: &str, version: &str) -> Result<()> {
1976 let dest = self.collect_dest(app, version);
1977 let dest_s = dest.to_string_lossy().into_owned();
1978 // The glob reaches a remote login shell intact (that's what expands it),
1979 // so command metacharacters stay barred. Path/wildcard chars are fine.
1980 ensure_glob_safe(glob)?;
1981 std::fs::create_dir_all(&dest)
1982 .with_context(|| format!("creating collect dest {dest_s}"))?;
1983 // The SYNC transport, not the host's exec executor: artifacts move over
1984 // ssh/rsync even from an agent host, whose `/pull` is confined to a
1985 // narrow `pull_root` that deliberately excludes the repo checkout these
1986 // artifacts are built in (see `state::build_sync`). The daemon still
1987 // runs the transfer itself, as it always has.
1988 let sync = self.host_sync(host)?;
1989 let opts = SyncOpts::precompressed();
1990 // Bounded by the collect step's deadline (rsync of a multi-GiB artifact
1991 // can wedge on a stalled transport) and interruptible on supersession.
1992 let dest_pull = dest.clone();
1993 self.run_bounded(&format!("collect {glob} from `{host}`"), async move {
1994 sync.pull_glob(glob, &dest_pull, &opts).await
1995 })
1996 .with_context(|| format!("collect {glob} from `{host}`"))?;
1997 // Assert the version and hash every collected file. This is where a
1998 // stale artifact is caught: a file whose name embeds a different version
1999 // fails the collect (rather than silently winning a later glob), and the
2000 // sha256 recorded here is what `publish` writes into the release ledger
2001 // and what the artifact record's manifest is built from.
2002 //
2003 // Recursive, and keyed by path relative to the collect dir. That is not
2004 // a preference: Sando's intake re-hashes the bundle with its own walker,
2005 // which recurses and keys the same way, and refuses a bundle whose bytes
2006 // do not match the manifest it was handed. A top-level `read_dir` keyed
2007 // by file name agrees with that walker for a flat directory and diverges
2008 // the moment a bundle carries a subdirectory — the honest artifact would
2009 // be refused for a manifest that omitted everything nested. The two
2010 // walkers have to be the same walk. See `bundle::digest_dir` in sando.
2011 for (rel, path) in
2012 collected_files(&dest).with_context(|| format!("listing collect dest {dest_s}"))?
2013 {
2014 // The version check stays on the file NAME rather than the relative
2015 // path: it is looking for a stale `app_1.2.3.AppImage` beside the
2016 // one this release built, and a directory component is not that.
2017 let name = path
2018 .file_name()
2019 .map_or_else(|| rel.clone(), |n| n.to_string_lossy().into_owned());
2020 assert_artifact_version(&name, &self.version)?;
2021 let digest = sha256_file(&path)?;
2022 self.artifact_hashes.lock().unwrap().insert(rel, digest);
2023 }
2024 // Deposit at the archive path, so this target's bytes have one address
2025 // whichever host produced them. A no-op when no archive is configured.
2026 //
2027 // Inside `collect`, not after the recipe: a failure here fails the
2028 // collect step, before sign and publish, rather than putting a red mark
2029 // on a release that has already shipped. And it is a failure, not a
2030 // warning — a deposit that is quietly skipped leaves the archive path
2031 // wrong for exactly the release nobody was watching, which is the thing
2032 // having one address is for.
2033 let (cfg, app_id, version, target) = (
2034 self.cfg.clone(),
2035 self.app.clone(),
2036 self.version.clone(),
2037 self.target,
2038 );
2039 let dest_archive = dest.clone();
2040 self.run_bounded("deposit in the archive", async move {
2041 crate::archive::deposit(&cfg, &dest_archive, &app_id, &version, target).await
2042 })?;
2043 // Best-effort size accounting for the event.
2044 events::emit(
2045 &self.events,
2046 Event::ArtifactCollected {
2047 app: self.app.clone(),
2048 target: self.target,
2049 path: dest_s,
2050 bytes: dir_size(&dest).unwrap_or(0),
2051 },
2052 );
2053 Ok(())
2054 }
2055
2056 /// The all-targets-green gate: err unless every declared target OTHER than
2057 /// the one publishing has a latest `target_runs` row of `ok` for this
2058 /// `(app, version)`. A sibling with no run, a running run, or a failed
2059 /// latest run all block the publish, naming what is not green.
2060 fn assert_siblings_green(self: &Arc<Self>, declared: &[Target]) -> Result<()> {
2061 let me = self.clone();
2062 let (app_s, ver_s) = (self.app.to_string(), self.version.to_string());
2063 let rows: Vec<(String, String)> = self.rt.block_on(async move {
2064 sqlx::query_as(
2065 "SELECT target, status FROM target_runs tr
2066 WHERE app = ?1 AND version = ?2
2067 AND id = (SELECT MAX(id) FROM target_runs
2068 WHERE app = ?1 AND version = ?2 AND target = tr.target)",
2069 )
2070 .bind(app_s)
2071 .bind(ver_s)
2072 .fetch_all(&me.pool)
2073 .await
2074 .unwrap_or_default()
2075 });
2076 let status_of = |t: &Target| -> Option<String> {
2077 let key = t.to_string();
2078 rows.iter()
2079 .find(|(name, _)| name == &key)
2080 .map(|(_, s)| s.clone())
2081 };
2082 let not_green: Vec<String> = declared
2083 .iter()
2084 .filter(|t| **t != self.target) // the publishing target is the last mile
2085 .filter(|t| status_of(t).as_deref() != Some("ok"))
2086 .map(|t| format!("{t} ({})", status_of(t).unwrap_or_else(|| "no run".into())))
2087 .collect();
2088 anyhow::ensure!(
2089 not_green.is_empty(),
2090 "all-targets-green gate: refusing to publish {} {} — not green: {}",
2091 self.app,
2092 self.version,
2093 not_green.join(", "),
2094 );
2095 Ok(())
2096 }
2097
2098 fn publish(
2099 self: &Arc<Self>,
2100 channel: &str,
2101 app: &str,
2102 target: &str,
2103 version: &str,
2104 artifact: &str,
2105 meta: &Map,
2106 ) -> Result<String> {
2107 // Never let a superseded build ship. This is the last and most important
2108 // cooperative-cancel checkpoint: even if a long-running step finished
2109 // after supersession, the artifact must not reach the backend.
2110 anyhow::ensure!(
2111 !self.is_cancelled(),
2112 "build superseded by a newer request; refusing to publish"
2113 );
2114 // Opt-in all-targets-green gate: refuse a partial release. Every OTHER
2115 // declared target of this (app, version) must have a successful latest
2116 // run before this one ships, so macOS can't publish while windows is red
2117 // or still building. The publishing target itself is the last mile (it
2118 // reached publish, so its steps passed) and is not required to be green
2119 // in the ledger yet.
2120 if let Some(declared) = self.all_green_required.clone() {
2121 self.assert_siblings_green(&declared)?;
2122 }
2123 let backend = self
2124 .ota
2125 .get(channel)
2126 .ok_or_else(|| anyhow::anyhow!("unknown publish channel `{channel}`"))?;
2127 let target: Target = target.parse().map_err(|e: String| anyhow::anyhow!(e))?;
2128 let version = Version::parse(version).map_err(|e| anyhow::anyhow!(e))?;
2129 let app = AppId::new(app);
2130
2131 // The backend must actually handle this target (e.g. the desktop updater
2132 // disclaims iOS) — otherwise publish would push an artifact through a
2133 // backend that does not support it.
2134 anyhow::ensure!(
2135 backend.supports(target),
2136 "publish channel `{channel}` does not support target {target}",
2137 );
2138
2139 // Monotonicity: never publish a version that is not strictly newer than
2140 // the latest already published for this (app, target, channel). Without
2141 // this an older build could republish over a live newer release. The
2142 // `releases` column is TEXT, so compare by parsed semver precedence
2143 // (Version: Ord), not lexically.
2144 {
2145 let (app_s, target_s, chan_s) =
2146 (app.to_string(), target.to_string(), channel.to_string());
2147 let me = self.clone();
2148 let latest: Option<Version> = self.rt.block_on(async move {
2149 let rows: Vec<(String,)> = sqlx::query_as(
2150 "SELECT version FROM releases WHERE app = ? AND target = ? AND channel = ?",
2151 )
2152 .bind(app_s)
2153 .bind(target_s)
2154 .bind(chan_s)
2155 .fetch_all(&me.pool)
2156 .await
2157 .unwrap_or_default();
2158 rows.into_iter()
2159 .filter_map(|(v,)| Version::parse(&v).ok())
2160 .max()
2161 });
2162 if let Some(latest) = latest {
2163 anyhow::ensure!(
2164 version > latest,
2165 "refusing to publish {app} {version} to `{channel}` ({target}): \
2166 not newer than the last published {latest}",
2167 );
2168 }
2169 }
2170
2171 // Step-success ledger (the Bento analogue of Sando's gate fail-closed),
2172 // minted as an unforgeable PublishAuthority. `backend.publish` cannot be
2173 // called without one, so the unverified/post-failure ship path is sealed
2174 // at the type level rather than guarded by a separate runtime check.
2175 let authority = {
2176 let failed = self.failed_steps.lock().unwrap();
2177 let gatekeeper = *self.gatekeeper_ok.lock().unwrap();
2178 PublishAuthority::prove(target, failed.as_slice(), gatekeeper)?
2179 };
2180 let notes = meta
2181 .get("notes")
2182 .and_then(|v| v.clone().into_string().ok())
2183 .unwrap_or_default();
2184 // Resolve the artifact relative to the collected dist dir if not absolute.
2185 let artifact_path = {
2186 let p = PathBuf::from(artifact);
2187 if p.is_absolute() {
2188 p
2189 } else {
2190 self.collect_dest(app.as_str(), &version.to_string())
2191 .join(artifact)
2192 }
2193 };
2194 let rel = Release {
2195 app: &app,
2196 target,
2197 version: &version,
2198 notes,
2199 };
2200 let receipt = backend
2201 .publish(&rel, &artifact_path, &authority)
2202 .with_context(|| format!("publish to `{channel}`"))?;
2203 // Record for idempotency / monotonicity. This write is CHECKED, not
2204 // fire-and-forget: a swallowed failure here would silently re-arm the
2205 // monotonicity guard (which reads this same table), letting an older
2206 // version republish over a live release. Concurrent same-(app,target)
2207 // publishers can't race the read-then-insert because the latest-wins slot
2208 // (state::ActiveSlot) serializes them and a superseded run is cancelled
2209 // before it reaches publish.
2210 // The artifact's hash, recorded so the release ledger says exactly which
2211 // bytes shipped. Prefer the digest computed at `collect`; fall back to
2212 // hashing the file now (an absolute-path artifact never routed through
2213 // `collect`). A hash failure must not fail an already-published release,
2214 // so degrade to NULL rather than erroring.
2215 let artifact_hash: Option<String> = artifact_path
2216 .file_name()
2217 .and_then(|n| n.to_str())
2218 .and_then(|n| self.artifact_hashes.lock().unwrap().get(n).cloned())
2219 .or_else(|| sha256_file(&artifact_path).ok());
2220 let me = self.clone();
2221 let (app_s, target_s, ver_s, chan_s) = (
2222 app.to_string(),
2223 target.to_string(),
2224 version.to_string(),
2225 channel.to_string(),
2226 );
2227 self.rt
2228 .block_on(async move {
2229 sqlx::query(
2230 "INSERT OR IGNORE INTO releases (app, target, version, channel, artifact_hash, published_at)
2231 VALUES (?, ?, ?, ?, ?, ?)",
2232 )
2233 .bind(app_s)
2234 .bind(target_s)
2235 .bind(ver_s)
2236 .bind(chan_s)
2237 .bind(artifact_hash)
2238 .bind(Self::now())
2239 .execute(&me.pool)
2240 .await
2241 })
2242 .context("recording release in the idempotency ledger (artifact published but ledger write failed)")?;
2243 events::emit(
2244 &self.events,
2245 Event::PublishOk {
2246 app: self.app.clone(),
2247 target: self.target,
2248 channel: channel.to_string(),
2249 },
2250 );
2251 Ok(receipt)
2252 }
2253 }
2254
2255 fn dir_size(p: &Path) -> Option<i64> {
2256 let mut total = 0i64;
2257 for entry in std::fs::read_dir(p).ok()? {
2258 let entry = entry.ok()?;
2259 let md = entry.metadata().ok()?;
2260 if md.is_file() {
2261 total += md.len() as i64;
2262 } else if md.is_dir() {
2263 // Recurse so a bundle dir (a `.app`) reports its real size, not ~0.
2264 total += dir_size(&entry.path()).unwrap_or(0);
2265 }
2266 }
2267 Some(total)
2268 }
2269
2270 /// macOS signing/notarization host functions. Thin wrappers over the right
2271 /// shell incantations, dispatched through the named host's executor. On the mac
2272 /// host (`transport = "agent"`) they run via the in-session `ops-agent`, the only
2273 /// context where codesign can use the Developer ID key (design §7 "THE WALL"); a
2274 /// plain SSH session cannot. Each is gated by the host's `sign` capability.
2275 fn register_macos_fns(engine: &mut Engine, ctx: &Arc<RecipeCtx>) {
2276 {
2277 let ctx = ctx.clone();
2278 engine.register_fn(
2279 "verify_gatekeeper",
2280 move |host: &str, path: &str| -> Result<bool, Box<EvalAltResult>> {
2281 // spctl has no JSON mode, so assess on-host and decide there,
2282 // emitting an unambiguous sentinel as the final line. We match the
2283 // sentinel rather than substring-hunting `source=Notarized...` in a
2284 // 2000-char tail: truncation only drops the front, so the sentinel
2285 // is always present, and it can't be spoofed by spctl's own prose.
2286 // The full assess output is still streamed to the step log.
2287 let q = ops_core::remote::sh_quote(path);
2288 let cmd = format!(
2289 "out=$(spctl --assess -vv --type install {q} 2>&1); printf '%s\\n' \"$out\"; \
2290 printf '%s' \"$out\" | grep -q 'source=Notarized Developer ID' \
2291 && echo BENTO_GATEKEEPER_OK || echo BENTO_GATEKEEPER_FAIL",
2292 );
2293 let (_, tail) = ctx.run(host, &cmd).map_err(rhai_err)?;
2294 let accepted = tail.contains("BENTO_GATEKEEPER_OK");
2295 // Record the verdict for the publish gate. A rejection also
2296 // fails the step, so the matrix shows red and `publish` is barred
2297 // even if the recipe ignores the returned bool.
2298 *ctx.gatekeeper_ok.lock().unwrap() = Some(accepted);
2299 if !accepted {
2300 ctx.fail_current_step();
2301 }
2302 Ok(accepted)
2303 },
2304 );
2305 }
2306 {
2307 let ctx = ctx.clone();
2308 engine.register_fn(
2309 "codesign",
2310 move |host: &str, identity: &str, path: &str| -> Result<(), Box<EvalAltResult>> {
2311 let cmd = format!(
2312 "codesign --force --options runtime --timestamp --sign {} {}",
2313 ops_core::remote::sh_quote(identity),
2314 ops_core::remote::sh_quote(path),
2315 );
2316 let (code, _) = ctx.run(host, &cmd).map_err(rhai_err)?;
2317 if code != 0 {
2318 return Err(rhai_err("codesign failed"));
2319 }
2320 Ok(())
2321 },
2322 );
2323 }
2324 {
2325 let ctx = ctx.clone();
2326 engine.register_fn(
2327 "staple",
2328 move |host: &str, path: &str| -> Result<(), Box<EvalAltResult>> {
2329 let (code, _) = ctx
2330 .run(
2331 host,
2332 &format!("xcrun stapler staple {}", ops_core::remote::sh_quote(path)),
2333 )
2334 .map_err(rhai_err)?;
2335 if code != 0 {
2336 return Err(rhai_err("stapler failed"));
2337 }
2338 Ok(())
2339 },
2340 );
2341 }
2342 {
2343 let ctx = ctx.clone();
2344 engine.register_fn(
2345 "notarize",
2346 move |host: &str, path: &str| -> Result<String, Box<EvalAltResult>> {
2347 ctx.notarize(host, path).map_err(rhai_err)
2348 },
2349 );
2350 }
2351 {
2352 let ctx = ctx.clone();
2353 engine.register_fn(
2354 "keychain_open",
2355 move |host: &str, name: &str| -> Result<(), Box<EvalAltResult>> {
2356 // The full build-keychain lifecycle lives in dist/build-keychain.sh
2357 // (design §7); this drives it by name so the recipe stays short.
2358 let (code, _) = ctx
2359 .run(
2360 host,
2361 &format!(
2362 ". ~/.tauri/passwords.env && ./dist/build-keychain.sh open {}",
2363 ops_core::remote::sh_quote(name)
2364 ),
2365 )
2366 .map_err(rhai_err)?;
2367 if code != 0 {
2368 return Err(rhai_err("keychain_open failed"));
2369 }
2370 Ok(())
2371 },
2372 );
2373 }
2374 {
2375 let ctx = ctx.clone();
2376 engine.register_fn(
2377 "keychain_close",
2378 move |host: &str, name: &str| -> Result<(), Box<EvalAltResult>> {
2379 let _ = ctx.run(
2380 host,
2381 &format!(
2382 "./dist/build-keychain.sh close {}",
2383 ops_core::remote::sh_quote(name)
2384 ),
2385 );
2386 Ok(())
2387 },
2388 );
2389 }
2390 }
2391
2392 impl RecipeCtx {
2393 /// `xcrun notarytool submit --wait` with bounded retry (the one flaky,
2394 /// network-bound step). Emits `NotarizeRetry` per attempt.
2395 fn notarize(self: &Arc<Self>, host: &str, path: &str) -> Result<String> {
2396 const MAX_ATTEMPTS: u32 = 3;
2397 let backoff = self
2398 .cfg
2399 .notarize_backoff_secs
2400 .map_or(std::time::Duration::from_secs(15), |s| {
2401 std::time::Duration::from_secs(s)
2402 });
2403 let cmd = format!(
2404 ". ~/.tauri/passwords.env && xcrun notarytool submit {} \
2405 --key \"$NOTARY_KEY\" --key-id \"$NOTARY_KEY_ID\" --issuer \"$NOTARY_ISSUER\" \
2406 --wait --output-format json",
2407 ops_core::remote::sh_quote(path),
2408 );
2409 let mut last = String::new();
2410 for attempt in 1..=MAX_ATTEMPTS {
2411 let (code, tail) = self.run(host, &cmd)?;
2412 if code == 0 && notary_accepted(&tail) {
2413 return Ok(tail);
2414 }
2415 last = tail;
2416 if attempt < MAX_ATTEMPTS {
2417 events::emit(
2418 &self.events,
2419 Event::NotarizeRetry {
2420 app: self.app.clone(),
2421 target: self.target,
2422 attempt,
2423 reason: format!("exit {code}"),
2424 },
2425 );
2426 self.rt.block_on(tokio::time::sleep(backoff));
2427 }
2428 }
2429 anyhow::bail!("notarization failed after {MAX_ATTEMPTS} attempts: {last}")
2430 }
2431 }
2432
2433 /// True iff `notarytool --output-format json` output reports `status: Accepted`.
2434 /// Isolates the JSON object (`{`..`}`) from any shell-sourcing noise and reads
2435 /// the typed `status` field, rather than substring-matching `"status":"Accepted"`
2436 /// in a possibly-truncated tail — which could match the literal inside an error
2437 /// message or miss it across a whitespace variant. Fails closed: any parse or
2438 /// field miss returns false.
2439 fn notary_accepted(output: &str) -> bool {
2440 let (Some(start), Some(end)) = (output.find('{'), output.rfind('}')) else {
2441 return false;
2442 };
2443 if start > end {
2444 return false;
2445 }
2446 serde_json::from_str::<serde_json::Value>(&output[start..=end])
2447 .ok()
2448 .and_then(|v| {
2449 v.get("status")
2450 .and_then(|s| s.as_str())
2451 .map(|s| s.eq_ignore_ascii_case("accepted"))
2452 })
2453 .unwrap_or(false)
2454 }
2455
2456 #[cfg(test)]
2457 mod tests {
2458 use super::*;
2459
2460 /// Build the shared cross-crate bundle fixture under `root`.
2461 ///
2462 /// A binary at the top and two files in a subdirectory — the shape a service
2463 /// that ships its migrations has, which is the case the flat walk used to
2464 /// get wrong.
2465 pub(crate) fn write_bundle_fixture(root: &Path) {
2466 std::fs::create_dir_all(root.join("migrations")).unwrap();
2467 std::fs::write(root.join("pom"), b"binary-bytes").unwrap();
2468 std::fs::write(root.join("migrations/001_init.sql"), b"create table a;").unwrap();
2469 std::fs::write(root.join("migrations/002_next.sql"), b"alter table a;").unwrap();
2470 }
2471
2472 /// The manifest text the fixture must produce, in BOTH crates.
2473 ///
2474 /// Sando's `bundle::digest_dir` has the identical constant and the identical
2475 /// fixture. That is the whole point: bento writes this text into the artifact
2476 /// record, sando recomputes it from the bytes that arrive, and an artifact is
2477 /// refused when they differ. Two walks, one answer, pinned from both ends —
2478 /// if either crate's walk drifts, its own test fails and names the drift
2479 /// rather than a release failing intake for a bundle nothing is wrong with.
2480 pub(crate) const BUNDLE_FIXTURE_MANIFEST: &str = concat!(
2481 "e4c908e219c533fa7ad7ea1634398f9bf51637ba20717769ada545bab26d7368 migrations/001_init.sql\n",
2482 "b026fd51bae096b34672cefdb781b6585b13efb53bc301d50c305f422552a380 migrations/002_next.sql\n",
2483 "71227a7f160afca3fb3c39f448735886dda7bd366252580c2222fb87d4bb4d85 pom\n",
2484 );
2485
2486 /// The producer half of the contract above: what `collect` hashes, turned
2487 /// into a manifest, is exactly the text the verifier will recompute.
2488 ///
2489 /// Nested files are included and addressed by relative path. Before this,
2490 /// `collect` listed only the top level, so `migrations/` contributed nothing
2491 /// to the manifest while sando's walker hashed both files in it — and the
2492 /// honest bundle was refused for a manifest that had omitted them.
2493 #[test]
2494 fn a_collected_bundle_manifests_exactly_as_the_verifier_will_read_it() {
2495 let dir = tempfile::tempdir().unwrap();
2496 write_bundle_fixture(dir.path());
2497
2498 let files = collected_files(dir.path()).unwrap();
2499 assert_eq!(
2500 files.iter().map(|(r, _)| r.as_str()).collect::<Vec<_>>(),
2501 vec!["migrations/001_init.sql", "migrations/002_next.sql", "pom"],
2502 "recursive, relative, sorted"
2503 );
2504
2505 let hashes: Vec<(String, String)> = files
2506 .into_iter()
2507 .map(|(rel, path)| (rel, sha256_file(&path).unwrap()))
2508 .collect();
2509 let manifest = ops_artifact::Manifest::new(hashes).unwrap();
2510 assert_eq!(manifest.to_text(), BUNDLE_FIXTURE_MANIFEST);
2511 }
2512
2513 /// A symlink is neither followed nor named. Following one would let bytes
2514 /// from outside the bundle into its identity; naming it would put a path in
2515 /// the manifest the verifier does not hash, which reads as a corrupt bundle.
2516 #[test]
2517 #[cfg(unix)]
2518 fn a_symlink_in_the_collect_dir_is_not_part_of_the_bundle() {
2519 let dir = tempfile::tempdir().unwrap();
2520 write_bundle_fixture(dir.path());
2521 let outside = dir.path().join("..").join("secret.env");
2522 std::fs::write(&outside, b"TOKEN=1").ok();
2523 std::os::unix::fs::symlink(&outside, dir.path().join("link.env")).unwrap();
2524
2525 let files = collected_files(dir.path()).unwrap();
2526 assert!(
2527 !files.iter().any(|(rel, _)| rel.contains("link.env")),
2528 "{files:?}"
2529 );
2530 }
2531
2532 /// Run 3 S1: once the cooperative cancel flag is set (a newer build
2533 /// superseded this run), a step boundary refuses to proceed — the blocking
2534 /// recipe stops at the next `step()` instead of running on and publishing.
2535 #[tokio::test]
2536 async fn begin_step_bails_when_cancelled() {
2537 let dir = tempfile::tempdir().unwrap();
2538 let cfg = Arc::new(Config::for_tests(dir.path()));
2539 let pool = crate::db::open(&cfg.db_path).await.unwrap();
2540 let cancel = Arc::new(AtomicBool::new(true));
2541 let ctx = Arc::new(RecipeCtx::new(
2542 AppId::new("demo"),
2543 Version::parse("0.1.0").unwrap(),
2544 "linux/x86_64".parse().unwrap(),
2545 "fw13".into(),
2546 "local".into(),
2547 "v0.1.0".into(),
2548 "/tmp".into(),
2549 vec![],
2550 Kind::App,
2551 1,
2552 Arc::new(std::collections::HashMap::new()),
2553 Arc::new(std::collections::HashMap::new()),
2554 None,
2555 pool,
2556 crate::events::channel(),
2557 cfg,
2558 Arc::new(OtaRegistry::standard("https://makenot.work")),
2559 tokio::runtime::Handle::current(),
2560 cancel.clone(),
2561 None,
2562 ));
2563 // Cancelled: begin_step refuses before touching the DB (the ensure! is
2564 // ahead of any block_on, so this is safe to call from the async test).
2565 let err = ctx.begin_step(Step::Build).unwrap_err();
2566 assert!(err.to_string().contains("supersede"), "got: {err}");
2567 assert!(ctx.is_cancelled());
2568 }
2569
2570 /// `feature_flags()` returns a whole flag or nothing at all. An app with
2571 /// no declared features must not yield a bare `--features`, which would
2572 /// swallow the next word of the build command as its argument.
2573 #[tokio::test]
2574 async fn feature_flags_renders_whole_flag_or_empty() {
2575 async fn flags_for(features: Vec<String>) -> String {
2576 let dir = tempfile::tempdir().unwrap();
2577 let cfg = Arc::new(Config::for_tests(dir.path()));
2578 let pool = crate::db::open(&cfg.db_path).await.unwrap();
2579 let ctx = Arc::new(RecipeCtx::new(
2580 AppId::new("demo"),
2581 Version::parse("0.1.0").unwrap(),
2582 "linux/x86_64".parse().unwrap(),
2583 "fw13".into(),
2584 "local".into(),
2585 "v0.1.0".into(),
2586 "/tmp".into(),
2587 features,
2588 Kind::App,
2589 1,
2590 Arc::new(std::collections::HashMap::new()),
2591 Arc::new(std::collections::HashMap::new()),
2592 None,
2593 pool,
2594 crate::events::channel(),
2595 cfg,
2596 Arc::new(OtaRegistry::standard("https://makenot.work")),
2597 tokio::runtime::Handle::current(),
2598 Arc::new(AtomicBool::new(false)),
2599 None,
2600 ));
2601 let engine = build_engine(&ctx);
2602 engine.eval::<String>("feature_flags()").unwrap()
2603 }
2604
2605 assert_eq!(flags_for(vec![]).await, "");
2606 assert_eq!(
2607 flags_for(vec!["supernote".into()]).await,
2608 "--features supernote"
2609 );
2610 assert_eq!(
2611 flags_for(vec!["supernote".into(), "extra".into()]).await,
2612 "--features supernote,extra"
2613 );
2614 }
2615
2616 /// `repo()` answers for the host this target builds on, not for the daemon.
2617 ///
2618 /// This is what lets a Windows recipe call `repo()` and `checkout_sha(h)`
2619 /// instead of hard-coding `C:/Users/me/...` — and hard-coding it is what
2620 /// kept those recipes off the release-tag pin, since `checkout_sha` builds
2621 /// its git commands from the app's path and takes no override.
2622 #[tokio::test]
2623 async fn repo_resolves_per_build_host() {
2624 async fn repo_on(build_host: &str) -> String {
2625 let dir = tempfile::tempdir().unwrap();
2626 let cfg = Arc::new(Config::for_tests(dir.path()));
2627 let pool = crate::db::open(&cfg.db_path).await.unwrap();
2628 let ctx = Arc::new(
2629 RecipeCtx::new(
2630 AppId::new("demo"),
2631 Version::parse("0.1.0").unwrap(),
2632 "linux/x86_64".parse().unwrap(),
2633 build_host.into(),
2634 "local".into(),
2635 "v0.1.0".into(),
2636 "~/Code/Apps/demo".into(),
2637 vec![],
2638 Kind::App,
2639 1,
2640 Arc::new(std::collections::HashMap::new()),
2641 Arc::new(std::collections::HashMap::new()),
2642 None,
2643 pool,
2644 crate::events::channel(),
2645 cfg,
2646 Arc::new(OtaRegistry::standard("https://makenot.work")),
2647 tokio::runtime::Handle::current(),
2648 Arc::new(AtomicBool::new(false)),
2649 None,
2650 )
2651 .with_repo_by_host(HashMap::from([(
2652 "windows-x86".to_string(),
2653 "C:/Users/me/Code/Apps/demo".to_string(),
2654 )])),
2655 );
2656 build_engine(&ctx).eval::<String>("repo()").unwrap()
2657 }
2658
2659 assert_eq!(repo_on("windows-x86").await, "C:/Users/me/Code/Apps/demo");
2660 assert_eq!(repo_on("fw13").await, "~/Code/Apps/demo");
2661 }
2662
2663 /// `secret(key)` reads a file under `secrets_root`, trims its trailing
2664 /// newline (the shape of a here-doc'd token file), and refuses any key that
2665 /// could escape the root. Covers the host-fn registered in `build_engine`.
2666 #[tokio::test]
2667 async fn secret_reads_under_root_and_blocks_traversal() {
2668 let dir = tempfile::tempdir().unwrap();
2669 let cfg = Config::for_tests(dir.path());
2670 // Seed a secret and one in a nested subdir; a trailing newline that the
2671 // read must strip.
2672 std::fs::create_dir_all(&cfg.secrets_root).unwrap();
2673 std::fs::write(cfg.secrets_root.join("token"), "s3cr3t\n").unwrap();
2674 std::fs::create_dir_all(cfg.secrets_root.join("app")).unwrap();
2675 std::fs::write(cfg.secrets_root.join("app").join("key"), "nested").unwrap();
2676 // Plant a file OUTSIDE the root that a traversal key would reach.
2677 std::fs::write(dir.path().join("outside"), "leak").unwrap();
2678
2679 let cfg = Arc::new(cfg);
2680 let pool = crate::db::open(&cfg.db_path).await.unwrap();
2681 let ctx = Arc::new(RecipeCtx::new(
2682 AppId::new("demo"),
2683 Version::parse("0.1.0").unwrap(),
2684 "linux/x86_64".parse().unwrap(),
2685 "fw13".into(),
2686 "local".into(),
2687 "v0.1.0".into(),
2688 "/tmp".into(),
2689 vec![],
2690 Kind::App,
2691 1,
2692 Arc::new(std::collections::HashMap::new()),
2693 Arc::new(std::collections::HashMap::new()),
2694 None,
2695 pool,
2696 crate::events::channel(),
2697 cfg,
2698 Arc::new(OtaRegistry::standard("https://makenot.work")),
2699 tokio::runtime::Handle::current(),
2700 Arc::new(AtomicBool::new(false)),
2701 None,
2702 ));
2703 let engine = build_engine(&ctx);
2704
2705 // Happy path: read + trim.
2706 assert_eq!(
2707 engine.eval::<String>(r#"secret("token")"#).unwrap(),
2708 "s3cr3t"
2709 );
2710 // A multi-segment relative key is allowed.
2711 assert_eq!(
2712 engine.eval::<String>(r#"secret("app/key")"#).unwrap(),
2713 "nested"
2714 );
2715
2716 // Traversal, absolute paths, and empty keys are refused BEFORE any read,
2717 // so the file one `..` above the root is never disclosed.
2718 for bad in [
2719 r#"secret("../outside")"#,
2720 r#"secret("/etc/passwd")"#,
2721 r#"secret("")"#,
2722 ] {
2723 let err = engine.eval::<String>(bad).unwrap_err().to_string();
2724 assert!(
2725 err.contains("relative path under secrets_root"),
2726 "`{bad}` should hit the traversal guard, got: {err}"
2727 );
2728 }
2729 // A missing key surfaces the filesystem error, not a panic, and does not
2730 // trip the traversal guard (it is a legitimate relative path).
2731 let err = engine
2732 .eval::<String>(r#"secret("nope")"#)
2733 .unwrap_err()
2734 .to_string();
2735 assert!(err.contains("secret `nope`"), "got: {err}");
2736 }
2737
2738 /// The two failures that actually shipped, as regression cases.
2739 #[test]
2740 fn preflight_catches_a_dead_repository_url() {
2741 // pter 0.1.0: repository pointed at a URL that does not exist. It
2742 // published clean and the link is now permanent for that version.
2743 let meta = CrateMeta {
2744 name: "pter".into(),
2745 version: "0.1.0".into(),
2746 repository: Some("https://github.com/maxjacobson/pter".into()),
2747 description: Some("d".into()),
2748 licensed: true,
2749 };
2750 let problems = crate_publish_problems(&meta, false, &[], true);
2751 assert_eq!(problems.len(), 1, "{problems:?}");
2752 assert!(
2753 problems[0].contains("not publicly clonable"),
2754 "{problems:?}"
2755 );
2756
2757 // Same metadata, reachable URL: nothing to report.
2758 assert!(crate_publish_problems(&meta, true, &[], true).is_empty());
2759 }
2760
2761 #[test]
2762 fn preflight_requires_the_fields_crates_io_bakes_in() {
2763 let bare = CrateMeta {
2764 name: "x".into(),
2765 version: "0.1.0".into(),
2766 repository: None,
2767 description: None,
2768 licensed: false,
2769 };
2770 let problems = crate_publish_problems(&bare, false, &[], true);
2771 assert_eq!(problems.len(), 3, "{problems:?}");
2772 assert!(problems.iter().any(|p| p.contains("repository")));
2773 assert!(problems.iter().any(|p| p.contains("description")));
2774 assert!(problems.iter().any(|p| p.contains("license")));
2775 }
2776
2777 // A library's verify is a crate preflight, not a Gatekeeper check on a
2778 // signed bundle. Gating it on `gatekeeper` asked a Linux host for a macOS
2779 // code-signing capability it can never hold, so the step was denied before
2780 // it ran a command; the denial then surfaced as "no crates.io credentials",
2781 // which is not what went wrong. The only way to satisfy the old gate was to
2782 // declare the capability falsely in the topology.
2783 #[test]
2784 fn a_library_verify_is_not_gated_on_gatekeeper() {
2785 assert_eq!(
2786 action_for(Step::Verify, Kind::Library),
2787 Action::Build,
2788 "a crate preflight runs the build toolchain; that is what it needs",
2789 );
2790 assert_eq!(
2791 action_for(Step::Verify, Kind::App),
2792 Action::Observe(ObserveKind::Custom("gatekeeper".into())),
2793 "an app's verify still proves the bundle is signed and notarized",
2794 );
2795 }
2796
2797 // The capability the default host grant actually carries. Without this the
2798 // fix above is only true by inspection.
2799 #[test]
2800 fn a_default_host_can_run_a_library_verify_and_not_an_app_one() {
2801 let caps =
2802 ops_exec::CapabilitySet::from_tokens(["build", "package"], ["build-log", "artifact"]);
2803 assert!(caps.permits(&action_for(Step::Verify, Kind::Library)));
2804 assert!(!caps.permits(&action_for(Step::Verify, Kind::App)));
2805 }
2806
2807 // Every other step is a property of the step alone; verify is the one that
2808 // depends on what is being released.
2809 #[test]
2810 fn no_other_step_changes_with_the_kind() {
2811 for step in [
2812 Step::Checkout,
2813 Step::Prebuild,
2814 Step::Build,
2815 Step::Sign,
2816 Step::Notarize,
2817 Step::Staple,
2818 Step::Package,
2819 Step::Publish,
2820 Step::Collect,
2821 ] {
2822 assert_eq!(
2823 action_for(step, Kind::App),
2824 action_for(step, Kind::Library),
2825 "{step:?} should not depend on the kind",
2826 );
2827 }
2828 }
2829
2830 #[test]
2831 fn preflight_rejects_republishing_the_same_version() {
2832 let meta = CrateMeta {
2833 name: "makeover".into(),
2834 version: "0.10.0".into(),
2835 repository: Some("https://git.sr.ht/~maxmj/makeover".into()),
2836 description: Some("d".into()),
2837 licensed: true,
2838 };
2839 let problems =
2840 crate_publish_problems(&meta, true, &["0.9.0".into(), "0.10.0".into()], true);
2841 assert_eq!(problems.len(), 1, "{problems:?}");
2842 assert!(problems[0].contains("already published"), "{problems:?}");
2843
2844 // An unreleased version against the same history is fine.
2845 let mut next = meta.clone();
2846 next.version = "0.11.0".into();
2847 assert!(crate_publish_problems(&next, true, &["0.10.0".into()], true).is_empty());
2848 }
2849
2850 /// Missing credentials must surface at preflight, not at the upload. The
2851 /// publish step is the irreversible one and runs last, after a full build
2852 /// and verify; discovering there that cargo cannot authenticate wastes the
2853 /// whole run.
2854 #[test]
2855 fn preflight_reports_missing_credentials_up_front() {
2856 let meta = CrateMeta {
2857 name: "makeover".into(),
2858 version: "0.11.0".into(),
2859 repository: Some("https://git.sr.ht/~maxmj/makeover".into()),
2860 description: Some("d".into()),
2861 licensed: true,
2862 };
2863 // Metadata is perfect; only the token is absent.
2864 let problems = crate_publish_problems(&meta, true, &[], false);
2865 assert_eq!(problems.len(), 1, "{problems:?}");
2866 assert!(problems[0].contains("credentials"), "{problems:?}");
2867 assert!(
2868 problems[0].contains("cargo login"),
2869 "should say how to fix it"
2870 );
2871
2872 // Present: nothing to report.
2873 assert!(crate_publish_problems(&meta, true, &[], true).is_empty());
2874 }
2875
2876 #[test]
2877 fn crate_meta_reads_cargo_metadata_json() {
2878 let raw = r#"{"packages":[{"name":"makeover","version":"0.10.0",
2879 "repository":"https://git.sr.ht/~maxmj/makeover","description":"themes",
2880 "license":"MIT"}]}"#;
2881 let m = crate_meta_from_json(raw).unwrap();
2882 assert_eq!(m.name, "makeover");
2883 assert_eq!(m.version, "0.10.0");
2884 assert!(m.licensed);
2885 assert_eq!(
2886 m.repository.as_deref(),
2887 Some("https://git.sr.ht/~maxmj/makeover")
2888 );
2889
2890 // license_file alone also counts as licensed; empty strings do not
2891 // count as present.
2892 let lf = r#"{"packages":[{"name":"x","version":"0.1.0","license":"",
2893 "license_file":"LICENSE","description":""}]}"#;
2894 let m = crate_meta_from_json(lf).unwrap();
2895 assert!(m.licensed);
2896 assert!(m.description.is_none());
2897 }
2898
2899 /// Reads the ambient `HOME` rather than setting one. `set_var` is
2900 /// process-global and unsynchronized, so a test that overwrote HOME changed
2901 /// it for every other test in the binary — which is what silently disabled
2902 /// `topology::live_config_smoke` (it skips when `$HOME/.config/bento` is
2903 /// absent, and `/home/test` always is).
2904 #[test]
2905 fn expand_tilde_handles_home() {
2906 let home = PathBuf::from(std::env::var("HOME").expect("HOME is set"));
2907 assert_eq!(expand_tilde("~/Code/x"), home.join("Code/x"));
2908 assert_eq!(expand_tilde("/abs/path"), PathBuf::from("/abs/path"));
2909 }
2910
2911 // ---- artifact resolution (the M3 silent-`sh` fix) ----
2912
2913 #[test]
2914 fn resolve_artifact_match_wants_exactly_one() {
2915 // Exactly one match: the path, trimmed of the listing's line noise.
2916 assert_eq!(
2917 resolve_artifact_match(" /d/App.AppImage \n", "*.AppImage", true).unwrap(),
2918 "/d/App.AppImage"
2919 );
2920 }
2921
2922 #[test]
2923 fn resolve_artifact_match_zero_depends_on_required() {
2924 // Required + zero matches is the case the old empty-string guard caught;
2925 // keep failing it.
2926 let err = resolve_artifact_match("", "*.dmg", true).unwrap_err();
2927 assert!(err.to_string().contains("no artifact matched"), "{err}");
2928 // Optional + zero matches resolves to empty (recipe skips the collect).
2929 assert_eq!(
2930 resolve_artifact_match("\n \n", "*.deb", false).unwrap(),
2931 ""
2932 );
2933 }
2934
2935 #[test]
2936 fn resolve_artifact_match_rejects_ambiguous() {
2937 // Two matches must throw rather than silently pick one — this is the
2938 // stale-newest-mtime hole the audit flagged. Applies even when optional.
2939 for required in [true, false] {
2940 let err =
2941 resolve_artifact_match("/d/old.deb\n/d/new.deb\n", "*.deb", required).unwrap_err();
2942 let msg = err.to_string();
2943 assert!(msg.contains("ambiguous"), "{msg}");
2944 assert!(msg.contains("old.deb") && msg.contains("new.deb"), "{msg}");
2945 }
2946 }
2947
2948 #[test]
2949 fn ensure_glob_safe_allows_paths_bars_commands() {
2950 // Path and wildcard characters pass.
2951 assert!(ensure_glob_safe("~/Code/app/dist/*.AppImage").is_ok());
2952 assert!(ensure_glob_safe("/t/App_1.2.3-x86_64.dmg").is_ok());
2953 // A command substitution or separator does not.
2954 for bad in ["*.dmg; rm -rf /", "$(evil)", "a|b", "a b"] {
2955 assert!(ensure_glob_safe(bad).is_err(), "should reject {bad:?}");
2956 }
2957 }
2958
2959 // ---- version resolution ----
2960
2961 #[test]
2962 fn version_from_tauri_json_reads_version() {
2963 assert_eq!(
2964 version_from_tauri_json(r#"{"version":"0.4.2"}"#).unwrap(),
2965 "0.4.2"
2966 );
2967 assert!(version_from_tauri_json(r#"{"productName":"X"}"#).is_err());
2968 }
2969
2970 #[test]
2971 fn version_from_cargo_toml_prefers_package_then_workspace() {
2972 // A leaf crate's [package].version.
2973 assert_eq!(
2974 version_from_cargo_toml("[package]\nname = \"x\"\nversion = \"0.5.0\"\n").unwrap(),
2975 "0.5.0"
2976 );
2977 // A workspace that sets [workspace.package].version.
2978 assert_eq!(
2979 version_from_cargo_toml("[workspace.package]\nversion = \"1.2.3\"\n").unwrap(),
2980 "1.2.3"
2981 );
2982 // No version anywhere -> error, not a panic.
2983 assert!(version_from_cargo_toml("[workspace]\nmembers = []\n").is_err());
2984 }
2985
2986 #[test]
2987 fn version_from_repo_default_and_explicit_paths() {
2988 let tmp = tempfile::tempdir().unwrap();
2989 let root = tmp.path();
2990
2991 // Tauri app: default path reads src-tauri/tauri.conf.json.
2992 let tauri = root.join("tauri");
2993 std::fs::create_dir_all(tauri.join("src-tauri")).unwrap();
2994 std::fs::write(
2995 tauri.join("src-tauri/tauri.conf.json"),
2996 r#"{"version":"0.4.2"}"#,
2997 )
2998 .unwrap();
2999 assert_eq!(
3000 version_from_repo(tauri.to_str().unwrap(), None)
3001 .unwrap()
3002 .to_string(),
3003 "0.4.2"
3004 );
3005
3006 // Workspace egui app: no tauri.conf.json, explicit version_path at a member crate.
3007 let ws = root.join("ws");
3008 std::fs::create_dir_all(ws.join("crates/app")).unwrap();
3009 std::fs::write(
3010 ws.join("Cargo.toml"),
3011 "[workspace]\nmembers = [\"crates/app\"]\n",
3012 )
3013 .unwrap();
3014 std::fs::write(
3015 ws.join("crates/app/Cargo.toml"),
3016 "[package]\nname = \"app\"\nversion = \"0.5.0\"\n",
3017 )
3018 .unwrap();
3019 assert_eq!(
3020 version_from_repo(ws.to_str().unwrap(), Some("crates/app/Cargo.toml"))
3021 .unwrap()
3022 .to_string(),
3023 "0.5.0"
3024 );
3025 }
3026
3027 // ---- version-source cross-check (drift preflight) ----
3028
3029 fn ver(s: &str) -> Version {
3030 Version::parse(s).unwrap()
3031 }
3032
3033 #[test]
3034 fn version_consistency_passes_when_all_sources_agree() {
3035 let tmp = tempfile::tempdir().unwrap();
3036 let repo = tmp.path();
3037 std::fs::create_dir_all(repo.join("src-tauri")).unwrap();
3038 std::fs::write(
3039 repo.join("src-tauri/tauri.conf.json"),
3040 r#"{"version":"0.5.0"}"#,
3041 )
3042 .unwrap();
3043 std::fs::write(
3044 repo.join("Cargo.toml"),
3045 "[package]\nname = \"app\"\nversion = \"0.5.0\"\n",
3046 )
3047 .unwrap();
3048 check_version_consistency(repo.to_str().unwrap(), None, &ver("0.5.0")).unwrap();
3049 }
3050
3051 #[test]
3052 fn version_consistency_flags_tauri_vs_cargo_drift() {
3053 // The concrete finding: tauri.conf.json bumped to 0.5.0 but the root
3054 // Cargo.toml left at 0.4.0. version_from_repo (one file) would miss it.
3055 let tmp = tempfile::tempdir().unwrap();
3056 let repo = tmp.path();
3057 std::fs::create_dir_all(repo.join("src-tauri")).unwrap();
3058 std::fs::write(
3059 repo.join("src-tauri/tauri.conf.json"),
3060 r#"{"version":"0.5.0"}"#,
3061 )
3062 .unwrap();
3063 std::fs::write(
3064 repo.join("Cargo.toml"),
3065 "[package]\nname = \"app\"\nversion = \"0.4.0\"\n",
3066 )
3067 .unwrap();
3068 let err =
3069 check_version_consistency(repo.to_str().unwrap(), None, &ver("0.5.0")).unwrap_err();
3070 let msg = format!("{err:#}");
3071 assert!(msg.contains("Cargo.toml says 0.4.0"), "{msg}");
3072 }
3073
3074 #[test]
3075 fn version_consistency_flags_explicit_version_the_repo_does_not_reflect() {
3076 let tmp = tempfile::tempdir().unwrap();
3077 let repo = tmp.path();
3078 std::fs::create_dir_all(repo.join("src-tauri")).unwrap();
3079 std::fs::write(
3080 repo.join("src-tauri/tauri.conf.json"),
3081 r#"{"version":"0.5.0"}"#,
3082 )
3083 .unwrap();
3084 let err =
3085 check_version_consistency(repo.to_str().unwrap(), None, &ver("9.9.9")).unwrap_err();
3086 assert!(format!("{err:#}").contains("building 9.9.9"));
3087 }
3088
3089 #[test]
3090 fn version_consistency_single_source_never_invents_drift() {
3091 // A virtual-workspace root Cargo.toml (no version) alongside the member
3092 // crate the version_path points at: only one real source, so no drift.
3093 let tmp = tempfile::tempdir().unwrap();
3094 let repo = tmp.path();
3095 std::fs::create_dir_all(repo.join("crates/app")).unwrap();
3096 std::fs::write(
3097 repo.join("Cargo.toml"),
3098 "[workspace]\nmembers = [\"crates/app\"]\n",
3099 )
3100 .unwrap();
3101 std::fs::write(
3102 repo.join("crates/app/Cargo.toml"),
3103 "[package]\nname = \"app\"\nversion = \"0.5.0\"\n",
3104 )
3105 .unwrap();
3106 check_version_consistency(
3107 repo.to_str().unwrap(),
3108 Some("crates/app/Cargo.toml"),
3109 &ver("0.5.0"),
3110 )
3111 .unwrap();
3112 }
3113
3114 // ---- artifact filename version assertion + hashing ----
3115
3116 #[test]
3117 fn versions_in_filename_extracts_only_real_semvers() {
3118 assert_eq!(
3119 versions_in_filename("GoingsOn_0.5.0_aarch64.dmg"),
3120 vec![ver("0.5.0")]
3121 );
3122 assert_eq!(
3123 versions_in_filename("AudioFiles-0.4.0-x86_64.AppImage"),
3124 vec![ver("0.4.0")]
3125 );
3126 // No three-part token ⇒ nothing (an updater manifest, a bare signature).
3127 assert!(versions_in_filename("latest.json").is_empty());
3128 assert!(versions_in_filename("app.sig").is_empty());
3129 }
3130
3131 #[test]
3132 fn assert_artifact_version_rejects_a_stale_artifact() {
3133 // The 0.4.0 file sitting in the output dir against a 0.5.0 build.
3134 let err =
3135 assert_artifact_version("AudioFiles-0.4.0-x86_64.AppImage", &ver("0.5.0")).unwrap_err();
3136 assert!(format!("{err:#}").contains("stale artifact"), "{err:#}");
3137 // The matching version passes, and a versionless file is not asserted.
3138 assert_artifact_version("GoingsOn_0.5.0_aarch64.dmg", &ver("0.5.0")).unwrap();
3139 assert_artifact_version("latest.json", &ver("0.5.0")).unwrap();
3140 }
3141
3142 /// The comparison that decides whether a binary can exec on the box that is
3143 /// about to be restarted onto it. Both sides are parsed out of text a tool
3144 /// printed, so both parsers are worth pinning: fw13 tracks a newer glibc
3145 /// than the Ubuntu 24.04 host in Hetzner, and getting this backwards means a
3146 /// dead unit rather than a failed step.
3147 #[test]
3148 fn glibc_versions_parse_from_what_the_tools_actually_print() {
3149 // `objdump -T | grep -o 'GLIBC_[0-9.]*'` output: highest wins, and the
3150 // comparison is numeric (2.9 must not beat 2.34 lexically).
3151 let objdump = "GLIBC_2.2.5\nGLIBC_2.34\nGLIBC_2.9\nGLIBC_2.17\n";
3152 assert_eq!(max_glibc_symbol(objdump), Some((2, 34)));
3153 // A static binary references none: nothing to check.
3154 assert_eq!(max_glibc_symbol(""), None);
3155
3156 // `ldd --version` first line, however the distro decorates it.
3157 assert_eq!(
3158 glibc_from_ldd("ldd (Ubuntu GLIBC 2.39-0ubuntu8.8) 2.39\nCopyright...\n"),
3159 Some((2, 39))
3160 );
3161 assert_eq!(
3162 glibc_from_ldd("ldd (GNU libc) 2.41\nCopyright (C) 2025\n"),
3163 Some((2, 41))
3164 );
3165 assert_eq!(glibc_from_ldd(""), None);
3166 }
3167
3168 /// A binary needing MORE than the host has is the failure this check exists
3169 /// for; equal and less are both fine (glibc symbol versioning is backward
3170 /// compatible, so an older requirement runs on a newer host).
3171 #[test]
3172 fn glibc_requirement_is_satisfied_by_equal_or_newer_only() {
3173 let needs = max_glibc_symbol("GLIBC_2.41").unwrap();
3174 assert!(needs > glibc_from_ldd("ldd (Ubuntu GLIBC 2.39) 2.39").unwrap());
3175 assert!(needs <= glibc_from_ldd("ldd (GNU libc) 2.41").unwrap());
3176 assert!(needs <= glibc_from_ldd("ldd (GNU libc) 2.42").unwrap());
3177 assert!(needs <= glibc_from_ldd("ldd (GNU libc) 3.0").unwrap());
3178 }
3179
3180 /// Every deploy host function fails with the app's KIND as the reason when
3181 /// there is no destination, rather than with a missing-host error from
3182 /// somewhere deeper. A recipe calling `deploy()` on a library is a recipe
3183 /// written against the wrong kind, and the message should say so.
3184 #[tokio::test]
3185 async fn deploy_host_fns_explain_a_missing_destination_by_kind() {
3186 let dir = tempfile::tempdir().unwrap();
3187 let cfg = Arc::new(Config::for_tests(dir.path()));
3188 let pool = crate::db::open(&cfg.db_path).await.unwrap();
3189 let ctx = Arc::new(RecipeCtx::new(
3190 AppId::new("demo"),
3191 Version::parse("0.1.0").unwrap(),
3192 "linux/x86_64".parse().unwrap(),
3193 "fw13".into(),
3194 "local".into(),
3195 "v0.1.0".into(),
3196 "/tmp".into(),
3197 vec![],
3198 Kind::Library,
3199 1,
3200 Arc::new(std::collections::HashMap::new()),
3201 Arc::new(std::collections::HashMap::new()),
3202 None,
3203 pool,
3204 crate::events::channel(),
3205 cfg,
3206 Arc::new(OtaRegistry::standard("https://makenot.work")),
3207 tokio::runtime::Handle::current(),
3208 Arc::new(AtomicBool::new(false)),
3209 None,
3210 ));
3211 let engine = build_engine(&ctx);
3212 for call in [
3213 "deploy_host()",
3214 "service_name()",
3215 "install_path()",
3216 "health_url()",
3217 r#"deploy("/tmp/x")"#,
3218 ] {
3219 let err = engine.eval::<String>(call).unwrap_err().to_string();
3220 assert!(
3221 err.contains("library") && err.contains("no deploy destination"),
3222 "`{call}` must fail on the kind, got: {err}"
3223 );
3224 }
3225 }
3226
3227 /// A service host is addressed on the DEPLOY plane whatever step is open.
3228 ///
3229 /// The subtle one. Actions are normally derived from the step, which is
3230 /// right for a build host — the step is what that host is being asked to do.
3231 /// A service host is granted `deploy`/`restart` and must never be granted
3232 /// `build`, so the same rule would have `glibc_check` ask it for `build`
3233 /// during a `verify` step and get denied for a reason unrelated to what was
3234 /// attempted. `verify` is the step that check belongs in, so without this
3235 /// routing the glibc gate cannot run at all.
3236 #[tokio::test]
3237 async fn a_service_host_is_addressed_on_the_deploy_plane_in_any_step() {
3238 let dir = tempfile::tempdir().unwrap();
3239 let cfg = Arc::new(Config::for_tests(dir.path()));
3240 let pool = crate::db::open(&cfg.db_path).await.unwrap();
3241 sqlx::query(
3242 "INSERT INTO builds (id, app, version, status, created_at) \
3243 VALUES (1, 'demo', '0.1.0', 'running', '2026-07-30T00:00:00Z')",
3244 )
3245 .execute(&pool)
3246 .await
3247 .unwrap();
3248 sqlx::query(
3249 "INSERT INTO target_runs (id, build_id, app, version, target, status, started_at) \
3250 VALUES (1, 1, 'demo', '0.1.0', 'linux/x86_64', 'running', '2026-07-30T00:00:00Z')",
3251 )
3252 .execute(&pool)
3253 .await
3254 .unwrap();
3255
3256 let deploy = crate::topology::DeployTarget {
3257 target: "linux/x86_64".parse().unwrap(),
3258 host: "local".into(),
3259 port: None,
3260 install_path: "/usr/local/bin/demo".into(),
3261 service: "demo.service".into(),
3262 health_url: None,
3263 };
3264 let mut execs: crate::state::ExecutorMap = std::collections::HashMap::new();
3265 execs.insert("local".into(), crate::state::build_deploy_executor(&deploy));
3266 // The service host's grant is exactly deploy + restart. If this ever
3267 // widens to include `build`, the test below stops proving anything.
3268 assert!(!execs["local"].capabilities().permits(&Action::Build));
3269 assert!(execs["local"].capabilities().permits(&Action::Deploy));
3270
3271 let ctx = Arc::new(RecipeCtx::new(
3272 AppId::new("demo"),
3273 Version::parse("0.1.0").unwrap(),
3274 "linux/x86_64".parse().unwrap(),
3275 "fw13".into(),
3276 "local".into(),
3277 "v0.1.0".into(),
3278 "/tmp".into(),
3279 vec![],
3280 Kind::Service,
3281 1,
3282 Arc::new(execs),
3283 Arc::new(std::collections::HashMap::new()),
3284 Some(deploy),
3285 pool,
3286 crate::events::channel(),
3287 cfg,
3288 Arc::new(OtaRegistry::standard("https://makenot.work")),
3289 tokio::runtime::Handle::current(),
3290 Arc::new(AtomicBool::new(false)),
3291 None,
3292 ));
3293
3294 let ctx_blocking = ctx.clone();
3295 tokio::task::spawn_blocking(move || {
3296 // `verify` on a service derives Action::Build — which the service
3297 // host does not grant. The command must still run.
3298 ctx_blocking.begin_step(Step::Verify).unwrap();
3299 assert_eq!(
3300 action_for(Step::Verify, Kind::Service),
3301 Action::Build,
3302 "the step's own action is the one that would be denied",
3303 );
3304 let (code, out) = ctx_blocking
3305 .run("local", "echo reached-the-service-host")
3306 .expect("a service host must be reachable during a verify step");
3307 assert_eq!(code, 0, "{out}");
3308 assert!(out.contains("reached-the-service-host"), "{out}");
3309 })
3310 .await
3311 .unwrap();
3312 }
3313
3314 /// A step that finalized `Failed` bars the deploy, exactly as it bars a
3315 /// publish. Without this, a recipe that inspects `sh(...).code` and carries
3316 /// on regardless still lands a binary on a production host — the precise
3317 /// hazard a pipeline exists to remove. The check is the ledger, not the
3318 /// control flow, so it holds whether or not the recipe noticed.
3319 #[tokio::test]
3320 async fn a_failed_step_bars_the_deploy() {
3321 let dir = tempfile::tempdir().unwrap();
3322 let cfg = Arc::new(Config::for_tests(dir.path()));
3323 let pool = crate::db::open(&cfg.db_path).await.unwrap();
3324 let deploy = crate::topology::DeployTarget {
3325 target: "linux/x86_64".parse().unwrap(),
3326 host: "local".into(),
3327 port: None,
3328 install_path: "/usr/local/bin/demo".into(),
3329 service: "demo.service".into(),
3330 health_url: None,
3331 };
3332 // A real build + target run, so the step rows this test finalizes have
3333 // the parents the schema requires.
3334 sqlx::query(
3335 "INSERT INTO builds (id, app, version, status, created_at) \
3336 VALUES (1, 'demo', '0.1.0', 'running', '2026-07-30T00:00:00Z')",
3337 )
3338 .execute(&pool)
3339 .await
3340 .unwrap();
3341 sqlx::query(
3342 "INSERT INTO target_runs (id, build_id, app, version, target, status, started_at) \
3343 VALUES (1, 1, 'demo', '0.1.0', 'linux/x86_64', 'running', '2026-07-30T00:00:00Z')",
3344 )
3345 .execute(&pool)
3346 .await
3347 .unwrap();
3348
3349 let mut execs: crate::state::ExecutorMap = std::collections::HashMap::new();
3350 execs.insert("local".into(), crate::state::build_deploy_executor(&deploy));
3351 let ctx = Arc::new(RecipeCtx::new(
3352 AppId::new("demo"),
3353 Version::parse("0.1.0").unwrap(),
3354 "linux/x86_64".parse().unwrap(),
3355 "fw13".into(),
3356 "local".into(),
3357 "v0.1.0".into(),
3358 "/tmp".into(),
3359 vec![],
3360 Kind::Service,
3361 1,
3362 Arc::new(execs),
3363 Arc::new(std::collections::HashMap::new()),
3364 Some(deploy),
3365 pool,
3366 crate::events::channel(),
3367 cfg,
3368 Arc::new(OtaRegistry::standard("https://makenot.work")),
3369 tokio::runtime::Handle::current(),
3370 Arc::new(AtomicBool::new(false)),
3371 None,
3372 ));
3373
3374 // A gate ran, failed, and the recipe did not abort — the swallowed
3375 // failure. Finalizing it is what puts it in the ledger.
3376 let ctx_blocking = ctx.clone();
3377 tokio::task::spawn_blocking(move || {
3378 ctx_blocking.begin_step(Step::Prebuild).unwrap();
3379 ctx_blocking.fail_current_step();
3380 ctx_blocking.finish_step(Status::Ok).unwrap();
3381
3382 let err = ctx_blocking.deploy("/tmp/demo").unwrap_err().to_string();
3383 assert!(
3384 err.contains("refusing to deploy") && err.contains("prebuild"),
3385 "must refuse and name the failed step, got: {err}"
3386 );
3387 })
3388 .await
3389 .unwrap();
3390 }
3391
3392 #[test]
3393 fn every_step_has_a_nonzero_default_budget() {
3394 // A zero/missing budget would deadline-fail a step instantly. Cover the
3395 // whole matrix so a new Step variant can't silently get a 0 budget.
3396 for step in Step::ALL {
3397 assert!(
3398 default_step_budget(step) >= std::time::Duration::from_mins(1),
3399 "{step} budget must be a sane ceiling",
3400 );
3401 }
3402 }
3403
3404 #[test]
3405 fn sha256_file_is_lowercase_hex_of_contents() {
3406 let tmp = tempfile::tempdir().unwrap();
3407 let f = tmp.path().join("a.bin");
3408 std::fs::write(&f, b"abc").unwrap();
3409 // Known SHA-256 of "abc".
3410 assert_eq!(
3411 sha256_file(&f).unwrap(),
3412 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
3413 );
3414 }
3415
3416 // ---- publish step-success gate ----
3417
3418 fn target(s: &str) -> Target {
3419 s.parse().unwrap()
3420 }
3421
3422 #[test]
3423 fn publish_gate_blocks_macos_without_verification() {
3424 // Never verified -> blocked, with a message pointing at verify_gatekeeper.
3425 let err = PublishAuthority::prove(target("macos/aarch64"), &[], None).unwrap_err();
3426 assert!(format!("{err:#}").contains("never verified"), "{err:#}");
3427 }
3428
3429 #[test]
3430 fn publish_gate_blocks_macos_when_gatekeeper_rejected() {
3431 let err = PublishAuthority::prove(target("macos/aarch64"), &[], Some(false)).unwrap_err();
3432 assert!(
3433 format!("{err:#}").contains("Gatekeeper rejected"),
3434 "{err:#}"
3435 );
3436 }
3437
3438 #[test]
3439 fn publish_gate_allows_macos_when_gatekeeper_accepted() {
3440 PublishAuthority::prove(target("macos/aarch64"), &[], Some(true)).unwrap();
3441 // iOS is gated the same way.
3442 PublishAuthority::prove(target("ios/universal"), &[], Some(true)).unwrap();
3443 assert!(PublishAuthority::prove(target("ios/universal"), &[], None).is_err());
3444 }
3445
3446 #[test]
3447 fn publish_gate_does_not_require_gatekeeper_for_non_apple_targets() {
3448 // Linux/Windows aren't notarized; no gatekeeper proof needed.
3449 PublishAuthority::prove(target("linux/x86_64"), &[], None).unwrap();
3450 PublishAuthority::prove(target("windows/x86_64"), &[], None).unwrap();
3451 }
3452
3453 #[test]
3454 fn publish_gate_blocks_when_any_prior_step_failed() {
3455 // A failed step bars publish on every target, even a verified macOS one.
3456 let err =
3457 PublishAuthority::prove(target("linux/x86_64"), &[Step::Build], None).unwrap_err();
3458 assert!(
3459 format!("{err:#}").contains("prior step(s) failed"),
3460 "{err:#}"
3461 );
3462 assert!(
3463 format!("{err:#}").contains("build"),
3464 "names the failed step: {err:#}"
3465 );
3466
3467 let err = PublishAuthority::prove(target("macos/aarch64"), &[Step::Sign], Some(true))
3468 .unwrap_err();
3469 assert!(
3470 format!("{err:#}").contains("prior step(s) failed"),
3471 "{err:#}"
3472 );
3473 }
3474
3475 #[test]
3476 fn notary_accepted_parses_status_field() {
3477 assert!(notary_accepted(
3478 r#"{"id":"abc","status":"Accepted","message":"ok"}"#
3479 ));
3480 // Embedded in shell-sourcing noise: the object is isolated and parsed.
3481 assert!(notary_accepted(
3482 "sourcing env...\n{\n \"status\": \"Accepted\"\n}\nbye"
3483 ));
3484 // Whitespace variant that a tight substring `"status":"Accepted"` misses.
3485 assert!(notary_accepted(r#"{ "status" : "Accepted" }"#));
3486 }
3487
3488 #[test]
3489 fn notary_accepted_rejects_non_accepted_and_garbage() {
3490 assert!(!notary_accepted(r#"{"status":"Invalid"}"#));
3491 assert!(!notary_accepted(r#"{"status":"In Progress"}"#));
3492 assert!(!notary_accepted("no json here"));
3493 assert!(!notary_accepted("")); // empty / truncated -> fail closed
3494 // A truncated tail whose opening brace was cut off cannot parse -> closed.
3495 assert!(!notary_accepted(r#""status":"Accepted"}"#));
3496 // The literal appearing inside an error string must NOT pass as success.
3497 assert!(!notary_accepted(
3498 r#"{"status":"Invalid","message":"expected status:Accepted"}"#
3499 ));
3500 }
3501
3502 /// Porcelain paths are repo-root relative, so an app that lives in a
3503 /// subdirectory can tell its own files from a sibling product's. Both get
3504 /// listed — the checkout was repo-wide and so is what blocked it — but only
3505 /// the sibling's is marked, because that is the one the app-scoped dirty
3506 /// gate just reported as clean.
3507 #[test]
3508 fn dirty_paths_mark_the_files_that_are_not_this_app_s() {
3509 let status = " M server/Cargo.lock\n M pom/src/main.rs\n";
3510 let out = dirty_paths_blocking_checkout(status, "pom/\n").unwrap();
3511 assert!(
3512 out.contains("server/Cargo.lock (outside pom/, not part of this app)"),
3513 "{out}"
3514 );
3515 assert!(out.contains("pom/src/main.rs"), "{out}");
3516 assert!(
3517 !out.contains("pom/src/main.rs (outside"),
3518 "the app's own file is not marked: {out}"
3519 );
3520 }
3521
3522 /// A repo holding one product has no prefix, so nothing is "outside" it.
3523 /// A rename is reported as `old -> new`, and the destination is the path
3524 /// that exists in the working tree to go and look at.
3525 #[test]
3526 fn dirty_paths_handle_a_single_product_repo_and_renames() {
3527 let out = dirty_paths_blocking_checkout("R a.rs -> b.rs\n M c.rs\n", "").unwrap();
3528 assert_eq!(out, "b.rs\n c.rs");
3529 assert!(dirty_paths_blocking_checkout("", "pom/").is_none());
3530 assert!(dirty_paths_blocking_checkout("\n\n", "pom/").is_none());
3531 }
3532
3533 /// With the files in hand the message names them; with a clean tree it has
3534 /// nothing to name and keeps the question. An absent tag is a different
3535 /// failure and neither says anything about the working tree.
3536 #[test]
3537 fn checkout_failure_reason_names_files_when_it_has_them() {
3538 let named = checkout_failure_reason("pom-v0.4.3", true, Some("server/Cargo.lock"));
3539 assert!(named.contains("server/Cargo.lock"), "{named}");
3540 assert!(
3541 !named.contains("uncommitted changes in the checkout?"),
3542 "no guessing once the files are known: {named}"
3543 );
3544 let guess = checkout_failure_reason("pom-v0.4.3", true, None);
3545 assert!(
3546 guess.contains("uncommitted changes in the checkout?"),
3547 "{guess}"
3548 );
3549 let missing = checkout_failure_reason("pom-v0.4.3", false, Some("server/Cargo.lock"));
3550 assert!(missing.contains("does not exist"), "{missing}");
3551 assert!(!missing.contains("Cargo.lock"), "{missing}");
3552 }
3553 }
3554