Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/versions/v5/native/existing-compose-project.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ the service and the field, and prints the command that runs it there.

An image is reused while its build inputs are unchanged: the Dockerfile, the ignore
file, the target, the args, and every file in the build context the ignore file lets
the build read. Change any of them and the next `up` builds again, also after
the build read. Native always leaves Hack's machine-local files out of its build
context, including `.hack/.internal/`, `.hack/.branch/`, `.hack/.env` and the
checkout's `.hack.secret.key`. Explicitly copying one of these paths in the
Dockerfile fails. Change any included input and the next `up` builds again, also after
`hack down`; the run's containers are then recreated from the new image and named
volumes are kept. `hack restart` checks the same inputs before it stops anything: a
build that fails leaves the current project running, and a rebuilt image is what the
Expand Down
6 changes: 6 additions & 0 deletions docs/versions/v5/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ flowchart LR
Follow [Upgrade from v4](upgrade.md). It is a backup-first procedure, and it
says how to go back.

### Native build contexts

Native builds exclude machine-local `.hack/` state, including generated Compose
env overrides, and the checkout's `.hack.secret.key`. Changes to that state no
longer trigger rebuilds.

## 2. What you will notice every day

**`hack env list` hides every value.** It shows names, scopes and source files.
Expand Down
1 change: 1 addition & 0 deletions packages/runtime-core/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ fn build_runtime_identity() {
"Cargo.toml",
"Cargo.lock",
"../config-compiler/src",
"../../src/project-private-files.json",
"../config-compiler/Cargo.toml",
] {
hash_path(&mut hash, Path::new(path));
Expand Down
11 changes: 6 additions & 5 deletions packages/runtime-core/src/project/generated.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//! Explicit public bytes, never a request to read an ignored host file.
use super::private_files::generated_state_child;
use super::{CandidateError, PlanData, problem};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::Path;
use std::{ffi::OsStr, path::Path};

pub(super) fn refused() -> CandidateError {
problem(
Expand Down Expand Up @@ -45,10 +46,10 @@ pub(super) fn declarations(files: &BTreeMap<String, String>) -> Result<(), Candi
|| lower == ".env"
|| lower.starts_with(".env.")
})
|| path == ".hack/.internal"
|| path == ".hack/.branch"
|| path.starts_with(".hack/.internal/")
|| path.starts_with(".hack/.branch/")
|| path.split_once('/').is_some_and(|(parent, tail)| {
let child = tail.split('/').next().unwrap_or(tail);
generated_state_child(OsStr::new(parent), OsStr::new(child))
})
|| content.len() > 16384
|| content
.chars()
Expand Down
1 change: 1 addition & 0 deletions packages/runtime-core/src/project/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub mod inputs;
pub mod live_source;
#[cfg(feature = "native-config-plan")]
pub mod native;
pub(crate) mod private_files;
pub mod registry;
pub mod snapshot;
mod source;
Expand Down
25 changes: 25 additions & 0 deletions packages/runtime-core/src/project/private_files.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use serde::Deserialize;
use std::{ffi::OsStr, sync::LazyLock};

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Policy {
pub(crate) env_key: String,
pub(crate) private_staging_dir: String,
generated_state_dirs: Vec<String>,
pub(crate) hack_dir_ignore: Vec<String>,
}

pub(crate) static POLICY: LazyLock<Policy> = LazyLock::new(|| {
serde_json::from_str(include_str!("../../../../src/project-private-files.json"))
.expect("embedded project private files policy")
});

/// State directories owned by Hack inside its project configuration directory.
pub(crate) fn generated_state_child(parent: &OsStr, name: &OsStr) -> bool {
parent.eq_ignore_ascii_case(".hack")
&& POLICY
.generated_state_dirs
.iter()
.any(|dir| name.eq_ignore_ascii_case(dir))
}
3 changes: 2 additions & 1 deletion packages/runtime-core/src/project/source.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::private_files::generated_state_child;
use super::{Diagnostic, problem};
use crate::CandidateError;
use caseless::Caseless;
Expand Down Expand Up @@ -169,7 +170,7 @@ pub fn excluded(path: &Path) -> bool {
|| [".pem", ".key", ".p12", ".pfx"]
.iter()
.any(|suffix| lower.ends_with(suffix))
|| (index > 0 && parts[index - 1] == ".hack" && [".internal", ".branch"].contains(part))
|| (index > 0 && generated_state_child(parts[index - 1].as_ref(), part.as_ref()))
{
return true;
}
Expand Down
69 changes: 67 additions & 2 deletions packages/runtime-core/src/provider/build_scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,13 @@ fn refusal(line: Option<usize>, message: &str) -> CandidateError {

/// Scan a Dockerfile for the images a native build of `request.target` can pull.
pub fn scan(request: &ScanRequest<'_>) -> Result<DockerfileScan, CandidateError> {
scan_with_context(request, &|_| Ok(false))
}

pub(super) fn scan_with_context(
request: &ScanRequest<'_>,
private: &dyn Fn(&str) -> Result<bool, CandidateError>,
) -> Result<DockerfileScan, CandidateError> {
validate_arguments(request.args)?;
if request.dockerfile.len() > MAX_DOCKERFILE_BYTES {
return Err(refusal(None, "exceeds the 1 MiB scan limit."));
Expand All @@ -152,7 +159,7 @@ pub fn scan(request: &ScanRequest<'_>) -> Result<DockerfileScan, CandidateError>
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
refuse_frontend_selection(text)?;
let parsed = parse(text)?;
resolve(&parsed, request)
resolve(&parsed, request, private)
}

fn validate_arguments(args: &BTreeMap<String, String>) -> Result<(), CandidateError> {
Expand Down Expand Up @@ -219,6 +226,8 @@ struct RawStage {
name: Option<String>,
uses: Vec<Use>,
onbuild: Vec<Use>,
copies: Vec<String>,
onbuild_copies: Vec<String>,
}

#[derive(Debug, Default)]
Expand Down Expand Up @@ -884,6 +893,8 @@ fn dispatch(
name,
uses: Vec::new(),
onbuild: Vec::new(),
copies: Vec::new(),
onbuild_copies: Vec::new(),
});
}
"arg" => {
Expand Down Expand Up @@ -925,18 +936,66 @@ fn dispatch(
let uses = instruction_uses(&inner, escape, line)?;
if let Some(stage) = parsed.stages.last_mut() {
stage.onbuild.extend(uses);
record_local_copies(&inner, escape, line, &mut stage.onbuild_copies)?;
}
}
_ => {
let uses = instruction_uses(&instruction, escape, line)?;
if let Some(stage) = parsed.stages.last_mut() {
stage.uses.extend(uses);
record_local_copies(&instruction, escape, line, &mut stage.copies)?;
}
}
}
Ok(())
}

/// Keep literal local sources for the context policy. Dynamic expansions and
/// globs still see only the filtered snapshot.
fn record_local_copies(
instruction: &Instruction,
escape: char,
line: usize,
copies: &mut Vec<String>,
) -> Result<(), CandidateError> {
if instruction.command != "copy" {
return Ok(());
}
if parse_flags(&instruction.flags, &COPY_FLAGS, line)?.contains_key("from") {
return Ok(());
}
let (words, json) = match json_words(&instruction.args, line)? {
Some(words) => (words, true),
None => (argument_words(&instruction.args, escape), false),
};
for word in words.iter().take(words.len().saturating_sub(1)) {
let value = if json && !word.contains('$') {
Some(word.clone())
} else {
argument_value(word, &Env::new(), MAX_DOCKERFILE_BYTES)
};
if let Some(value) = value {
copies.push(value);
}
}
Ok(())
}

fn check_local_copies(
copies: &[String],
private: &dyn Fn(&str) -> Result<bool, CandidateError>,
) -> Result<(), CandidateError> {
for source in copies {
if !source.starts_with("<<") && private(source)? {
return Err(CandidateError::new(
"native_build_copy_private",
"COPY names Hack's own machine-local file or directory, which is never sent to a build.",
));
}
}
Ok(())
}

/// Port of the frontend's `parseWords`: whitespace-separated words, quotes kept,
/// the escape token keeping the character it escapes.
fn argument_words(text: &str, escape: char) -> Vec<String> {
Expand Down Expand Up @@ -1197,7 +1256,11 @@ fn base_image(name: &str, line: usize) -> Result<BaseImage, CandidateError> {
}
}

fn resolve(parsed: &Parsed, request: &ScanRequest<'_>) -> Result<DockerfileScan, CandidateError> {
fn resolve(
parsed: &Parsed,
request: &ScanRequest<'_>,
private: &dyn Fn(&str) -> Result<bool, CandidateError>,
) -> Result<DockerfileScan, CandidateError> {
let env = global_env(parsed, request.args);
// Each stage's base as the frontend registers it: an earlier stage of that name,
// `scratch`, or an image. `None` marks a name the scanner cannot expand. Stage
Expand Down Expand Up @@ -1238,6 +1301,7 @@ fn resolve(parsed: &Parsed, request: &ScanRequest<'_>) -> Result<DockerfileScan,
continue;
}
let stage = &parsed.stages[index];
check_local_copies(&stage.copies, private)?;
if let Some(platform) = &stage.platform {
if !platform_supported(platform, &env, parsed) {
return Err(refusal(
Expand All @@ -1263,6 +1327,7 @@ fn resolve(parsed: &Parsed, request: &ScanRequest<'_>) -> Result<DockerfileScan,
// frontend's inheritance, so no trigger image is missed).
let mut ancestor = &bases[index];
while let Some(Source::Stage(parent)) = ancestor {
check_local_copies(&parsed.stages[*parent].onbuild_copies, private)?;
for used in &parsed.stages[*parent].onbuild {
sources.push((use_source(parsed, used)?, used.line));
}
Expand Down
26 changes: 21 additions & 5 deletions packages/runtime-core/src/provider/image_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,20 @@ pub(super) fn prepare(request: BuildRequest, builds: &Path) -> Result<Inputs, Ca
"The build context must be an existing project directory.",
));
}
let private = context::private::PrivateFiles::new()?;
if private.excludes(&context)? {
return Err(refusal(
"native_build_source",
"The build context is Hack's own machine-local directory, which is never sent to a build.",
));
}
let dockerfile = crate::project::resolve_source(&root, &context, &request.dockerfile, false)?;
if private.excludes(&dockerfile)? {
return Err(refusal(
"native_build_source",
"The Dockerfile is Hack's own machine-local file, which is never sent to a build.",
));
}
// Every input file is read through descriptors held from the project root down.
let project = context::ProjectRoot::open(&root)?;
let bytes = project
Expand All @@ -559,11 +572,14 @@ pub(super) fn prepare(request: BuildRequest, builds: &Path) -> Result<Inputs, Ca
"The Dockerfile must be an existing regular project file.",
)
})?;
let scan = build_scan::scan(&build_scan::ScanRequest {
dockerfile: &bytes,
target: request.target.as_deref(),
args: &request.args,
})?;
let scan = build_scan::scan_with_context(
&build_scan::ScanRequest {
dockerfile: &bytes,
target: request.target.as_deref(),
args: &request.args,
},
&|source| private.copy_source(&context, source),
)?;
let namespace = namespace(&root, request.branch.as_deref());
let relative = |path: &Path, base: &Path| -> String {
path.strip_prefix(base)
Expand Down
8 changes: 8 additions & 0 deletions packages/runtime-core/src/provider/image_build/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ use std::{

mod fsat;
pub(super) mod ignore;
pub(super) mod private;
pub(super) mod snapshot;
#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -603,6 +604,7 @@ pub(super) fn digest(
bounds: Bounds,
) -> Result<ContextDigest, CandidateError> {
let rules = ignore::Rules::parse(ignore)?;
let private = private::PrivateFiles::new()?;
let id = context_id(context);
let mut walk = Walk {
bounds,
Expand Down Expand Up @@ -656,7 +658,13 @@ pub(super) fn digest(
read_error,
)?;
walk.keep(listing)?;
let parent = Path::new(std::ffi::OsStr::from_bytes(&relative))
.file_name()
.or_else(|| context.file_name());
for name in names {
if private.excludes_child(parent, std::ffi::OsStr::from_bytes(&name))? {
continue;
}
let mut child = relative.clone();
if !child.is_empty() {
child.push(b'/');
Expand Down
Loading
Loading