zlayer-builder 0.14.1

Dockerfile parsing and buildah-based container image building
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! `build_image` implementation for the buildah-sidecar backend.
//!
//! Translates a [`BuildOptions`] + parsed [`Dockerfile`] into a
//! [`proto::BuildRequest`], opens the server-streamed `Build` RPC against
//! the sidecar gRPC service, and translates each [`proto::BuildEvent`] into
//! a [`BuildEvent`] for the TUI. The final [`BuiltImage`] is constructed
//! from the terminal `BuildFinished` event.

use std::io::Write as _;
use std::path::Path;
use std::sync::mpsc::Sender;

use tokio_stream::StreamExt;
use tonic::Request;

use crate::backend::buildah_sidecar::proto;
use crate::backend::progress::InstructionProgress;
use crate::builder::{BuildOptions, BuiltImage, PullBaseMode};
use crate::dockerfile::{
    expand_dockerfile, forward_build_arg_env, merge_default_cache_mounts, render_dockerfile,
    Dockerfile, Instruction, RunMount,
};
use crate::error::{BuildError, Result};
use crate::tui::{BuildEvent, PlannedStage};

use super::BuildahSidecarBackend;

impl BuildahSidecarBackend {
    /// Server-stream the build through the sidecar and assemble a
    /// [`BuiltImage`]. Wired up from the `BuildBackend::build_image` trait
    /// method on [`BuildahSidecarBackend`] in `mod.rs`.
    pub(super) async fn build_image_impl(
        &self,
        context: &Path,
        dockerfile: &Dockerfile,
        options: &BuildOptions,
        event_tx: Option<Sender<BuildEvent>>,
    ) -> Result<BuiltImage> {
        // Emit as a plain event (not an entered span guard): an `EnteredSpan` is
        // `!Send` and would poison the `Send` bound on `build_image` when held
        // across the `.await`s below.
        tracing::info!(
            platform = ?options.platform,
            dockerfile = ?options.dockerfile,
            "buildd build started"
        );

        let started_at = std::time::Instant::now();
        let live = self.lifecycle.ensure().await?;
        let mut client = live.client();

        // Render ZLayer's IR (ZImagefile conversion + `${VAR}` expansion +
        // default-cache-mount merge) to canonical Dockerfile text and ship THAT
        // to the sidecar, instead of a raw on-disk Dockerfile path. The
        // `NamedTempFile` is held in this scope so it outlives the streamed
        // `Build` RPC below — dropping it deletes the file the sidecar reads.
        let (request, _rendered) = build_request_from(context, dockerfile, options, self.config())?;

        let stream = client
            .build(Request::new(request))
            .await
            .map_err(|s| grpc_err(&s))?
            .into_inner();

        let built = consume_build_stream(stream, event_tx, dockerfile, options, started_at).await?;

        // Push if requested. Mirrors the native CLI backend
        // (`backend/buildah.rs::build_image` step 6): `buildah build` only
        // commits the image locally, so `--push` must fan out an explicit
        // remote push per tag through the sidecar's `Push` RPC.
        if options.push {
            for tag in &options.tags {
                self.push_image_impl(tag, options.registry_auth.as_ref())
                    .await?;
                tracing::info!("Pushed image: {}", tag);
            }
        }

        Ok(built)
    }
}

