1use std::collections::{BTreeMap, BTreeSet, HashSet};
4use std::path::{Path, PathBuf};
5
6use anyhow::Result;
7use hcl::eval::{Context as HclContext, Evaluate};
8use hcl::{BlockLabel, Body, Expression, Value as HclValue};
9use ignore::WalkBuilder;
10use serde::{Deserialize, Serialize};
11use serde_json::Value as JsonValue;
12use serde_yaml::Value as YamlValue;
13use sha2::{Digest, Sha256};
14
15use crate::repository::{self, ContainerEngine};
16use crate::rules::Finding;
17
18pub const INVOCATION_SCHEMA_VERSION: u32 = 1;
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum InvocationKind {
23 Direct,
24 Compose,
25 Bake,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum ValueState {
31 Resolved,
32 Unresolved,
33 Redacted,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct Provenance {
38 pub kind: String,
39 pub source: String,
40 pub path: String,
41 pub precedence: u32,
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub line: Option<usize>,
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub column: Option<usize>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct EffectiveValue {
50 pub state: ValueState,
51 #[serde(skip_serializing_if = "Option::is_none")]
52 pub value: Option<String>,
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub expression: Option<String>,
55 pub provenance: Vec<Provenance>,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct InvocationOrigin {
60 pub kind: InvocationKind,
61 #[serde(skip_serializing_if = "Option::is_none")]
62 pub name: Option<String>,
63 pub location: Provenance,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct DeclaredInput {
68 pub id: EffectiveValue,
69 #[serde(skip_serializing_if = "Option::is_none")]
70 pub target: Option<EffectiveValue>,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub struct BuildInvocation {
75 pub schema_version: u32,
76 pub id: String,
77 pub origin: InvocationOrigin,
78 pub dockerfile: EffectiveValue,
79 pub context: EffectiveValue,
80 #[serde(skip_serializing_if = "Option::is_none")]
81 pub target: Option<EffectiveValue>,
82 pub build_args: BTreeMap<String, EffectiveValue>,
83 pub platforms: Vec<EffectiveValue>,
84 pub named_contexts: BTreeMap<String, EffectiveValue>,
85 pub secrets: Vec<DeclaredInput>,
86 pub ssh: Vec<DeclaredInput>,
87 pub cache_from: Vec<EffectiveValue>,
88 pub cache_to: Vec<EffectiveValue>,
89 pub exporters: Vec<EffectiveValue>,
90 pub attestations: Vec<EffectiveValue>,
91 pub effective_ignore_file: EffectiveValue,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct InvocationDocument {
96 pub schema_version: u32,
97 pub invocations: Vec<BuildInvocation>,
98 pub warnings: Vec<String>,
99}
100
101#[derive(Debug, Clone)]
102pub struct InvocationFinding {
103 pub invocation_ids: Vec<String>,
104 pub effective_inputs_hash: String,
105 pub file: String,
106 pub finding: Finding,
107}
108
109pub fn lint(
113 document: &InvocationDocument,
114 options: &crate::linter::LintOptions,
115) -> Result<Vec<InvocationFinding>> {
116 let mut findings = BTreeMap::<(String, String), InvocationFinding>::new();
117 for invocation in &document.invocations {
118 let (Some(dockerfile), Some(context)) = (
119 invocation.dockerfile.value.as_deref(),
120 invocation.context.value.as_deref(),
121 ) else {
122 continue;
123 };
124 let linted = crate::linter::lint_file_with_context(
125 Path::new(dockerfile),
126 Path::new(context),
127 options,
128 )?;
129 let effective_inputs_hash = effective_inputs_hash(invocation);
130 for finding in linted.findings {
131 let fingerprint = crate::output::finding_fingerprint(&linted.file, &finding);
132 let key = (effective_inputs_hash.clone(), fingerprint);
133 match findings.get_mut(&key) {
134 Some(existing) => existing.invocation_ids.push(invocation.id.clone()),
135 None => {
136 findings.insert(
137 key,
138 InvocationFinding {
139 invocation_ids: vec![invocation.id.clone()],
140 effective_inputs_hash: effective_inputs_hash.clone(),
141 file: linted.file.clone(),
142 finding,
143 },
144 );
145 }
146 }
147 }
148 }
149 for finding in findings.values_mut() {
150 finding.invocation_ids.sort();
151 }
152 Ok(findings.into_values().collect())
153}
154
155fn effective_inputs_hash(invocation: &BuildInvocation) -> String {
156 let mut inputs = serde_json::json!({
157 "dockerfile": invocation.dockerfile,
158 "context": invocation.context,
159 "target": invocation.target,
160 "build_args": invocation.build_args,
161 "platforms": invocation.platforms,
162 "named_contexts": invocation.named_contexts,
163 "secrets": invocation.secrets,
164 "ssh": invocation.ssh,
165 "cache_from": invocation.cache_from,
166 "cache_to": invocation.cache_to,
167 "exporters": invocation.exporters,
168 "attestations": invocation.attestations,
169 "effective_ignore_file": invocation.effective_ignore_file,
170 });
171 remove_nonsemantic_provenance(&mut inputs);
172 let material =
173 serde_json::to_vec(&inputs).expect("effective invocation inputs are serializable");
174 format!("sha256:{:x}", Sha256::digest(material))
175}
176
177fn remove_nonsemantic_provenance(value: &mut JsonValue) {
178 match value {
179 JsonValue::Object(values) => {
180 let redacted = values.get("state").and_then(JsonValue::as_str) == Some("redacted");
181 if !redacted {
182 values.remove("provenance");
183 }
184 for value in values.values_mut() {
185 remove_nonsemantic_provenance(value);
186 }
187 }
188 JsonValue::Array(values) => {
189 for value in values {
190 remove_nonsemantic_provenance(value);
191 }
192 }
193 _ => {}
194 }
195}
196
197#[derive(Debug, Default, Clone)]
198struct RawBuild {
199 context: Option<String>,
200 dockerfile: Option<String>,
201 target: Option<String>,
202 args: BTreeMap<String, RawValue>,
203 platforms: Vec<String>,
204 contexts: BTreeMap<String, String>,
205 secrets: Vec<(String, Option<String>)>,
206 ssh: Vec<(String, Option<String>)>,
207 cache_from: Vec<String>,
208 cache_to: Vec<String>,
209 outputs: Vec<String>,
210 attestations: Vec<String>,
211 inherits: Vec<String>,
212 matrix: BTreeMap<String, Vec<String>>,
213 inline: bool,
214 source_paths: BTreeMap<String, String>,
215}
216
217#[derive(Debug, Clone)]
218enum RawValue {
219 Value(String),
220 Inherit,
221 Unresolved(String),
222}
223
224pub fn discover(paths: &[PathBuf], engine: ContainerEngine) -> InvocationDocument {
225 let repository = repository::discover(paths, engine);
226 let mut warnings = repository.warnings;
227 let definitions = definition_files(paths, &mut warnings);
228 let mut invocations = Vec::new();
229
230 for definition in definitions {
231 if is_compose_file(&definition) {
232 resolve_compose(&definition, engine, &mut invocations, &mut warnings);
233 } else {
234 resolve_bake(&definition, engine, &mut invocations, &mut warnings);
235 }
236 }
237
238 let represented = invocations
239 .iter()
240 .filter_map(resolved_pair)
241 .collect::<BTreeSet<_>>();
242 for input in repository.inputs {
243 let pair = (
244 canonicalish(&input.dockerfile),
245 canonicalish(&input.context),
246 );
247 if represented.contains(&pair) {
248 continue;
249 }
250 invocations.push(direct_invocation(&input, engine));
251 }
252
253 for invocation in &mut invocations {
254 invocation.id.clear();
255 let material = serde_json::to_vec(invocation).expect("invocation schema is serializable");
256 invocation.id = format!("sha256:{:x}", Sha256::digest(material));
257 }
258 invocations.sort_by(|left, right| left.id.cmp(&right.id));
259 warnings.sort();
260 warnings.dedup();
261 InvocationDocument {
262 schema_version: INVOCATION_SCHEMA_VERSION,
263 invocations,
264 warnings,
265 }
266}
267
268fn direct_invocation(input: &repository::BuildInput, engine: ContainerEngine) -> BuildInvocation {
269 let source = display_path(&input.dockerfile);
270 let origin_location = provenance("discovery", &source, "dockerfile", 0);
271 let dockerfile = resolved(display_path(&input.dockerfile), origin_location.clone());
272 let context = resolved(
273 display_path(&input.context),
274 provenance("inferred", &source, "context", 0),
275 );
276 let ignore = ignore_file(&input.dockerfile, &input.context, engine, &source);
277 empty_invocation(
278 InvocationOrigin {
279 kind: InvocationKind::Direct,
280 name: None,
281 location: origin_location,
282 },
283 dockerfile,
284 context,
285 ignore,
286 )
287}
288
289fn empty_invocation(
290 origin: InvocationOrigin,
291 dockerfile: EffectiveValue,
292 context: EffectiveValue,
293 effective_ignore_file: EffectiveValue,
294) -> BuildInvocation {
295 BuildInvocation {
296 schema_version: INVOCATION_SCHEMA_VERSION,
297 id: String::new(),
298 origin,
299 dockerfile,
300 context,
301 target: None,
302 build_args: BTreeMap::new(),
303 platforms: Vec::new(),
304 named_contexts: BTreeMap::new(),
305 secrets: Vec::new(),
306 ssh: Vec::new(),
307 cache_from: Vec::new(),
308 cache_to: Vec::new(),
309 exporters: Vec::new(),
310 attestations: Vec::new(),
311 effective_ignore_file,
312 }
313}
314
315fn resolve_compose(
316 file: &Path,
317 engine: ContainerEngine,
318 output: &mut Vec<BuildInvocation>,
319 warnings: &mut Vec<String>,
320) {
321 let content = match std::fs::read_to_string(file) {
322 Ok(content) => content,
323 Err(error) => {
324 warnings.push(format!(
325 "cannot read Compose file '{}': {error}",
326 file.display()
327 ));
328 return;
329 }
330 };
331 let document: YamlValue = match serde_yaml::from_str(&content) {
332 Ok(document) => document,
333 Err(error) => {
334 warnings.push(format!(
335 "cannot parse Compose file '{}': {error}",
336 file.display()
337 ));
338 return;
339 }
340 };
341 let Some(services) = mapping_value(&document, "services").and_then(YamlValue::as_mapping)
342 else {
343 return;
344 };
345 let base = file.parent().unwrap_or_else(|| Path::new("."));
346 let environment = compose_environment(base);
347 for (name, service) in services {
348 let Some(name) = name.as_str() else { continue };
349 let Some(build) = mapping_value(service, "build") else {
350 continue;
351 };
352 let raw = compose_build(build);
353 if raw.inline {
354 warnings.push(format!(
355 "Compose service {name:?} in '{}' uses dockerfile_inline, which has no filesystem Dockerfile",
356 file.display()
357 ));
358 continue;
359 }
360 let key_path = format!("services.{name}.build");
361 output.push(materialize(
362 raw,
363 MaterializeContext {
364 file,
365 key_path: &key_path,
366 kind: InvocationKind::Compose,
367 name,
368 base,
369 environment: &environment,
370 engine,
371 },
372 ));
373 }
374}
375
376fn compose_build(value: &YamlValue) -> RawBuild {
377 if let Some(context) = value.as_str() {
378 return RawBuild {
379 context: Some(context.to_string()),
380 dockerfile: Some("Dockerfile".into()),
381 ..RawBuild::default()
382 };
383 }
384 let mut raw = RawBuild {
385 context: mapping_value(value, "context")
386 .and_then(YamlValue::as_str)
387 .map(str::to_string)
388 .or(Some(".".into())),
389 dockerfile: mapping_value(value, "dockerfile")
390 .and_then(YamlValue::as_str)
391 .map(str::to_string)
392 .or(Some("Dockerfile".into())),
393 target: string_value(mapping_value(value, "target")),
394 platforms: string_list(mapping_value(value, "platforms")),
395 cache_from: string_or_object_list(mapping_value(value, "cache_from")),
396 cache_to: string_or_object_list(mapping_value(value, "cache_to")),
397 outputs: string_or_object_list(
398 mapping_value(value, "outputs").or_else(|| mapping_value(value, "output")),
399 ),
400 inline: mapping_value(value, "dockerfile_inline").is_some(),
401 ..RawBuild::default()
402 };
403 raw.args = yaml_key_values(mapping_value(value, "args"));
404 raw.contexts = yaml_named_values(mapping_value(value, "additional_contexts"));
405 raw.secrets = yaml_declarations(mapping_value(value, "secrets"));
406 raw.ssh = yaml_declarations(mapping_value(value, "ssh"));
407 if let Some(value) = mapping_value(value, "provenance") {
408 raw.attestations
409 .push(format!("type=provenance,{}", yaml_scalar(value)));
410 }
411 if let Some(value) = mapping_value(value, "sbom") {
412 raw.attestations
413 .push(format!("type=sbom,{}", yaml_scalar(value)));
414 }
415 raw
416}
417
418fn resolve_bake(
419 file: &Path,
420 engine: ContainerEngine,
421 output: &mut Vec<BuildInvocation>,
422 warnings: &mut Vec<String>,
423) {
424 let content = match std::fs::read_to_string(file) {
425 Ok(content) => content,
426 Err(error) => {
427 warnings.push(format!(
428 "cannot read Bake file '{}': {error}",
429 file.display()
430 ));
431 return;
432 }
433 };
434 let targets = if file.extension().and_then(|value| value.to_str()) == Some("json") {
435 parse_bake_json(&content)
436 } else {
437 parse_bake_hcl(&content)
438 };
439 let targets = match targets {
440 Ok(targets) => targets,
441 Err(error) => {
442 warnings.push(format!(
443 "cannot parse Bake file '{}': {error}",
444 file.display()
445 ));
446 return;
447 }
448 };
449 let base = file.parent().unwrap_or_else(|| Path::new("."));
450 let environment = process_environment();
451 for name in targets.keys() {
452 if let Some(target) = targets.get(name) {
453 let parents = target
454 .inherits
455 .iter()
456 .filter_map(|parent| {
457 resolve_bake_target(parent, &targets, &mut HashSet::new())
458 .map(|resolved| (parent, resolved))
459 })
460 .collect::<Vec<_>>();
461 for left in 0..parents.len() {
462 for right in left + 1..parents.len() {
463 let conflicts = raw_conflicts(&parents[left].1, &parents[right].1);
464 if !conflicts.is_empty() {
465 warnings.push(format!(
466 "Bake target {name:?} in '{}' inherits conflicting definitions from {:?} and {:?}: {} (later inheritance wins)",
467 file.display(),
468 parents[left].0,
469 parents[right].0,
470 conflicts.join(", ")
471 ));
472 }
473 }
474 }
475 }
476 let mut visiting = HashSet::new();
477 let Some(target) = resolve_bake_target(name, &targets, &mut visiting) else {
478 warnings.push(format!(
479 "Bake target {name:?} in '{}' has cyclic, missing, or conflicting inheritance",
480 file.display()
481 ));
482 continue;
483 };
484 if target.inline {
485 continue;
486 }
487 for (suffix, expanded) in expand_matrix(&target) {
488 let key_path = format!("target.{name}{suffix}");
489 let expanded_name = format!("{name}{suffix}");
490 output.push(materialize(
491 expanded,
492 MaterializeContext {
493 file,
494 key_path: &key_path,
495 kind: InvocationKind::Bake,
496 name: &expanded_name,
497 base,
498 environment: &environment,
499 engine,
500 },
501 ));
502 }
503 }
504}
505
506fn raw_conflicts(left: &RawBuild, right: &RawBuild) -> Vec<String> {
507 let mut conflicts = Vec::new();
508 for (name, left, right) in [
509 ("context", left.context.as_ref(), right.context.as_ref()),
510 (
511 "dockerfile",
512 left.dockerfile.as_ref(),
513 right.dockerfile.as_ref(),
514 ),
515 ("target", left.target.as_ref(), right.target.as_ref()),
516 ] {
517 if matches!((left, right), (Some(left), Some(right)) if left != right) {
518 conflicts.push(name.to_string());
519 }
520 }
521 for key in left.args.keys().filter(|key| right.args.contains_key(*key)) {
522 let different = match (&left.args[key], &right.args[key]) {
523 (RawValue::Value(left), RawValue::Value(right)) => left != right,
524 (RawValue::Inherit, RawValue::Inherit) => false,
525 (RawValue::Unresolved(left), RawValue::Unresolved(right)) => left != right,
526 _ => true,
527 };
528 if different {
529 conflicts.push(format!("args.{key}"));
530 }
531 }
532 conflicts
533}
534
535struct MaterializeContext<'a> {
536 file: &'a Path,
537 key_path: &'a str,
538 kind: InvocationKind,
539 name: &'a str,
540 base: &'a Path,
541 environment: &'a BTreeMap<String, EnvValue>,
542 engine: ContainerEngine,
543}
544
545fn materialize(raw: RawBuild, resolution: MaterializeContext<'_>) -> BuildInvocation {
546 let MaterializeContext {
547 file,
548 key_path,
549 kind,
550 name,
551 base,
552 environment,
553 engine,
554 } = resolution;
555 let source = display_path(file);
556 let source_paths = raw.source_paths.clone();
557 let path_for =
558 |field: &str, default: String| source_paths.get(field).cloned().unwrap_or(default);
559 let context_expression = raw.context.as_deref().unwrap_or(".");
560 let context_interpolated = interpolate(context_expression, environment);
561 let context = path_value(
562 context_interpolated,
563 base,
564 &source,
565 &path_for("context", format!("{key_path}.context")),
566 );
567 let dockerfile_expression = raw.dockerfile.as_deref().unwrap_or("Dockerfile");
568 let dockerfile_interpolated = interpolate(dockerfile_expression, environment);
569 let dockerfile = match (&context.value, dockerfile_interpolated) {
570 (Some(context), Interpolation::Resolved(value, mut provenance_values)) => {
571 let path = PathBuf::from(context).join(value);
572 provenance_values.push(provenance(
573 "definition",
574 &source,
575 &path_for("dockerfile", format!("{key_path}.dockerfile")),
576 0,
577 ));
578 resolved_with(display_path(&path), provenance_values)
579 }
580 (_, Interpolation::Unresolved(expression, provenance_values)) => {
581 unresolved_with(expression, provenance_values)
582 }
583 _ => unresolved(
584 dockerfile_expression,
585 provenance(
586 "definition",
587 &source,
588 &path_for("dockerfile", format!("{key_path}.dockerfile")),
589 0,
590 ),
591 ),
592 };
593 let ignore = match (dockerfile.value.as_deref(), context.value.as_deref()) {
594 (Some(dockerfile), Some(context)) => {
595 ignore_file(Path::new(dockerfile), Path::new(context), engine, &source)
596 }
597 _ => unresolved(
598 "effective ignore file depends on unresolved build paths",
599 provenance("derived", &source, &format!("{key_path}.ignore"), 0),
600 ),
601 };
602 let mut invocation = empty_invocation(
603 InvocationOrigin {
604 kind,
605 name: Some(name.to_string()),
606 location: provenance("definition", &source, key_path, 0),
607 },
608 dockerfile,
609 context,
610 ignore,
611 );
612 invocation.target = raw.target.as_deref().map(|value| {
613 effective_interpolation(
614 value,
615 environment,
616 &source,
617 &path_for("target", format!("{key_path}.target")),
618 )
619 });
620 for (name, value) in raw.args {
621 let path = path_for(&format!("args.{name}"), format!("{key_path}.args.{name}"));
622 let value = match value {
623 RawValue::Value(value) => {
624 if sensitive_name(&name) {
625 redacted(&value, provenance("definition", &source, &path, 0))
626 } else {
627 effective_interpolation(&value, environment, &source, &path)
628 }
629 }
630 RawValue::Inherit => match environment.get(&name) {
631 Some(value) if sensitive_name(&name) => redacted(&name, value.provenance.clone()),
632 Some(value) => resolved_with(value.value.clone(), vec![value.provenance.clone()]),
633 None => unresolved(&name, provenance("environment", &source, &path, 1)),
634 },
635 RawValue::Unresolved(expression) => {
636 unresolved(expression, provenance("definition", &source, &path, 0))
637 }
638 };
639 invocation.build_args.insert(name, value);
640 }
641 invocation.platforms = raw
642 .platforms
643 .iter()
644 .map(|value| {
645 effective_interpolation(
646 value,
647 environment,
648 &source,
649 &path_for("platforms", format!("{key_path}.platforms")),
650 )
651 })
652 .collect();
653 invocation.named_contexts = raw
654 .contexts
655 .iter()
656 .map(|(name, value)| {
657 (
658 name.clone(),
659 named_context_value(
660 value,
661 environment,
662 base,
663 &source,
664 &path_for(
665 &format!("contexts.{name}"),
666 format!("{key_path}.contexts.{name}"),
667 ),
668 ),
669 )
670 })
671 .collect();
672 invocation.secrets = declarations(
673 raw.secrets,
674 &source,
675 &path_for("secrets", format!("{key_path}.secrets")),
676 );
677 invocation.ssh = declarations(
678 raw.ssh,
679 &source,
680 &path_for("ssh", format!("{key_path}.ssh")),
681 );
682 invocation.cache_from = effective_list(
683 raw.cache_from,
684 environment,
685 &source,
686 &path_for("cache_from", format!("{key_path}.cache_from")),
687 );
688 invocation.cache_to = effective_list(
689 raw.cache_to,
690 environment,
691 &source,
692 &path_for("cache_to", format!("{key_path}.cache_to")),
693 );
694 invocation.exporters = effective_list(
695 raw.outputs,
696 environment,
697 &source,
698 &path_for("outputs", format!("{key_path}.outputs")),
699 );
700 invocation.attestations = effective_list(
701 raw.attestations,
702 environment,
703 &source,
704 &path_for("attestations", format!("{key_path}.attestations")),
705 );
706 invocation
707}
708
709fn named_context_value(
710 expression: &str,
711 environment: &BTreeMap<String, EnvValue>,
712 base: &Path,
713 source: &str,
714 path: &str,
715) -> EffectiveValue {
716 let value = effective_interpolation(expression, environment, source, path);
717 let Some(resolved_value) = value.value.as_deref() else {
718 return value;
719 };
720 if resolved_value.contains("://")
721 || resolved_value.starts_with("service:")
722 || resolved_value.starts_with("target:")
723 || resolved_value.starts_with("docker-image:")
724 {
725 value
726 } else {
727 resolved_with(display_path(&base.join(resolved_value)), value.provenance)
728 }
729}
730
731#[derive(Debug, Clone)]
732struct EnvValue {
733 value: String,
734 provenance: Provenance,
735}
736
737fn compose_environment(base: &Path) -> BTreeMap<String, EnvValue> {
738 let mut environment = BTreeMap::new();
739 let dotenv = base.join(".env");
740 if let Ok(values) = dotenvy::from_path_iter(&dotenv) {
741 for (name, value) in values.flatten() {
742 environment.insert(
743 name.clone(),
744 EnvValue {
745 value,
746 provenance: provenance("dotenv", &display_path(&dotenv), &name, 10),
747 },
748 );
749 }
750 }
751 for (name, value) in std::env::vars() {
752 environment.insert(
753 name.clone(),
754 EnvValue {
755 value,
756 provenance: provenance("process_environment", "<environment>", &name, 20),
757 },
758 );
759 }
760 environment
761}
762
763fn process_environment() -> BTreeMap<String, EnvValue> {
764 compose_environment(Path::new("/__droast_no_dotenv__"))
765}
766
767enum Interpolation {
768 Resolved(String, Vec<Provenance>),
769 Unresolved(String, Vec<Provenance>),
770}
771
772fn interpolate(expression: &str, environment: &BTreeMap<String, EnvValue>) -> Interpolation {
773 let mut result = String::new();
774 let mut provenance_values = Vec::new();
775 let bytes = expression.as_bytes();
776 let mut index = 0;
777 while index < bytes.len() {
778 if bytes[index] != b'$' {
779 let character = expression[index..].chars().next().unwrap();
780 result.push(character);
781 index += character.len_utf8();
782 continue;
783 }
784 if bytes.get(index + 1) == Some(&b'$') {
785 result.push('$');
786 index += 2;
787 continue;
788 }
789 let (name, operation, operand, end) = if bytes.get(index + 1) == Some(&b'{') {
790 let Some(close) = expression[index + 2..].find('}') else {
791 return Interpolation::Unresolved(expression.to_string(), provenance_values);
792 };
793 let end = index + 2 + close;
794 let inner = &expression[index + 2..end];
795 let parsed = [":-", ":+", ":?", "-", "+", "?"]
796 .into_iter()
797 .find_map(|operation| {
798 inner
799 .split_once(operation)
800 .map(|(name, operand)| (name, Some(operation), Some(operand)))
801 })
802 .unwrap_or((inner, None, None));
803 (parsed.0, parsed.1, parsed.2, end + 1)
804 } else {
805 let start = index + 1;
806 let mut end = start;
807 while end < bytes.len() && (bytes[end].is_ascii_alphanumeric() || bytes[end] == b'_') {
808 end += 1;
809 }
810 if end == start {
811 result.push('$');
812 index += 1;
813 continue;
814 }
815 (&expression[start..end], None, None, end)
816 };
817 let environment_value = environment.get(name);
818 let is_set = environment_value.is_some();
819 let is_nonempty = environment_value.is_some_and(|value| !value.value.is_empty());
820 let colon = operation.is_some_and(|operation| operation.starts_with(':'));
821 let usable = is_set && (!colon || is_nonempty);
822 match operation.map(|operation| operation.trim_start_matches(':')) {
823 None if is_set => {
824 let value = environment_value.unwrap();
825 result.push_str(&value.value);
826 provenance_values.push(value.provenance.clone());
827 }
828 Some("-") if usable => {
829 let value = environment_value.unwrap();
830 result.push_str(&value.value);
831 provenance_values.push(value.provenance.clone());
832 }
833 Some("-") => result.push_str(operand.unwrap_or_default()),
834 Some("+") if usable => result.push_str(operand.unwrap_or_default()),
835 Some("+") => {}
836 Some("?") if usable => {
837 let value = environment_value.unwrap();
838 result.push_str(&value.value);
839 provenance_values.push(value.provenance.clone());
840 }
841 Some("?") | None => {
842 return Interpolation::Unresolved(expression.to_string(), provenance_values)
843 }
844 _ => return Interpolation::Unresolved(expression.to_string(), provenance_values),
845 }
846 index = end;
847 }
848 Interpolation::Resolved(result, provenance_values)
849}
850
851fn effective_interpolation(
852 expression: &str,
853 environment: &BTreeMap<String, EnvValue>,
854 source: &str,
855 path: &str,
856) -> EffectiveValue {
857 match interpolate(expression, environment) {
858 Interpolation::Resolved(value, mut values) => {
859 values.push(provenance("definition", source, path, 0));
860 resolved_with(value, values)
861 }
862 Interpolation::Unresolved(expression, mut values) => {
863 values.push(provenance("definition", source, path, 0));
864 unresolved_with(expression, values)
865 }
866 }
867}
868
869fn path_value(value: Interpolation, base: &Path, source: &str, path: &str) -> EffectiveValue {
870 match value {
871 Interpolation::Resolved(value, mut values) => {
872 values.push(provenance("definition", source, path, 0));
873 if value.contains("://") || value.starts_with("docker-image://") {
874 unresolved_with(value, values)
875 } else {
876 resolved_with(display_path(&base.join(value)), values)
877 }
878 }
879 Interpolation::Unresolved(expression, mut values) => {
880 values.push(provenance("definition", source, path, 0));
881 unresolved_with(expression, values)
882 }
883 }
884}
885
886fn declarations(
887 values: Vec<(String, Option<String>)>,
888 source: &str,
889 path: &str,
890) -> Vec<DeclaredInput> {
891 values
892 .into_iter()
893 .enumerate()
894 .map(|(index, (id, target))| DeclaredInput {
895 id: resolved(
896 id,
897 provenance("declaration", source, &format!("{path}[{index}].id"), 0),
898 ),
899 target: target.map(|target| {
900 resolved(
901 target,
902 provenance("declaration", source, &format!("{path}[{index}].target"), 0),
903 )
904 }),
905 })
906 .collect()
907}
908
909fn effective_list(
910 values: Vec<String>,
911 env: &BTreeMap<String, EnvValue>,
912 source: &str,
913 path: &str,
914) -> Vec<EffectiveValue> {
915 values
916 .iter()
917 .map(|value| effective_interpolation(value, env, source, path))
918 .collect()
919}
920
921fn ignore_file(
922 dockerfile: &Path,
923 context: &Path,
924 engine: ContainerEngine,
925 source: &str,
926) -> EffectiveValue {
927 let docker_specific = PathBuf::from(format!("{}.dockerignore", dockerfile.display()));
928 let candidates = match engine {
929 ContainerEngine::Docker => vec![docker_specific, context.join(".dockerignore")],
930 ContainerEngine::Podman => vec![
931 context.join(".containerignore"),
932 context.join(".dockerignore"),
933 ],
934 };
935 if let Some(path) = candidates.iter().find(|path| path.is_file()) {
936 resolved(
937 display_path(path),
938 provenance("filesystem", source, "effective_ignore_file", 0),
939 )
940 } else {
941 unresolved(
942 display_path(candidates.last().expect("ignore candidates are nonempty")),
943 provenance("filesystem", source, "effective_ignore_file", 0),
944 )
945 }
946}
947
948fn parse_bake_json(content: &str) -> Result<BTreeMap<String, RawBuild>> {
949 let document: JsonValue = serde_json::from_str(content)?;
950 let mut result = BTreeMap::new();
951 let Some(targets) = document.get("target").and_then(JsonValue::as_object) else {
952 return Ok(result);
953 };
954 for (name, target) in targets {
955 let mut raw = raw_from_json(target);
956 annotate_bake_paths(&mut raw, name);
957 result.insert(name.clone(), raw);
958 }
959 let variables = document
960 .get("variable")
961 .and_then(JsonValue::as_object)
962 .into_iter()
963 .flatten()
964 .filter_map(|(name, definition)| {
965 std::env::var(name)
966 .ok()
967 .or_else(|| {
968 definition
969 .get("default")
970 .and_then(|value| value.as_str().map(str::to_string))
971 })
972 .map(|value| (name.clone(), value))
973 })
974 .collect::<BTreeMap<_, _>>();
975 for target in result.values_mut() {
976 substitute_raw(target, &variables);
977 }
978 Ok(result)
979}
980
981fn raw_from_json(value: &JsonValue) -> RawBuild {
982 let mut raw = RawBuild {
983 context: json_string(value.get("context")),
984 dockerfile: json_string(value.get("dockerfile")),
985 target: json_string(value.get("target")),
986 platforms: json_strings(value.get("platforms")),
987 contexts: json_named_values(value.get("contexts")),
988 secrets: json_declarations(value.get("secret").or_else(|| value.get("secrets"))),
989 ssh: json_declarations(value.get("ssh")),
990 cache_from: json_strings(value.get("cache-from")),
991 cache_to: json_strings(value.get("cache-to")),
992 outputs: json_strings(value.get("output")),
993 attestations: json_strings(value.get("attest")),
994 inherits: json_strings(value.get("inherits")),
995 matrix: json_matrix(value.get("matrix")),
996 inline: value.get("dockerfile-inline").is_some(),
997 ..RawBuild::default()
998 };
999 raw.args = json_key_values(value.get("args"));
1000 raw
1001}
1002
1003fn parse_bake_hcl(content: &str) -> Result<BTreeMap<String, RawBuild>> {
1004 let body: Body = hcl::parse(content)?;
1005 let mut context = HclContext::new();
1006 for block in body
1007 .blocks()
1008 .filter(|block| block.identifier() == "variable")
1009 {
1010 let Some(name) = block_label(block.labels.first()) else {
1011 continue;
1012 };
1013 let value = std::env::var(name).ok().map(HclValue::from).or_else(|| {
1014 hcl_attribute(block, "default").and_then(|value| value.evaluate(&context).ok())
1015 });
1016 if let Some(value) = value {
1017 context.declare_var(name, value);
1018 }
1019 }
1020 let mut result = BTreeMap::new();
1021 for block in body.blocks().filter(|block| block.identifier() == "target") {
1022 let Some(name) = block_label(block.labels.first()) else {
1023 continue;
1024 };
1025 let matrix = hcl_attribute(block, "matrix")
1026 .and_then(|expression| expression.evaluate(&context).ok())
1027 .and_then(|value| serde_json::to_value(value).ok());
1028 let combinations = matrix_combinations(&json_matrix(matrix.as_ref()));
1029 for combination in combinations {
1030 let mut expanded_context = context.clone();
1031 for (key, value) in &combination {
1032 expanded_context.declare_var(key.as_str(), value.clone());
1033 }
1034 let value = |key: &str| {
1035 hcl_attribute(block, key).and_then(|expression| {
1036 expression
1037 .evaluate(&expanded_context)
1038 .ok()
1039 .and_then(|value| serde_json::to_value(value).ok())
1040 .or_else(|| hcl::to_string(expression).ok().map(JsonValue::String))
1041 })
1042 };
1043 let object = [
1044 "context",
1045 "dockerfile",
1046 "target",
1047 "platforms",
1048 "contexts",
1049 "secret",
1050 "ssh",
1051 "cache-from",
1052 "cache-to",
1053 "output",
1054 "attest",
1055 "inherits",
1056 "args",
1057 ]
1058 .into_iter()
1059 .filter_map(|key| value(key).map(|value| (key.to_string(), value)))
1060 .collect::<serde_json::Map<_, _>>();
1061 let mut raw = raw_from_json(&JsonValue::Object(object));
1062 if let Some(Expression::Object(values)) = hcl_attribute(block, "args") {
1063 raw.args.clear();
1064 for (key, expression) in values {
1065 let key = key.to_string().trim_matches('"').to_string();
1066 let value = match expression.evaluate(&expanded_context) {
1067 Ok(HclValue::Null) => RawValue::Inherit,
1068 Ok(value) => {
1069 RawValue::Value(value.as_str().map(str::to_string).unwrap_or_else(
1070 || serde_json::to_string(&value).unwrap_or_default(),
1071 ))
1072 }
1073 Err(_) => RawValue::Unresolved(
1074 hcl::to_string(expression)
1075 .unwrap_or_else(|_| "<unresolved HCL expression>".into()),
1076 ),
1077 };
1078 raw.args.insert(key, value);
1079 }
1080 }
1081 raw.inline = hcl_attribute(block, "dockerfile-inline").is_some();
1082 annotate_bake_paths(&mut raw, name);
1083 let suffix = if combination.is_empty() {
1084 String::new()
1085 } else {
1086 format!(
1087 "[{}]",
1088 combination
1089 .iter()
1090 .map(|(key, value)| format!("{key}={value}"))
1091 .collect::<Vec<_>>()
1092 .join(",")
1093 )
1094 };
1095 result.insert(format!("{name}{suffix}"), raw);
1096 }
1097 }
1098 Ok(result)
1099}
1100
1101fn resolve_bake_target(
1102 name: &str,
1103 targets: &BTreeMap<String, RawBuild>,
1104 visiting: &mut HashSet<String>,
1105) -> Option<RawBuild> {
1106 if !visiting.insert(name.to_string()) {
1107 return None;
1108 }
1109 let target = targets.get(name)?;
1110 let mut result = RawBuild::default();
1111 for parent in &target.inherits {
1112 merge_raw(&mut result, resolve_bake_target(parent, targets, visiting)?);
1113 }
1114 merge_raw(&mut result, target.clone());
1115 visiting.remove(name);
1116 Some(result)
1117}
1118
1119fn merge_raw(base: &mut RawBuild, child: RawBuild) {
1120 base.source_paths.extend(child.source_paths.clone());
1121 if child.context.is_some() {
1122 base.context = child.context;
1123 }
1124 if child.dockerfile.is_some() {
1125 base.dockerfile = child.dockerfile;
1126 base.inline = false;
1127 }
1128 if child.target.is_some() {
1129 base.target = child.target;
1130 }
1131 base.args.extend(child.args);
1132 if !child.platforms.is_empty() {
1133 base.platforms = child.platforms;
1134 }
1135 base.contexts.extend(child.contexts);
1136 if !child.secrets.is_empty() {
1137 base.secrets = child.secrets;
1138 }
1139 if !child.ssh.is_empty() {
1140 base.ssh = child.ssh;
1141 }
1142 if !child.cache_from.is_empty() {
1143 base.cache_from = child.cache_from;
1144 }
1145 if !child.cache_to.is_empty() {
1146 base.cache_to = child.cache_to;
1147 }
1148 if !child.outputs.is_empty() {
1149 base.outputs = child.outputs;
1150 }
1151 if !child.attestations.is_empty() {
1152 base.attestations = child.attestations;
1153 }
1154 if !child.matrix.is_empty() {
1155 base.matrix = child.matrix;
1156 }
1157 if child.inline {
1158 base.inline = true;
1159 base.dockerfile = None;
1160 }
1161}
1162
1163fn annotate_bake_paths(raw: &mut RawBuild, name: &str) {
1164 let base = format!("target.{name}");
1165 let mut add = |field: &str, present: bool, source_name: &str| {
1166 if present {
1167 raw.source_paths
1168 .insert(field.to_string(), format!("{base}.{source_name}"));
1169 }
1170 };
1171 add("context", raw.context.is_some(), "context");
1172 add("dockerfile", raw.dockerfile.is_some(), "dockerfile");
1173 add("target", raw.target.is_some(), "target");
1174 add("platforms", !raw.platforms.is_empty(), "platforms");
1175 add("secrets", !raw.secrets.is_empty(), "secret");
1176 add("ssh", !raw.ssh.is_empty(), "ssh");
1177 add("cache_from", !raw.cache_from.is_empty(), "cache-from");
1178 add("cache_to", !raw.cache_to.is_empty(), "cache-to");
1179 add("outputs", !raw.outputs.is_empty(), "output");
1180 add("attestations", !raw.attestations.is_empty(), "attest");
1181 for key in raw.args.keys() {
1182 raw.source_paths
1183 .insert(format!("args.{key}"), format!("{base}.args.{key}"));
1184 }
1185 for key in raw.contexts.keys() {
1186 raw.source_paths
1187 .insert(format!("contexts.{key}"), format!("{base}.contexts.{key}"));
1188 }
1189}
1190
1191fn expand_matrix(raw: &RawBuild) -> Vec<(String, RawBuild)> {
1192 let combinations = matrix_combinations(&raw.matrix);
1193 if combinations.is_empty() {
1194 return Vec::new();
1195 }
1196 combinations
1197 .into_iter()
1198 .map(|values| {
1199 let mut expanded = raw.clone();
1200 expanded.matrix.clear();
1201 substitute_raw(&mut expanded, &values);
1202 let suffix = if values.is_empty() {
1203 String::new()
1204 } else {
1205 format!(
1206 "[{}]",
1207 values
1208 .iter()
1209 .map(|(key, value)| format!("{key}={value}"))
1210 .collect::<Vec<_>>()
1211 .join(",")
1212 )
1213 };
1214 (suffix, expanded)
1215 })
1216 .collect()
1217}
1218
1219fn matrix_combinations(matrix: &BTreeMap<String, Vec<String>>) -> Vec<BTreeMap<String, String>> {
1220 let mut combinations = vec![BTreeMap::<String, String>::new()];
1221 for (name, values) in matrix {
1222 let mut next = Vec::new();
1223 for combination in &combinations {
1224 for value in values {
1225 let mut expanded = combination.clone();
1226 expanded.insert(name.clone(), value.clone());
1227 next.push(expanded);
1228 }
1229 }
1230 combinations = next;
1231 }
1232 combinations
1233}
1234
1235fn substitute_raw(raw: &mut RawBuild, values: &BTreeMap<String, String>) {
1236 let substitute = |value: &mut String| {
1237 for (name, replacement) in values {
1238 *value = value.replace(&format!("${{{name}}}"), replacement);
1239 }
1240 };
1241 for value in [&mut raw.context, &mut raw.dockerfile, &mut raw.target]
1242 .into_iter()
1243 .flatten()
1244 {
1245 substitute(value);
1246 }
1247 for value in raw.args.values_mut() {
1248 if let RawValue::Value(value) = value {
1249 substitute(value);
1250 }
1251 }
1252 for value in raw
1253 .platforms
1254 .iter_mut()
1255 .chain(raw.contexts.values_mut())
1256 .chain(raw.cache_from.iter_mut())
1257 .chain(raw.cache_to.iter_mut())
1258 .chain(raw.outputs.iter_mut())
1259 .chain(raw.attestations.iter_mut())
1260 {
1261 substitute(value);
1262 }
1263}
1264
1265fn definition_files(paths: &[PathBuf], warnings: &mut Vec<String>) -> BTreeSet<PathBuf> {
1266 let requested = if paths.is_empty() {
1267 vec![PathBuf::from(".")]
1268 } else {
1269 paths.to_vec()
1270 };
1271 let mut result = BTreeSet::new();
1272 let mut expanded = Vec::new();
1273 for path in requested {
1274 let pattern = path.to_string_lossy();
1275 if pattern.contains(['*', '?', '[']) {
1276 match glob::glob(&pattern) {
1277 Ok(matches) => expanded.extend(matches.flatten()),
1278 Err(error) => warnings.push(format!("invalid path pattern {pattern:?}: {error}")),
1279 }
1280 } else {
1281 expanded.push(path);
1282 }
1283 }
1284 for path in expanded {
1285 if path.is_file() && (is_compose_file(&path) || is_bake_file(&path)) {
1286 result.insert(path);
1287 } else if path.is_dir() {
1288 let mut walker = WalkBuilder::new(&path);
1289 walker
1290 .follow_links(false)
1291 .hidden(false)
1292 .ignore(true)
1293 .git_ignore(true)
1294 .parents(true);
1295 for entry in walker.build() {
1296 match entry {
1297 Ok(entry) if entry.file_type().is_some_and(|value| value.is_file()) => {
1298 let path = entry.into_path();
1299 if is_compose_file(&path) || is_bake_file(&path) {
1300 result.insert(path);
1301 }
1302 }
1303 Err(error) => {
1304 warnings.push(format!("cannot inspect invocation definition: {error}"))
1305 }
1306 _ => {}
1307 }
1308 }
1309 }
1310 }
1311 result
1312}
1313
1314fn is_compose_file(path: &Path) -> bool {
1315 matches!(
1316 path.file_name().and_then(|value| value.to_str()),
1317 Some("compose.yaml" | "compose.yml" | "docker-compose.yaml" | "docker-compose.yml")
1318 )
1319}
1320
1321fn is_bake_file(path: &Path) -> bool {
1322 matches!(
1323 path.file_name().and_then(|value| value.to_str()),
1324 Some("docker-bake.hcl" | "docker-bake.json")
1325 )
1326}
1327
1328fn mapping_value<'a>(value: &'a YamlValue, key: &str) -> Option<&'a YamlValue> {
1329 value.as_mapping()?.get(YamlValue::String(key.to_string()))
1330}
1331
1332fn string_value(value: Option<&YamlValue>) -> Option<String> {
1333 value.and_then(YamlValue::as_str).map(str::to_string)
1334}
1335fn string_list(value: Option<&YamlValue>) -> Vec<String> {
1336 value
1337 .and_then(YamlValue::as_sequence)
1338 .map(|values| {
1339 values
1340 .iter()
1341 .filter_map(|value| value.as_str().map(str::to_string))
1342 .collect()
1343 })
1344 .unwrap_or_default()
1345}
1346fn yaml_scalar(value: &YamlValue) -> String {
1347 value.as_str().map(str::to_string).unwrap_or_else(|| {
1348 serde_yaml::to_string(value)
1349 .unwrap_or_default()
1350 .trim()
1351 .to_string()
1352 })
1353}
1354fn string_or_object_list(value: Option<&YamlValue>) -> Vec<String> {
1355 value
1356 .map(|value| match value {
1357 YamlValue::Sequence(values) => values.iter().map(yaml_scalar).collect(),
1358 _ => vec![yaml_scalar(value)],
1359 })
1360 .unwrap_or_default()
1361}
1362
1363fn yaml_key_values(value: Option<&YamlValue>) -> BTreeMap<String, RawValue> {
1364 let mut result = BTreeMap::new();
1365 match value {
1366 Some(YamlValue::Mapping(values)) => {
1367 for (key, value) in values {
1368 if let Some(key) = key.as_str() {
1369 result.insert(
1370 key.to_string(),
1371 if value.is_null() {
1372 RawValue::Inherit
1373 } else {
1374 RawValue::Value(yaml_scalar(value))
1375 },
1376 );
1377 }
1378 }
1379 }
1380 Some(YamlValue::Sequence(values)) => {
1381 for value in values.iter().filter_map(YamlValue::as_str) {
1382 if let Some((key, value)) = value.split_once('=') {
1383 result.insert(key.to_string(), RawValue::Value(value.to_string()));
1384 } else {
1385 result.insert(value.to_string(), RawValue::Inherit);
1386 }
1387 }
1388 }
1389 _ => {}
1390 }
1391 result
1392}
1393
1394fn yaml_named_values(value: Option<&YamlValue>) -> BTreeMap<String, String> {
1395 let mut result = BTreeMap::new();
1396 match value {
1397 Some(YamlValue::Mapping(values)) => {
1398 for (key, value) in values {
1399 if let Some(key) = key.as_str() {
1400 result.insert(key.to_string(), yaml_scalar(value));
1401 }
1402 }
1403 }
1404 Some(YamlValue::Sequence(values)) => {
1405 for value in values.iter().filter_map(YamlValue::as_str) {
1406 if let Some((key, value)) = value.split_once('=') {
1407 result.insert(key.to_string(), value.to_string());
1408 }
1409 }
1410 }
1411 _ => {}
1412 }
1413 result
1414}
1415
1416fn yaml_declarations(value: Option<&YamlValue>) -> Vec<(String, Option<String>)> {
1417 value
1418 .and_then(YamlValue::as_sequence)
1419 .map(|values| {
1420 values
1421 .iter()
1422 .filter_map(|value| match value {
1423 YamlValue::String(id) => Some((id.clone(), None)),
1424 YamlValue::Mapping(_) => {
1425 let id = mapping_value(value, "source")
1426 .or_else(|| mapping_value(value, "id"))
1427 .and_then(YamlValue::as_str)?;
1428 let target = mapping_value(value, "target")
1429 .and_then(YamlValue::as_str)
1430 .map(str::to_string);
1431 Some((id.to_string(), target))
1432 }
1433 _ => None,
1434 })
1435 .collect()
1436 })
1437 .unwrap_or_default()
1438}
1439
1440fn json_string(value: Option<&JsonValue>) -> Option<String> {
1441 value.and_then(JsonValue::as_str).map(str::to_string)
1442}
1443fn json_strings(value: Option<&JsonValue>) -> Vec<String> {
1444 match value {
1445 Some(JsonValue::String(value)) => vec![value.clone()],
1446 Some(JsonValue::Array(values)) => values
1447 .iter()
1448 .map(|value| {
1449 value
1450 .as_str()
1451 .map(str::to_string)
1452 .unwrap_or_else(|| value.to_string())
1453 })
1454 .collect(),
1455 _ => Vec::new(),
1456 }
1457}
1458fn json_named_values(value: Option<&JsonValue>) -> BTreeMap<String, String> {
1459 value
1460 .and_then(JsonValue::as_object)
1461 .map(|values| {
1462 values
1463 .iter()
1464 .map(|(key, value)| {
1465 (
1466 key.clone(),
1467 value
1468 .as_str()
1469 .map(str::to_string)
1470 .unwrap_or_else(|| value.to_string()),
1471 )
1472 })
1473 .collect()
1474 })
1475 .unwrap_or_default()
1476}
1477fn json_key_values(value: Option<&JsonValue>) -> BTreeMap<String, RawValue> {
1478 value
1479 .and_then(JsonValue::as_object)
1480 .map(|values| {
1481 values
1482 .iter()
1483 .map(|(key, value)| {
1484 (
1485 key.clone(),
1486 if value.is_null() {
1487 RawValue::Inherit
1488 } else {
1489 RawValue::Value(
1490 value
1491 .as_str()
1492 .map(str::to_string)
1493 .unwrap_or_else(|| value.to_string()),
1494 )
1495 },
1496 )
1497 })
1498 .collect()
1499 })
1500 .unwrap_or_default()
1501}
1502fn json_matrix(value: Option<&JsonValue>) -> BTreeMap<String, Vec<String>> {
1503 value
1504 .and_then(JsonValue::as_object)
1505 .map(|values| {
1506 values
1507 .iter()
1508 .map(|(key, value)| (key.clone(), json_strings(Some(value))))
1509 .collect()
1510 })
1511 .unwrap_or_default()
1512}
1513fn json_declarations(value: Option<&JsonValue>) -> Vec<(String, Option<String>)> {
1514 json_strings(value)
1515 .into_iter()
1516 .map(|value| {
1517 let mut id = value.clone();
1518 let mut target = None;
1519 for field in value.split(',') {
1520 if let Some(value) = field.strip_prefix("id=") {
1521 id = value.to_string();
1522 }
1523 if let Some(value) = field.strip_prefix("target=") {
1524 target = Some(value.to_string());
1525 }
1526 }
1527 (id, target)
1528 })
1529 .collect()
1530}
1531
1532fn hcl_attribute<'a>(block: &'a hcl::Block, key: &str) -> Option<&'a Expression> {
1533 block
1534 .body
1535 .attributes()
1536 .find(|attribute| attribute.key() == key)
1537 .map(|attribute| attribute.expr())
1538}
1539fn block_label(label: Option<&BlockLabel>) -> Option<&str> {
1540 match label? {
1541 BlockLabel::Identifier(value) => Some(value.as_str()),
1542 BlockLabel::String(value) => Some(value),
1543 }
1544}
1545
1546fn sensitive_name(name: &str) -> bool {
1547 let name = name.to_ascii_lowercase();
1548 [
1549 "secret",
1550 "password",
1551 "passwd",
1552 "token",
1553 "credential",
1554 "private_key",
1555 "auth",
1556 ]
1557 .iter()
1558 .any(|part| name.contains(part))
1559}
1560fn resolved(value: String, provenance: Provenance) -> EffectiveValue {
1561 resolved_with(value, vec![provenance])
1562}
1563fn resolved_with(value: String, provenance: Vec<Provenance>) -> EffectiveValue {
1564 EffectiveValue {
1565 state: ValueState::Resolved,
1566 value: Some(value),
1567 expression: None,
1568 provenance,
1569 }
1570}
1571fn unresolved(expression: impl Into<String>, provenance: Provenance) -> EffectiveValue {
1572 unresolved_with(expression.into(), vec![provenance])
1573}
1574fn unresolved_with(expression: String, provenance: Vec<Provenance>) -> EffectiveValue {
1575 EffectiveValue {
1576 state: ValueState::Unresolved,
1577 value: None,
1578 expression: Some(expression),
1579 provenance,
1580 }
1581}
1582fn redacted(_expression: &str, provenance: Provenance) -> EffectiveValue {
1583 EffectiveValue {
1584 state: ValueState::Redacted,
1585 value: None,
1586 expression: None,
1587 provenance: vec![provenance],
1588 }
1589}
1590fn provenance(kind: &str, source: &str, path: &str, precedence: u32) -> Provenance {
1591 Provenance {
1592 kind: kind.into(),
1593 source: source.into(),
1594 path: path.into(),
1595 precedence,
1596 line: None,
1597 column: None,
1598 }
1599}
1600
1601fn display_path(path: &Path) -> String {
1602 let path = canonicalish(path);
1603 let display = std::env::current_dir()
1604 .ok()
1605 .and_then(|cwd| {
1606 path.strip_prefix(canonicalish(&cwd))
1607 .ok()
1608 .map(Path::to_path_buf)
1609 })
1610 .unwrap_or(path);
1611 let value = display.to_string_lossy().replace('\\', "/");
1612 if value.is_empty() {
1613 ".".into()
1614 } else {
1615 value
1616 }
1617}
1618
1619fn canonicalish(path: &Path) -> PathBuf {
1620 path.canonicalize().unwrap_or_else(|_| {
1621 if path.is_absolute() {
1622 path.to_path_buf()
1623 } else {
1624 std::env::current_dir()
1625 .unwrap_or_else(|_| PathBuf::from("."))
1626 .join(path)
1627 }
1628 })
1629}
1630
1631fn resolved_pair(invocation: &BuildInvocation) -> Option<(PathBuf, PathBuf)> {
1632 Some((
1633 canonicalish(Path::new(invocation.dockerfile.value.as_ref()?)),
1634 canonicalish(Path::new(invocation.context.value.as_ref()?)),
1635 ))
1636}
1637
1638#[cfg(test)]
1639mod tests {
1640 use super::*;
1641
1642 #[test]
1643 fn unresolved_interpolation_is_not_replaced_with_empty_text() {
1644 match interpolate("images/${MISSING}/Dockerfile", &BTreeMap::new()) {
1645 Interpolation::Unresolved(expression, _) => {
1646 assert_eq!(expression, "images/${MISSING}/Dockerfile")
1647 }
1648 Interpolation::Resolved(..) => panic!("missing variable was resolved"),
1649 }
1650 }
1651
1652 #[test]
1653 fn matrix_expansion_is_deterministic() {
1654 let raw = RawBuild {
1655 context: Some("${arch}".into()),
1656 matrix: BTreeMap::from([("arch".into(), vec!["amd64".into(), "arm64".into()])]),
1657 ..RawBuild::default()
1658 };
1659 let values = expand_matrix(&raw);
1660 assert_eq!(values[0].0, "[arch=amd64]");
1661 assert_eq!(values[1].1.context.as_deref(), Some("arm64"));
1662 }
1663
1664 #[test]
1665 fn hcl_matrix_values_resolve_and_unknown_arguments_remain_unresolved() {
1666 let targets = parse_bake_hcl(
1667 r#"
1668target "release" {
1669 matrix = { arch = ["amd64", "arm64"] }
1670 platforms = ["linux/${arch}"]
1671 args = { ARCH = arch, UNKNOWN = missing_value }
1672}
1673"#,
1674 )
1675 .unwrap();
1676 let amd64 = &targets["release[arch=amd64]"];
1677 assert_eq!(amd64.platforms, vec!["linux/amd64"]);
1678 assert!(matches!(amd64.args["ARCH"], RawValue::Value(ref value) if value == "amd64"));
1679 assert!(matches!(amd64.args["UNKNOWN"], RawValue::Unresolved(_)));
1680 }
1681
1682 #[test]
1683 fn invocation_lint_deduplicates_only_identical_effective_inputs() {
1684 let root =
1685 std::env::temp_dir().join(format!("droast-invocation-lint-{}", std::process::id()));
1686 let _ = std::fs::remove_dir_all(&root);
1687 std::fs::create_dir_all(&root).unwrap();
1688 std::fs::write(root.join("Dockerfile"), "FROM alpine as build\n").unwrap();
1689 std::fs::write(
1690 root.join("compose.yaml"),
1691 "services:\n one:\n build: .\n two:\n build: .\n",
1692 )
1693 .unwrap();
1694 let mut document = discover(std::slice::from_ref(&root), ContainerEngine::Docker);
1695 assert_eq!(document.invocations.len(), 2);
1696 let options = crate::linter::LintOptions {
1697 only_rules: vec!["DF079".into()],
1698 check_dockerignore: false,
1699 ..crate::linter::LintOptions::default()
1700 };
1701 let identical = lint(&document, &options).unwrap();
1702 assert_eq!(identical.len(), 1);
1703 assert_eq!(identical[0].invocation_ids.len(), 2);
1704
1705 document.invocations[0].build_args.insert(
1706 "MODE".into(),
1707 resolved("release".into(), provenance("test", "test", "MODE", 0)),
1708 );
1709 let different = lint(&document, &options).unwrap();
1710 assert_eq!(different.len(), 2);
1711 assert!(different
1712 .iter()
1713 .all(|finding| finding.invocation_ids.len() == 1));
1714 std::fs::remove_dir_all(root).unwrap();
1715 }
1716}