/// Translate a [`BuildOptions`] + parsed [`Dockerfile`] into a
/// [`proto::BuildRequest`]. Every field on the proto schema is set
/// explicitly so the wire payload is deterministic.
///
/// The parsed [`Dockerfile`] IR is expanded (build-args + default cache mounts)
/// and rendered back to canonical Dockerfile text, then written to a temp file
/// INSIDE the build `context` dir so the existing `translate_context_path`
/// prefix-rewrite maps it correctly for a cross-namespace VZ sidecar. The
/// returned [`tempfile::NamedTempFile`] MUST be kept alive by the caller until
/// the streamed `Build` RPC completes — dropping it deletes the file the
/// sidecar reads.
fn build_request_from(
    context: &Path,
    dockerfile: &Dockerfile,
    options: &BuildOptions,
    config: &zlayer_types::builder::SidecarConfig,
) -> Result<(proto::BuildRequest, tempfile::NamedTempFile)> {
    // Resolve the path the *sidecar* sees for the context. For a same-host
    // sidecar this is the host path verbatim; for a cross-namespace sidecar
    // (e.g. `zlayer-buildd` inside a VZ-Linux container) we rewrite the
    // host-side mount prefix to the in-guest mount prefix.
    let context_dir = translate_context_path(context, config);

    // Build the final IR exactly like the native CLI backend
    // (`backend/buildah.rs::build_image`): merge pipeline vars into build args
    // (sorted/deterministic), expand the Dockerfile, merge default cache mounts,
    // then render canonical text.
    let mut effective_build_args = std::collections::BTreeMap::<String, String>::new();
    for (k, v) in &options.build_args {
        effective_build_args.insert(k.clone(), v.clone());
    }
    for (k, v) in &options.pipeline_vars {
        effective_build_args.insert(k.clone(), v.clone());
    }
    // Docker `--build-arg FOO` (no `=value`) semantics: a build-arg DECLARED in
    // the IR (`ARG`) but left empty/unset is populated from a matching non-empty
    // process-env var. Mirrors `backend/buildah.rs::build_image`.
    forward_build_arg_env(dockerfile, &mut effective_build_args);
    let expand_args: std::collections::HashMap<String, String> = effective_build_args
        .iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();

    let mut ir = expand_dockerfile(dockerfile, &expand_args);
    merge_default_cache_mounts(&mut ir, options);
    let text = render_dockerfile(&ir);

    // Write the rendered Dockerfile INSIDE the context dir so the
    // cross-namespace prefix-rewrite below maps it correctly. The handle is
    // returned to the caller and held across the RPC.
    let mut rendered = tempfile::Builder::new()
        .prefix("zlayer-rendered-")
        .tempfile_in(context)
        .map_err(BuildError::from)?;
    rendered
        .write_all(text.as_bytes())
        .map_err(BuildError::from)?;
    rendered.flush().map_err(BuildError::from)?;

    let dockerfile_path = translate_context_path(rendered.path(), config);

    // Collect distinct RUN secret/ssh ids from the final IR. The Go sidecar
    // consumes these as buildah `--secret` / `--ssh` specs
    // (`bin/zlayer-buildd/internal/server/build.go`).
    let secrets = collect_secret_ids(&ir);
    let ssh = collect_ssh_ids(&ir);

    let platforms = options
        .platform
        .as_deref()
        .map(|s| {
            s.split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(String::from)
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    let cache_from = options.cache_from.clone().unwrap_or_default();
    let cache_to = options.cache_to.clone().unwrap_or_default();

    // ARG bindings: the build_args (already merged with pipeline_vars above) so
    // `${VAR}` references reach the sidecar as ARG bindings. The proto field is
    // an unordered map, so a HashMap is the natural conversion target.
    let build_args: std::collections::HashMap<String, String> =
        effective_build_args.into_iter().collect();

    let pull_policy = pull_policy_str(options.pull).to_string();
    let format = options.format.clone().unwrap_or_default();
    let target_stage = options.target.clone().unwrap_or_default();

    let request = proto::BuildRequest {
        request_id: String::new(),
        context_dir,
        dockerfile_paths: vec![dockerfile_path],
        tags: options.tags.clone(),
        platforms,
        build_args,
        secrets,
        ssh,
        target_stage,
        host_network: options.host_network,
        cache_from,
        cache_to,
        no_cache: options.no_cache,
        squash: options.squash,
        layers: options.layers,
        format,
        pull_policy,
        labels: Vec::new(),
        annotations: Vec::new(),
        add_hosts: Vec::new(),
        envs: Vec::new(),
        shm_size: String::new(),
        ulimits: Vec::new(),
        volumes: Vec::new(),
        source_date_epoch: 0,
        rewrite_timestamp: false,
        isolation: detect_default_isolation(),
    };

    Ok((request, rendered))
}

/// Collect the distinct `RUN --mount=type=secret` ids across the whole IR, in
/// first-seen order, formatted as buildah `--secret` specs.
///
/// The IR only carries the secret `id` (not the host `src`/`env` source — that
/// is supplied out-of-band by the operator), so each spec is the minimal
/// `id=<name>` form buildah accepts, which defaults the source to the
/// like-named environment variable. The Go sidecar passes these straight into
/// `define.CommonBuildOptions.Secrets` (`req.GetSecrets()`).
fn collect_secret_ids(df: &Dockerfile) -> Vec<String> {
    let mut specs: Vec<String> = Vec::new();
    for stage in &df.stages {
        for instruction in &stage.instructions {
            let Instruction::Run(run) = instruction else {
                continue;
            };
            for mount in &run.mounts {
                if let RunMount::Secret { id, .. } = mount {
                    let spec = format!("id={id}");
                    if !specs.contains(&spec) {
                        specs.push(spec);
                    }
                }
            }
        }
    }
    specs
}

/// Collect the distinct `RUN --mount=type=ssh` ids across the whole IR, in
/// first-seen order, so the sidecar can pass one `--ssh <id>` per id (mirrors
/// `backend/buildah.rs::collect_ssh_ids`).
///
/// A bare `RUN --mount=type=ssh` (no `id=`) maps to the conventional `default`
/// id that `buildah build --ssh default` authorizes.
fn collect_ssh_ids(df: &Dockerfile) -> Vec<String> {
    let mut ids: Vec<String> = Vec::new();
    for stage in &df.stages {
        for instruction in &stage.instructions {
            let Instruction::Run(run) = instruction else {
                continue;
            };
            for mount in &run.mounts {
                if let RunMount::Ssh { id, .. } = mount {
                    let id = id.clone().unwrap_or_else(|| "default".to_string());
                    if !ids.contains(&id) {
                        ids.push(id);
                    }
                }
            }
        }
    }
    ids
}

/// Rewrite a host-side path to the path the sidecar sees, honoring the
/// optional `context_mount` prefix translation on [`SidecarConfig`].
///
/// With no `context_mount` (same-host sidecar) the path is returned
/// verbatim. With `Some((host_prefix, guest_prefix))` any path under
/// `host_prefix` has that prefix swapped for `guest_prefix`; paths outside
/// the mount are returned unchanged (the caller is responsible for keeping
/// the context inside the shared mount).
fn translate_context_path(path: &Path, config: &zlayer_types::builder::SidecarConfig) -> String {
    if let Some((host_prefix, guest_prefix)) = config.context_mount.as_ref() {
        if let Ok(rel) = path.strip_prefix(host_prefix) {
            return guest_prefix.join(rel).to_string_lossy().into_owned();
        }
    }
    path.to_string_lossy().into_owned()
}

/// Pick the safe isolation backend for the *current process*.
///
/// On Unix, when the caller is unprivileged (real uid != 0), we send
/// `"chroot"` so the sidecar uses buildah's chroot isolation. The chroot
/// path does not need an OCI runtime (runc/crun) and works correctly
/// inside the user namespace that the sidecar's
/// `unshare.MaybeReexecUsingUserNamespace` creates.
///
/// When running as real root, we send the empty string so the sidecar
/// picks buildah's default (= OCI on Linux), which is faster but requires
/// runc/crun on PATH.
///
/// Non-Unix targets return the empty string (the sidecar only supports
/// Unix; this matches the existing behavior).
fn detect_default_isolation() -> String {
    #[cfg(unix)]
    {
        if nix::unistd::Uid::current().is_root() {
            String::new()
        } else {
            "chroot".to_string()
        }
    }
    #[cfg(not(unix))]
    {
        String::new()
    }
}

/// Map [`PullBaseMode`] to the string the sidecar / buildah expect for the
/// `--pull` flag.
///
/// `PullBaseMode::Newer` is documented as "only pull if the registry has a
/// newer version", which is exactly `buildah --pull=ifnewer`.
fn pull_policy_str(mode: PullBaseMode) -> &'static str {
    match mode {
        PullBaseMode::Never => "never",
        PullBaseMode::Always => "always",
        PullBaseMode::Newer => "ifnewer",
    }
}

/// Consume the streamed `BuildEvent`s from the sidecar, fan out
/// [`BuildEvent`]s to the optional TUI sender, and assemble the final
/// [`BuiltImage`] from the terminal `BuildFinished` event.
async fn consume_build_stream(
    mut stream: tonic::Streaming<proto::BuildEvent>,
    event_tx: Option<Sender<BuildEvent>>,
    dockerfile: &Dockerfile,
    options: &BuildOptions,
    started_at: std::time::Instant,
) -> Result<BuiltImage> {
    let total_stages = dockerfile.stages.len();
    let total_instructions: usize = dockerfile.stages.iter().map(|s| s.instructions.len()).sum();

    if let Some(tx) = &event_tx {
        let _ = tx.send(BuildEvent::BuildStarted {
            total_stages,
            total_instructions,
        });
    }

    // Pre-fill the instruction list from the parsed Dockerfile. The sidecar's
    // Go buildd only streams `Log` lines (never per-instruction events), so
    // without this the TUI would sit on "Waiting for build to start...". The
    // instruction text is rendered with `format!("{instruction:?}")` to match
    // the native backend (`backend/buildah.rs`) byte-for-byte.
    let planned_stages: Vec<PlannedStage> = dockerfile
        .stages
        .iter()
        .map(|stage| PlannedStage {
            name: stage.name.clone(),
            base_image: stage.base_image.to_string(),
            instructions: stage
                .instructions
                .iter()
                .map(|instruction| format!("{instruction:?}"))
                .collect(),
        })
        .collect();

    // Flattened progress cursor over (stage_idx, inst_idx) in Dockerfile order.
    // As buildah prints commit markers (`--> <hex>` / `--> Using cache <hex>`)
    // we advance this cursor and translate each marker into the matching
    // InstructionComplete / next InstructionStarted / StageComplete events.
    let mut progress = InstructionProgress::from_planned_stages(&planned_stages);

    if let Some(tx) = &event_tx {
        let _ = tx.send(BuildEvent::BuildPlan {
            stages: planned_stages,
        });
        // Mark the first instruction of the first non-empty stage as Running.
        for event in progress.start_first() {
            let _ = tx.send(event);
        }
    }

    let mut final_image_id: Option<String> = None;
    let mut final_manifest_ref: Option<String> = None;
    let mut final_error: Option<String> = None;

    // Longer than a normal base-image pull, finite so a fuse-overlayfs deadlock can't hang forever.
    #[allow(clippy::items_after_statements)]
    const STALL: std::time::Duration = std::time::Duration::from_secs(120);

    loop {
        match tokio::time::timeout(STALL, stream.next()).await {
            Err(_elapsed) => {
                tracing::error!(
                    stall_secs = STALL.as_secs(),
                    "buildd build stream stalled — no BuildEvent; aborting (likely fuse-overlayfs/virtiofs deadlock)"
                );
                return Err(BuildError::BuildahExecution {
                    command: "buildah-sidecar build".to_string(),
                    exit_code: 1,
                    stderr: format!(
                        "sidecar build stream stalled for {}s with no BuildEvent (likely fuse-overlayfs/virtiofs deadlock); aborting",
                        STALL.as_secs()
                    ),
                });
            }
            Ok(None) => break,
            Ok(Some(message)) => {
                let event = message.map_err(|s| grpc_err(&s))?;
                let Some(ev) = event.event else {
                    continue;
                };
                dispatch_event(
                    ev,
                    event_tx.as_ref(),
                    &mut progress,
                    &mut final_image_id,
                    &mut final_manifest_ref,
                    &mut final_error,
                );
            }
        }
    }

    if let Some(err) = final_error {
        if let Some(tx) = &event_tx {
            let _ = tx.send(BuildEvent::BuildFailed { error: err.clone() });
        }
        return Err(BuildError::BuildahExecution {
            command: "buildah-sidecar build".to_string(),
            exit_code: 1,
            stderr: err,
        });
    }

    let image_id = final_image_id.ok_or_else(|| BuildError::BuildahExecution {
        command: "buildah-sidecar build".to_string(),
        exit_code: 1,
        stderr: "sidecar stream ended without Finished or Error event".to_string(),
    })?;

    if let Some(tx) = &event_tx {
        let _ = tx.send(BuildEvent::BuildComplete {
            image_id: image_id.clone(),
        });
    }

    Ok(built_image_from(
        image_id,
        final_manifest_ref.as_deref(),
        options,
        started_at,
    ))
}

/// Dispatch a single sidecar event: forward the corresponding [`BuildEvent`]
/// to the TUI (if any) and update the terminal-state slots for the caller.
fn dispatch_event(
    ev: proto::build_event::Event,
    event_tx: Option<&Sender<BuildEvent>>,
    progress: &mut InstructionProgress,
    final_image_id: &mut Option<String>,
    final_manifest_ref: &mut Option<String>,
    final_error: &mut Option<String>,
) {
    match ev {
        proto::build_event::Event::StageStarted(s) => {
            if let Some(tx) = event_tx {
                let _ = tx.send(BuildEvent::StageStarted {
                    index: s.index as usize,
                    name: if s.name.is_empty() {
                        None
                    } else {
                        Some(s.name)
                    },
                    base_image: s.base_image,
                });
            }
        }
        proto::build_event::Event::StageFinished(s) => {
            if let Some(tx) = event_tx {
                let _ = tx.send(BuildEvent::StageComplete {
                    index: s.index as usize,
                });
            }
        }
        proto::build_event::Event::InstructionStarted(i) => {
            if let Some(tx) = event_tx {
                let _ = tx.send(BuildEvent::InstructionStarted {
                    stage: i.stage as usize,
                    index: i.index as usize,
                    instruction: i.instruction,
                });
            }
        }
        proto::build_event::Event::InstructionFinished(i) => {
            if let Some(tx) = event_tx {
                let _ = tx.send(BuildEvent::InstructionComplete {
                    stage: i.stage as usize,
                    index: i.index as usize,
                    cached: i.cached,
                });
            }
        }
        proto::build_event::Event::Log(line) => {
            for event in progress.on_line(&line.line, line.is_stderr) {
                if let Some(tx) = event_tx {
                    let _ = tx.send(event);
                }
            }
        }
        proto::build_event::Event::Warning(w) => {
            tracing::warn!(message = %w.message, "buildd build warning");
            if let Some(tx) = event_tx {
                let _ = tx.send(BuildEvent::Output {
                    line: format!("warning: {}", w.message),
                    is_stderr: true,
                });
            }
        }
        proto::build_event::Event::Finished(f) => {
            tracing::info!(
                image_id = %f.image_id,
                manifest_ref = %f.manifest_ref,
                "buildd build finished"
            );
            *final_image_id = Some(f.image_id);
            *final_manifest_ref = if f.manifest_ref.is_empty() {
                None
            } else {
                Some(f.manifest_ref)
            };
        }
        proto::build_event::Event::Error(e) => {
            tracing::error!(kind = %e.kind, message = %e.message, "buildd build error");
            *final_error = Some(if e.kind.is_empty() {
                e.message
            } else {
                format!("{}: {}", e.kind, e.message)
            });
        }
    }
}

/// Construct a [`BuiltImage`] from the terminal sidecar event.
///
/// The sidecar's `BuildFinished` carries only the image ID and (optionally)
/// the canonical `name@sha256:...` reference. `layer_count` and `size` are
/// not reported by the current schema; an `Inspect` RPC would be needed to
/// surface them. Those fields are zeroed for now — callers that need them
/// can follow up via `crate::backend::BuildahSidecarBackend::lifecycle`
/// and the `Inspect` RPC.
fn built_image_from(
    image_id: String,
    manifest_ref: Option<&str>,
    options: &BuildOptions,
    started_at: std::time::Instant,
) -> BuiltImage {
    let is_manifest =
        manifest_ref.is_some() && options.platform.as_deref().is_some_and(|s| s.contains(','));

    BuiltImage {
        image_id,
        tags: options.tags.clone(),
        layer_count: 0,
        size: 0,
        build_time_ms: u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX),
        is_manifest,
    }
}

/// Convert a tonic `Status` into a typed `BuildError` so the surrounding
/// code can match on the variant rather than parsing strings.
fn grpc_err(status: &tonic::Status) -> BuildError {
    BuildError::BuildahExecution {
        command: format!("buildah-sidecar rpc ({:?})", status.code()),
        exit_code: 1,
        stderr: status.message().to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::PullBaseMode;

    fn empty_dockerfile() -> Dockerfile {
        // A trivial single-stage Dockerfile so `parse` succeeds and we get
        // a `Dockerfile` value cheaply for tests that don't care about
        // its contents.
        Dockerfile::parse("FROM scratch\n").expect("trivial Dockerfile must parse")
    }

    #[test]
    fn build_request_from_minimal_options() {
        // `build_request_from` now writes the rendered Dockerfile INSIDE the
        // context, so the context must be a real directory.
        let ctx = tempfile::tempdir().expect("tempdir");
        let context = ctx.path();
        let df = empty_dockerfile();
        let options = BuildOptions {
            tags: vec!["test/img:latest".into()],
            ..BuildOptions::default()
        };

        let (req, rendered) = build_request_from(
            context,
            &df,
            &options,
            &zlayer_types::builder::SidecarConfig::default(),
        )
        .expect("build_request_from");
        assert_eq!(req.context_dir, context.to_string_lossy());
        assert_eq!(req.tags, vec!["test/img:latest".to_string()]);
        assert!(req.platforms.is_empty());

        // The single dockerfile path is the rendered temp file, living inside
        // the context dir, with the `zlayer-rendered-` prefix.
        assert_eq!(req.dockerfile_paths.len(), 1);
        let rendered_path = Path::new(&req.dockerfile_paths[0]);
        assert_eq!(rendered_path.parent(), Some(context));
        assert!(rendered_path
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.starts_with("zlayer-rendered-")));
        // The file the sidecar would read actually exists while the handle is
        // alive.
        assert!(rendered.path().exists());

        assert_eq!(req.pull_policy, "ifnewer"); // PullBaseMode default = Newer
        assert!(!req.no_cache);
        assert!(!req.squash);
        assert!(req.layers); // default in BuildOptions::default()
        assert_eq!(req.target_stage, "");
        assert_eq!(req.format, "");
        assert_eq!(req.cache_from, "");
        assert_eq!(req.cache_to, "");
        // A bare `FROM scratch` Dockerfile has no secret/ssh mounts.
        assert!(req.secrets.is_empty());
        assert!(req.ssh.is_empty());
    }

    #[test]
    fn build_request_dockerfile_path_is_rendered_temp_in_context() {
        // Regardless of `options.dockerfile`, the request now ships the
        // ZLayer-rendered Dockerfile written inside the context.
        let ctx = tempfile::tempdir().expect("tempdir");
        let context = ctx.path();
        let df = empty_dockerfile();
        let options = BuildOptions {
            dockerfile: Some(Path::new("/custom/Dockerfile.web").into()),
            ..BuildOptions::default()
        };
        let (req, _rendered) = build_request_from(
            context,
            &df,
            &options,
            &zlayer_types::builder::SidecarConfig::default(),
        )
        .expect("build_request_from");
        assert_eq!(req.dockerfile_paths.len(), 1);
        let rendered_path = Path::new(&req.dockerfile_paths[0]);
        assert_eq!(rendered_path.parent(), Some(context));
        assert!(rendered_path
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.starts_with("zlayer-rendered-")));
    }

    #[test]
    fn build_request_populates_secrets_and_ssh_from_run_mounts() {
        use crate::dockerfile::RunInstruction;

        // The text parser does not lift `--mount=` flags into the IR, so build
        // RUN instructions with secret + ssh mounts directly (mirrors the
        // native backend's `collect_ssh_ids` test).
        let ctx = tempfile::tempdir().expect("tempdir");
        let context = ctx.path();

        let mut run_secret = RunInstruction::shell("cat /run/secrets/foo");
        run_secret.mounts.push(RunMount::Secret {
            target: String::new(),
            id: "foo".to_string(),
            required: false,
        });
        let mut run_ssh = RunInstruction::shell("git fetch");
        run_ssh.mounts.push(RunMount::Ssh {
            target: String::new(),
            id: Some("github".to_string()),
            required: true,
        });

        let mut df = Dockerfile::parse("FROM alpine\n").expect("trivial Dockerfile parses");
        df.stages[0].instructions = vec![Instruction::Run(run_secret), Instruction::Run(run_ssh)];

        let options = BuildOptions::default();
        let (req, _rendered) = build_request_from(
            context,
            &df,
            &options,
            &zlayer_types::builder::SidecarConfig::default(),
        )
        .expect("build_request_from");
        assert_eq!(req.secrets, vec!["id=foo".to_string()]);
        assert_eq!(req.ssh, vec!["github".to_string()]);
    }

    #[test]
    fn build_request_translates_rendered_path_with_context_mount() {
        // With a cross-namespace `context_mount`, the rendered temp file's
        // host prefix is rewritten to the guest prefix.
        let host_root = tempfile::tempdir().expect("tempdir");
        let context = host_root.path();
        let df = empty_dockerfile();
        let options = BuildOptions::default();
        let config = zlayer_types::builder::SidecarConfig {
            context_mount: Some((
                context.to_path_buf(),
                std::path::PathBuf::from("/mnt/guest-ctx"),
            )),
            ..zlayer_types::builder::SidecarConfig::default()
        };
        let (req, _rendered) =
            build_request_from(context, &df, &options, &config).expect("build_request_from");
        // `join`ing an empty relative path leaves a trailing slash; normalize.
        assert_eq!(req.context_dir.trim_end_matches('/'), "/mnt/guest-ctx");
        let rendered_path = Path::new(&req.dockerfile_paths[0]);
        assert_eq!(rendered_path.parent(), Some(Path::new("/mnt/guest-ctx")));
        assert!(rendered_path
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.starts_with("zlayer-rendered-")));
    }

    #[test]
    fn build_request_splits_multi_platform_string() {
        let ctx = tempfile::tempdir().expect("tempdir");
        let context = ctx.path();
        let df = empty_dockerfile();
        let options = BuildOptions {
            platform: Some(" linux/amd64 , linux/arm64 ".to_string()),
            ..BuildOptions::default()
        };
        let (req, _rendered) = build_request_from(
            context,
            &df,
            &options,
            &zlayer_types::builder::SidecarConfig::default(),
        )
        .expect("build_request_from");
        assert_eq!(
            req.platforms,
            vec!["linux/amd64".to_string(), "linux/arm64".to_string()]
        );
    }

    #[test]
    fn build_request_merges_pipeline_vars_into_build_args() {
        let ctx = tempfile::tempdir().expect("tempdir");
        let context = ctx.path();
        let df = empty_dockerfile();
        let mut build_args = std::collections::HashMap::new();
        build_args.insert("FOO".to_string(), "1".to_string());
        let mut pipeline_vars = std::collections::HashMap::new();
        pipeline_vars.insert("LTSC".to_string(), "ltsc2025".to_string());
        let options = BuildOptions {
            build_args,
            pipeline_vars,
            ..BuildOptions::default()
        };
        let (req, _rendered) = build_request_from(
            context,
            &df,
            &options,
            &zlayer_types::builder::SidecarConfig::default(),
        )
        .expect("build_request_from");
        assert_eq!(req.build_args.get("FOO"), Some(&"1".to_string()));
        assert_eq!(req.build_args.get("LTSC"), Some(&"ltsc2025".to_string()));
    }

    #[test]
    fn pull_policy_translations() {
        assert_eq!(pull_policy_str(PullBaseMode::Never), "never");
        assert_eq!(pull_policy_str(PullBaseMode::Always), "always");
        assert_eq!(pull_policy_str(PullBaseMode::Newer), "ifnewer");
    }

    #[test]
    fn detect_default_isolation_picks_chroot_when_unprivileged() {
        // We run unit tests as the developer's user (uid != 0 on every
        // contributor's box AND on CI). The function must therefore return
        // "chroot" in this environment.
        #[cfg(unix)]
        {
            if nix::unistd::Uid::current().is_root() {
                // When running as actual root the function returns the
                // empty string so the sidecar inherits buildah's default
                // (oci on Linux) — verify that root path too.
                assert_eq!(detect_default_isolation(), "");
            } else {
                assert_eq!(detect_default_isolation(), "chroot");
            }
        }
        #[cfg(not(unix))]
        {
            assert_eq!(detect_default_isolation(), "");
        }
    }

    #[test]
    fn built_image_carries_tags_and_id() {
        let started = std::time::Instant::now();
        let options = BuildOptions {
            tags: vec!["a:b".into(), "c:d".into()],
            ..BuildOptions::default()
        };
        let img = built_image_from("sha256:abc".to_string(), None, &options, started);
        assert_eq!(img.image_id, "sha256:abc");
        assert_eq!(img.tags, vec!["a:b".to_string(), "c:d".to_string()]);
        assert!(!img.is_manifest);
    }

    #[test]
    fn built_image_flags_manifest_for_multi_arch_with_manifest_ref() {
        let started = std::time::Instant::now();
        let options = BuildOptions {
            tags: vec!["a:b".into()],
            platform: Some("linux/amd64,linux/arm64".to_string()),
            ..BuildOptions::default()
        };
        let img = built_image_from(
            "sha256:abc".to_string(),
            Some("registry/img@sha256:abc"),
            &options,
            started,
        );
        assert!(img.is_manifest);
    }

    #[test]
    fn grpc_err_carries_status_message() {
        let status = tonic::Status::internal("boom");
        let err = grpc_err(&status);
        match err {
            BuildError::BuildahExecution {
                command, stderr, ..
            } => {
                assert!(command.contains("Internal"));
                assert_eq!(stderr, "boom");
            }
            other => panic!("unexpected variant: {other:?}"),
        }
    }
}