diff --git a/README.md b/README.md index 61babbc1..962bbe59 100644 --- a/README.md +++ b/README.md @@ -214,9 +214,11 @@ skips binaries and proc-macros. tinymold caches every rustc call cargo makes, `cargo llvm-cov`, and passing test runs. **It never trades correctness for speed.** Anything that is an input is in the -key; anything that is not stays out. Objects are immutable once stored, and a -remote server can only make a build miss, never restore different bytes. When -in doubt, tinymold misses. +key; anything that is not stays out. Objects are immutable once stored, and remote blobs are checked against their +digests. Use trusted signing keys to authenticate remote records: a writer +without that protection can poison build outputs despite valid hashes. See +[cache security](docs/specs/cache-security.md) before sharing a cache with +public pull-request jobs. When in doubt, tinymold misses. The cache never links for you: a binary that depends on the crate you edited is still relinked in full, while unchanged crates, binaries and test diff --git a/crates/tinymold-remote/src/remote/mod.rs b/crates/tinymold-remote/src/remote/mod.rs index c89e357d..fc3e845b 100644 --- a/crates/tinymold-remote/src/remote/mod.rs +++ b/crates/tinymold-remote/src/remote/mod.rs @@ -49,6 +49,21 @@ pub use types::{Capabilities, PushReport}; /// How many digests one `FindMissingBlobs` call asks about. const FIND_BATCH: usize = 1000; +/// Metadata is much smaller than artifacts. Check server-supplied sizes +/// before opening a stream, including before signature verification. +const MAX_RECORD: i64 = 16 << 20; +const MAX_SIGNATURE: i64 = 1024; + +fn metadata_size(digest: &proto::Digest, limit: i64) -> Result<()> { + if digest.size_bytes < 0 || digest.size_bytes > limit { + return Err(Error::BlobSize { + hash: digest.hash.clone(), + size: digest.size_bytes, + }); + } + Ok(()) +} + /// How many calls `push` and a fetch keep in flight at once. Each is a round /// trip; a CI runner an ocean away from its cache spends most of a call /// waiting, and one at a time leaves the link nearly idle. @@ -433,6 +448,7 @@ impl RemoteCache { key: key.hash.clone(), reason: "it is not signed", })?; + metadata_size(&signature, MAX_SIGNATURE)?; let blob = self.client.read(&signature).await?; trusted.verify(kind, key, record, &blob) } @@ -444,6 +460,7 @@ impl RemoteCache { return Ok(None); }; let digest = find_file(&result, PREKEY_FILE, &key)?; + metadata_size(&digest, MAX_RECORD)?; // The record is only used once the signature checks out, but // reading both at once saves a round trip. A refused signature // drops the read at once, whatever the server is sending. @@ -468,12 +485,24 @@ impl RemoteCache { return Ok(None); }; let record = find_file(&result, ACTION_FILE, &key)?; + metadata_size(&record, MAX_RECORD)?; // Before any object: an untrusted entry fetches nothing. self.verify(Kind::Action, &key, &record, &result).await?; let malformed = |reason| Error::Malformed { key: key.hash.clone(), reason, }; + // The signature authenticates the record, not the server's + // output list. Parse it before fetching any artifact so a server + // cannot graft arbitrary downloads onto a valid signed entry. + let bytes = self.client.read(&record).await?; + let text = + String::from_utf8(bytes).map_err(|_| malformed("its action record is not text"))?; + let references: HashSet<_> = + tinymold_wrap::action_references_from_text(&text, Path::new(ACTION_FILE))? + .into_iter() + .collect(); + let mut listed = HashSet::new(); let mut wanted = Vec::new(); for file in &result.output_files { if file.path == ACTION_FILE || file.path == SIGNATURE_FILE { @@ -481,56 +510,38 @@ impl RemoteCache { } let name = Digest::from_str(&file.path) .map_err(|_| malformed("an output is not named by its digest"))?; - if store.contains(&name) { - continue; + if !references.contains(&name) || !listed.insert(name) { + return Err(malformed("outputs do not match the action record")); } let digest = file .digest .clone() .ok_or_else(|| malformed("an output has no digest"))?; - wanted.push((name, digest)); + if !store.contains(&name) { + wanted.push((blob_size(&digest), (name, digest))); + } + } + if listed != references { + return Err(malformed("outputs do not match the action record")); } - // Every object, and the record, in flight together under one - // limit: each read is a round trip. Each object goes into the - // store as it arrives, so memory holds only what is in flight. - let reads = std::iter::once((blob_size(&record), None)) - .chain( - wanted - .into_iter() - .map(|(name, digest)| (blob_size(&digest), Some((name, digest)))), - ) - .collect(); - let mut text = None; + // Fetch only the objects the parsed record authorizes, keeping + // the ordinary byte budget and parallel artifact downloads. in_flight( - reads, - |object| { - let record = &record; - async move { - let (name, digest) = match object { - Some((name, digest)) => (Some(name), digest), - None => (None, record.clone()), - }; - let bytes = self.client.read_sharing(&digest, IN_FLIGHT_BYTES).await; - (name, bytes) - } + wanted, + |(name, digest)| async move { + let bytes = self.client.read_sharing(&digest, IN_FLIGHT_BYTES).await; + (name, bytes) }, - |(name, bytes)| match name { - None => { - text = Some(bytes?); + |(name, bytes)| { + if store.insert_bytes(&bytes?)? == name { Ok(()) + } else { + Err(malformed("an output does not match its name")) } - Some(name) if store.insert_bytes(&bytes?)? == name => Ok(()), - Some(_) => Err(malformed("an output does not match its name")), }, ) .await?; - let text = text.ok_or_else(|| malformed("its action record was never read"))?; - String::from_utf8(text) - .map(Some) - .map_err(|_| Error::Malformed { - key: key.hash, - reason: "its action record is not text", - }) + Ok(Some(text)) }) } } diff --git a/crates/tinymold-remote/src/remote/test.rs b/crates/tinymold-remote/src/remote/test.rs index ff7578f3..4bf72057 100644 --- a/crates/tinymold-remote/src/remote/test.rs +++ b/crates/tinymold-remote/src/remote/test.rs @@ -865,7 +865,7 @@ fn entries_tinymold_did_not_write_are_refused() { )); let unnamed = fetch_error(vec![ - (ACTION_FILE.to_owned(), b"record".to_vec()), + (ACTION_FILE.to_owned(), record_for(b"x")), ("libdemo.rlib".to_owned(), b"x".to_vec()), ]); assert!(matches!( @@ -877,7 +877,7 @@ fn entries_tinymold_did_not_write_are_refused() { )); let misnamed = fetch_error(vec![ - (ACTION_FILE.to_owned(), b"record".to_vec()), + (ACTION_FILE.to_owned(), record_for(b"other")), (Digest::of_bytes(b"other").to_hex(), b"x".to_vec()), ]); assert!(matches!( @@ -905,7 +905,7 @@ fn an_output_without_a_digest_is_refused() { plant( &server, &key, - vec![(ACTION_FILE.to_owned(), b"record".to_vec())], + vec![(ACTION_FILE.to_owned(), record_for(b"x"))], ); server.with(|state| { let result = state @@ -1082,3 +1082,185 @@ fn a_cache_outage_stops_queued_refreshes_instead_of_retrying_every_action() { "queued actions repeated a cache-wide outage: {attempts} calls" ); } + +#[test] +fn an_oversized_signature_is_refused_before_downloading_it() { + let server = Server::start(); + let local = Local::new(); + let signer = SigningKey::generate(); + configured(&server, signing(&signer)) + .push(&local.root, None) + .unwrap(); + server.with(|state| { + let result = state + .actions + .get_mut(&naming::action_key(&local.key).hash) + .unwrap(); + let signature = result + .output_files + .iter_mut() + .find(|file| file.path == SIGNATURE_FILE) + .unwrap(); + signature.digest.as_mut().unwrap().size_bytes = 1025; + }); + let reads = server.with(|state| state.peak_in_flight.get("Read").copied()); + let empty = tempfile::tempdir().unwrap(); + let store = Store::open(empty.path()).unwrap(); + let result = configured(&server, trusting(&signer)).fetch_action_into(&local.key, &store); + assert!( + matches!(result, Err(Error::BlobSize { size: 1025, .. })), + "{result:?}" + ); + assert_eq!( + server.with(|state| state.peak_in_flight.get("Read").copied()), + reads + ); +} + +#[test] +fn oversized_remote_records_are_refused_before_downloading_them() { + let server = Server::start(); + let local = Local::new(); + remote(&server).push(&local.root, None).unwrap(); + server.with(|state| { + for result in state.actions.values_mut() { + for file in &mut result.output_files { + if file.path == ACTION_FILE || file.path == PREKEY_FILE { + file.digest.as_mut().unwrap().size_bytes = (16 << 20) + 1; + } + } + } + }); + let reads = server.with(|state| state.peak_in_flight.get("Read").copied()); + let empty = tempfile::tempdir().unwrap(); + let store = Store::open(empty.path()).unwrap(); + let reader = remote(&server); + assert!(matches!( + reader.fetch_action_into(&local.key, &store), + Err(Error::BlobSize { .. }) + )); + assert!(matches!( + reader.input_sets_of(&local.pre), + Err(Error::BlobSize { .. }) + )); + assert_eq!( + server.with(|state| state.peak_in_flight.get("Read").copied()), + reads + ); +} + +#[test] +fn a_signed_record_does_not_authorize_an_unrelated_extra_blob() { + let server = Server::start(); + let local = Local::new(); + let signer = SigningKey::generate(); + configured(&server, signing(&signer)) + .push(&local.root, None) + .unwrap(); + let bytes = b"attacker controlled extra object"; + let extra = Digest::of_bytes(bytes); + server.with(|state| { + let digest = naming::blob(bytes); + state.blobs.insert(digest.hash.clone(), bytes.to_vec()); + state + .actions + .get_mut(&naming::action_key(&local.key).hash) + .unwrap() + .output_files + .push(output(&extra.to_hex(), digest)); + }); + let empty = tempfile::tempdir().unwrap(); + let store = Store::open(empty.path()).unwrap(); + let result = configured(&server, trusting(&signer)).fetch_action_into(&local.key, &store); + assert!(matches!(result, Err(Error::Malformed { .. })), "{result:?}"); + assert!(!store.contains(&extra)); + for object in &local.objects { + assert!( + !store.contains(object), + "refuse the entry before fetching artifacts" + ); + } +} + +/// A valid action that references just the supplied diagnostic bytes. +fn record_for(bytes: &[u8]) -> Vec { + let digest = Digest::of_bytes(bytes); + format!("tinymold-action 1\nstdout {digest}\nstderr {digest}\n").into_bytes() +} + +#[test] +fn metadata_size_limits_include_the_boundary_and_reject_negative_sizes() { + for limit in [MAX_RECORD, MAX_SIGNATURE] { + let mut digest = naming::blob(b""); + digest.size_bytes = limit; + assert!(metadata_size(&digest, limit).is_ok()); + for size in [-1, limit + 1] { + digest.size_bytes = size; + assert!(matches!( + metadata_size(&digest, limit), + Err(Error::BlobSize { .. }) + )); + } + } +} + +#[test] +fn missing_and_duplicate_action_objects_are_refused_even_when_cached_locally() { + for duplicate in [false, true] { + let server = Server::start(); + let local = Local::new(); + remote(&server).push(&local.root, None).unwrap(); + server.with(|state| { + let result = state + .actions + .get_mut(&naming::action_key(&local.key).hash) + .unwrap(); + if duplicate { + let file = result + .output_files + .iter() + .find(|file| file.path != ACTION_FILE) + .unwrap() + .clone(); + result.output_files.push(file); + } else { + result + .output_files + .retain(|file| file.path != local.objects[1].to_hex()); + } + }); + let result = remote(&server).fetch_action_into(&local.key, &local.store); + assert!( + matches!( + result, + Err(Error::Malformed { + reason: "outputs do not match the action record", + .. + }) + ), + "{result:?}" + ); + } +} + +#[test] +fn a_malformed_record_is_refused_before_any_artifact_is_stored() { + let server = Server::start(); + let key = Digest::of_bytes(b"malformed"); + let object = Digest::of_bytes(b"artifact"); + plant( + &server, + &key, + vec![ + (ACTION_FILE.to_owned(), b"not an action".to_vec()), + (object.to_hex(), b"artifact".to_vec()), + ], + ); + let empty = tempfile::tempdir().unwrap(); + let store = Store::open(empty.path()).unwrap(); + assert!(matches!( + remote(&server).fetch_action_into(&key, &store), + Err(Error::Wrap(_)) + )); + assert!(!store.contains(&object)); +} diff --git a/crates/tinymold-remote/src/signing/mod.rs b/crates/tinymold-remote/src/signing/mod.rs index 7a5301a2..d2577835 100644 --- a/crates/tinymold-remote/src/signing/mod.rs +++ b/crates/tinymold-remote/src/signing/mod.rs @@ -4,7 +4,8 @@ //! A cache server decides who may write, and a server set up wrong lets //! anyone write. With [`TrustedKeys`] configured, the client stops depending //! on that: an entry that a trusted [`SigningKey`] did not sign is refused, -//! so the worst an open server can do is make a build miss. +//! so an open server cannot forge a trusted record. It can still withhold +//! entries or consume resources up to the client's limits. //! //! The signature is a blob of its own, listed in the entry's `ActionResult` //! as [`SIGNATURE_FILE`]. It signs [`message`]: the entry's kind, its diff --git a/crates/tinymold-server/src/front/reapi/mod.rs b/crates/tinymold-server/src/front/reapi/mod.rs index fd49305f..56b639a4 100644 --- a/crates/tinymold-server/src/front/reapi/mod.rs +++ b/crates/tinymold-server/src/front/reapi/mod.rs @@ -343,18 +343,22 @@ async fn batch_read_blobs( let (metadata, _, request) = call.into_parts(); check_function(request.digest_function)?; authorize(&state, &metadata, &request.instance_name, Permission::Read)?; + // Bound the whole response, including repeated requests for one blob. + // Ignore negative sizes here so ordinary per-blob validation reports them. + let declared = request.digests.iter().try_fold(0_i64, |total, digest| { + total.checked_add(digest.size_bytes.max(0)) + }); + if declared.is_none_or(|total| total > MAX_BATCH) { + return Err(Status::invalid_argument( + "batch exceeds the maximum total size", + )); + } let store = state.store.clone(); let responses = blocking(move || { let mut responses = Vec::new(); for digest in request.digests { - let (data, status) = match resolve(&store, &digest) { - Ok(Some(blob)) => match store.cas().read(&blob) { - Ok(data) => (data, rpc_status(tonic::Code::Ok, "")), - Err(_) => ( - Vec::new(), - rpc_status(tonic::Code::NotFound, "blob is gone"), - ), - }, + let (data, status) = match read_batch_blob(&store, &digest) { + Ok(Some(data)) => (data, rpc_status(tonic::Code::Ok, "")), Ok(None) => ( Vec::new(), rpc_status(tonic::Code::NotFound, "blob is not stored"), @@ -383,6 +387,38 @@ async fn batch_read_blobs( Ok(tonic::Response::new(BatchReadBlobsResponse { responses })) } +/// Reads one batch member only when the stored size matches its declaration. +/// The caller has already bounded the sum of all declarations by `MAX_BATCH`. +fn read_batch_blob(store: &Store, digest: &Digest) -> Result>, Status> { + let Some(blob) = resolve(store, digest)? else { + return Ok(None); + }; + let file = match std::fs::File::open(store.cas().object_path(&blob)) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(internal(error)), + }; + let declared = u64::try_from(digest.size_bytes) + .map_err(|_| Status::invalid_argument("negative digest size"))?; + if file.metadata().map_err(internal)?.len() != declared { + return Err(Status::invalid_argument( + "stored blob size does not match digest", + )); + } + // Even a file changed after metadata inspection cannot grow this buffer + // without bound. The store directory itself must remain trusted. + let mut data = Vec::new(); + file.take(declared + 1) + .read_to_end(&mut data) + .map_err(internal)?; + if data.len() as u64 != declared { + return Err(Status::invalid_argument( + "stored blob size does not match digest", + )); + } + Ok(Some(data)) +} + type ReadStream = tokio_stream::wrappers::ReceiverStream>; async fn read( diff --git a/crates/tinymold-server/src/front/reapi/test.rs b/crates/tinymold-server/src/front/reapi/test.rs index 65de83bd..36750d6d 100644 --- a/crates/tinymold-server/src/front/reapi/test.rs +++ b/crates/tinymold-server/src/front/reapi/test.rs @@ -730,3 +730,79 @@ fn a_raw_message_is_never_decoded_and_clears_to_nothing() { raw.clear(); assert_eq!(raw, Raw::default()); } + +#[tokio::test(flavor = "multi_thread")] +async fn batch_reads_refuse_a_declared_total_above_the_advertised_limit() { + let server = start().await; + let mut claimed = digest(b"small"); + claimed.size_bytes = MAX_BATCH; + let result: Result = unary( + &server, + BATCH_READ, + BatchReadBlobsRequest { + instance_name: String::new(), + digests: vec![claimed, digest(b"small")], + digest_function: DIGEST_SHA256, + }, + None, + ) + .await; + assert_eq!(result.unwrap_err().code(), tonic::Code::InvalidArgument); +} + +#[tokio::test(flavor = "multi_thread")] +async fn batch_reads_refuse_a_large_stored_blob_with_an_understated_size() { + let server = start().await; + let bytes = vec![42; usize::try_from(MAX_BATCH).unwrap() + 1]; + server.store.ingest(bytes.as_slice(), None).unwrap(); + let mut claimed = digest(&bytes); + claimed.size_bytes = 1; + let response: BatchReadBlobsResponse = unary( + &server, + BATCH_READ, + BatchReadBlobsRequest { + instance_name: String::new(), + digests: vec![claimed], + digest_function: DIGEST_SHA256, + }, + None, + ) + .await + .unwrap(); + assert_eq!(response.responses[0].data, [] as [u8; 0]); + assert_eq!( + response.responses[0].status.as_ref().unwrap().code, + tonic::Code::InvalidArgument as i32 + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn batch_reads_refuse_an_overflowing_declared_total() { + let server = start().await; + let mut claimed = digest(b"x"); + claimed.size_bytes = i64::MAX; + let result: Result = unary( + &server, + BATCH_READ, + BatchReadBlobsRequest { + instance_name: String::new(), + digests: vec![claimed.clone(), claimed], + digest_function: DIGEST_SHA256, + }, + None, + ) + .await; + assert_eq!(result.unwrap_err().code(), tonic::Code::InvalidArgument); +} + +#[test] +fn a_batch_member_at_the_size_limit_can_be_read() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(dir.path()).unwrap(); + let bytes = vec![23; usize::try_from(MAX_BATCH).unwrap()]; + store.ingest(bytes.as_slice(), None).unwrap(); + assert_eq!( + read_batch_blob(&store, &digest(&bytes)).unwrap().unwrap(), + bytes + ); +} diff --git a/crates/tinymold-wrap/src/catalog/mod.rs b/crates/tinymold-wrap/src/catalog/mod.rs index 21a01e4d..68e88fef 100644 --- a/crates/tinymold-wrap/src/catalog/mod.rs +++ b/crates/tinymold-wrap/src/catalog/mod.rs @@ -132,6 +132,18 @@ pub fn action_references(path: &Path) -> Result> { Ok(action_info(path)?.references) } +/// Parses an action record in memory and returns every object it references, +/// including diagnostics and incremental session files. `path` is used only +/// to identify the record in errors; this function performs no I/O. +/// +/// # Errors +/// +/// Returns [`Error::CorruptRecord`](crate::Error::CorruptRecord) when the +/// record does not parse. +pub fn action_references_from_text(text: &str, path: &Path) -> Result> { + Ok(Action::decode(text, path)?.references()) +} + /// Every object the test run recorded at `path` needs to be replayed: its /// stdout and stderr. /// diff --git a/crates/tinymold-wrap/src/catalog/test.rs b/crates/tinymold-wrap/src/catalog/test.rs index 21419b49..fd09cec8 100644 --- a/crates/tinymold-wrap/src/catalog/test.rs +++ b/crates/tinymold-wrap/src/catalog/test.rs @@ -210,3 +210,18 @@ fn test_run_references_name_both_streams() { write(&path, "garbage"); assert!(test_run_references(&path).is_err()); } + +#[test] +fn in_memory_action_references_parse_without_reading_the_diagnostic_path() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("absent"); + let digest = Digest::of_bytes(b"diagnostics"); + let text = format!("tinymold-action 1\nstdout {digest}\nstderr {digest}\n"); + assert_eq!( + action_references_from_text(&text, &path).unwrap(), + vec![digest, digest] + ); + assert!(matches!(action_references_from_text("bad", &path), + Err(crate::Error::CorruptRecord { path: error_path, line: 1 }) if error_path == path)); + assert!(!path.exists()); +} diff --git a/crates/tinymold-wrap/src/compile/mod.rs b/crates/tinymold-wrap/src/compile/mod.rs index e582e788..21680928 100644 --- a/crates/tinymold-wrap/src/compile/mod.rs +++ b/crates/tinymold-wrap/src/compile/mod.rs @@ -530,6 +530,17 @@ impl Unit<'_> { /// Places every output of `action` and replays rustc's output. fn restore(&self, action: &Action) -> Result<()> { + // Validate names before cleanup. A remote record must not turn a + // shared stem prefix into permission to replace another unit's files. + let prefixes = self.invocation.output_prefixes(); + let dep_info = format!("{}.d", prefixes[1]); + for output in &action.outputs { + if !matches_output_stem(&output.name, &prefixes) + || (output.text && output.name != dep_info) + { + return Err(Error::UnexpectedOutput(output.name.clone())); + } + } // Read the replayed text first, so a missing object fails the hit // before any output is touched. let stdout = self.expand_object(&action.stdout)?; @@ -604,7 +615,15 @@ impl Unit<'_> { let destination = self.out_dir.join(&output.name); if output.text { let text = self.expand_object(&output.digest)?; - fs::write(&destination, text).map_err(io("write", &destination))?; + // Records may come from a remote. Like binary materialization, + // refuse existing files and symlinks rather than following them. + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&destination) + .map_err(io("create", &destination))?; + file.write_all(text.as_bytes()) + .map_err(io("write", &destination))?; } else if !in_place { // A reflink or a copy, never a hardlink: a linker may rewrite // its output in place, and that must not be the store's inode. @@ -967,9 +986,7 @@ impl Unit<'_> { for entry in entries { let entry = entry.map_err(io("read", &self.out_dir))?; if let Some(name) = entry.file_name().to_str() - && prefixes - .iter() - .any(|prefix| name.starts_with(prefix.as_str())) + && matches_output_stem(name, &prefixes) { files.push((name.to_owned(), entry.path())); } @@ -1035,6 +1052,15 @@ impl Unit<'_> { /// How many bytes of an output [`file_contains`] holds in memory at once. const SCAN_CHUNK: usize = 1 << 20; +/// A unit stem ends before an extension (or at the filename's end), so +/// demo-1 does not claim demo-10's files in a shared output directory. +fn matches_output_stem(name: &str, prefixes: &[String; 2]) -> bool { + prefixes.iter().any(|prefix| { + name.strip_prefix(prefix.as_str()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('.')) + }) +} + /// Whether each of `needles` occurs anywhere in the file at `path`, read /// `chunk` bytes at a time, so a large output never has to fit in memory. /// Each read keeps the last `longest - 1` bytes of the one before, so a diff --git a/crates/tinymold-wrap/src/compile/test.rs b/crates/tinymold-wrap/src/compile/test.rs index 9e2893c1..f8a810ec 100644 --- a/crates/tinymold-wrap/src/compile/test.rs +++ b/crates/tinymold-wrap/src/compile/test.rs @@ -1304,3 +1304,68 @@ fn a_needle_split_across_two_reads_of_an_output_is_still_found() { } assert!(file_contains(&dir.path().join("missing"), &needles, 5).is_err()); } + +#[cfg(unix)] +#[test] +fn restoring_text_refuses_a_symlink_outside_the_units_outputs() { + let unit = Crate::new("pub fn f() {}\n"); + let invocation = invocation_of(&unit); + let restoring = unit_for(&unit, &invocation); + let mut action = many_output_action(&restoring.store, 0); + // A remote record may name any plain filename, including one that the + // unit_files cleanup does not recognize as belonging to this compile. + action.outputs[0].name = "unrelated.d".to_owned(); + let victim = unit.root.join("outside.txt"); + fs::write(&victim, b"keep me").unwrap(); + std::os::unix::fs::symlink(&victim, unit.out().join("unrelated.d")).unwrap(); + + let result = restoring.restore(&action); + assert_eq!(fs::read(&victim).unwrap(), b"keep me"); + assert!( + result.is_err(), + "an existing symlink must refuse the restore" + ); +} + +#[test] +fn restoring_text_refuses_an_unrelated_existing_file() { + let unit = Crate::new("pub fn f() {}\n"); + let invocation = invocation_of(&unit); + let restoring = unit_for(&unit, &invocation); + let mut action = many_output_action(&restoring.store, 0); + action.outputs[0].name = "unrelated.d".to_owned(); + let victim = unit.out().join("unrelated.d"); + fs::write(&victim, b"keep me").unwrap(); + + let result = restoring.restore(&action); + assert_eq!(fs::read(&victim).unwrap(), b"keep me"); + assert!(result.is_err(), "an unrelated file must not be overwritten"); +} + +#[test] +fn restoring_a_record_cannot_replace_another_units_text_with_an_overlapping_prefix() { + let unit = Crate::new("pub fn f() {}\n"); + let invocation = invocation_of(&unit); + let restoring = unit_for(&unit, &invocation); + let mut action = many_output_action(&restoring.store, 0); + action.outputs[0].name = "demo-10.d".to_owned(); + let victim = unit.out().join("demo-10.d"); + fs::write(&victim, b"another unit").unwrap(); + let result = restoring.restore(&action); + assert_eq!(fs::read(&victim).unwrap(), b"another unit"); + assert!(matches!(result, Err(Error::UnexpectedOutput(_)))); +} + +#[test] +fn restoring_a_valid_action_preserves_other_units_with_overlapping_prefixes() { + let unit = Crate::new("pub fn f() {}\n"); + let invocation = invocation_of(&unit); + let restoring = unit_for(&unit, &invocation); + let action = many_output_action(&restoring.store, 0); + let victim = unit.out().join("demo-10.d"); + fs::write(&victim, b"another unit").unwrap(); + restoring.restore(&action).unwrap(); + assert_eq!(fs::read(&victim).unwrap(), b"another unit"); + // Replacing this invocation's own dep-info remains a valid warm hit. + restoring.restore(&action).unwrap(); +} diff --git a/crates/tinymold-wrap/src/error/mod.rs b/crates/tinymold-wrap/src/error/mod.rs index 799e5e4b..bfc1f5b0 100644 --- a/crates/tinymold-wrap/src/error/mod.rs +++ b/crates/tinymold-wrap/src/error/mod.rs @@ -43,6 +43,10 @@ pub enum Error { line: usize, }, + /// An action names an output that does not belong to this invocation. + #[error("cached output {0} does not belong to this invocation")] + UnexpectedOutput(String), + /// A program could not be started. #[error("failed to run {program}")] Spawn { diff --git a/crates/tinymold-wrap/src/error/test.rs b/crates/tinymold-wrap/src/error/test.rs index d88ec9a6..9f712e93 100644 --- a/crates/tinymold-wrap/src/error/test.rs +++ b/crates/tinymold-wrap/src/error/test.rs @@ -16,6 +16,12 @@ fn errors_say_what_failed_and_keep_their_cause() { }; assert_eq!(corrupt.to_string(), "cache record r is corrupt at line 2"); + let output = Error::UnexpectedOutput("demo-10.d".into()); + assert_eq!( + output.to_string(), + "cached output demo-10.d does not belong to this invocation" + ); + let spawn = Error::Spawn { program: "rustc".into(), source: std::io::Error::other("x"), diff --git a/crates/tinymold-wrap/src/lib.rs b/crates/tinymold-wrap/src/lib.rs index 87caa641..1c0cde74 100644 --- a/crates/tinymold-wrap/src/lib.rs +++ b/crates/tinymold-wrap/src/lib.rs @@ -61,8 +61,8 @@ use std::time::{Duration, Instant}; use tinymold_key::{Classified, Invocation}; pub use catalog::{ - ActionInfo, RecordFile, RecordKind, action_info, action_references, records, - test_run_references, + ActionInfo, RecordFile, RecordKind, action_info, action_references, + action_references_from_text, records, test_run_references, }; pub use clock::{filesystem_now, written_before}; use compile::Served; diff --git a/docs/specs/cache-security.md b/docs/specs/cache-security.md new file mode 100644 index 00000000..172a2020 --- /dev/null +++ b/docs/specs/cache-security.md @@ -0,0 +1,139 @@ +# Cache security for public repositories + +## Trust boundary + +A cache writer can influence code that a later build executes. A malicious +artifact can have valid SHA-256 and BLAKE3 digests: hashes prove which bytes +arrived, not that those bytes came from the expected compiler or source. +Cached executables, build scripts, proc macros and libraries can introduce +code into a build or its resulting release. A poisoned test-result record +can also suppress a test run. + +Uploading bytes through the cache protocols does not ask tinymold's server +to execute them. Turbo, Nx and Gradle artifacts remain opaque blobs; the +server does not extract their archives. Their consumers remain responsible +for safe extraction and for trusting the producer. REAPI execution is not +implemented. These properties do not make arbitrary uploads harmless: +storage, bandwidth, parsing and concurrent requests still use resources. + +## Required deployment policy + +- Give write access only to CI that builds trusted code. Fork PRs, ordinary + PR jobs and other untrusted workloads get read-only credentials or no + credential. A repository being public does not make its contributors + trusted cache writers. +- For the Rust REAPI adapter, configure `TINYMOLD_REMOTE_TRUSTED_KEYS` on + every reader. Keep `TINYMOLD_REMOTE_SIGNING_KEY` only in the trusted + producer job. Both pre-key and action records must be authenticated. + Signed entries are currently opt-in; an unsigned configuration does not + provide this guarantee. A signature authenticates the producer, not the + correctness of its build. +- Scope credentials by protocol and repository tenant. Use distinct signing + keys for repositories or groups that must not trust each other's builds. + The current signature binds the action key and record, but not the REAPI + instance name: a shared key is a shared signing trust domain. +- Turbo, Nx, Gradle and ordinary Bazel clients do not gain the Rust + adapter's signature verification. Restrict their write credentials and + isolate their trusted and untrusted namespaces server-side. +- Use TLS across untrusted networks. Do not put credentials or sensitive + artifacts in a cache readable by public PRs. The server's CAS digest + index is shared across protocols and tenants; namespaces isolate action + mappings, not confidential blob storage. Use separate server stores for + confidentiality boundaries. +- Run untrusted jobs on disposable runners. The local wrapper store trusts + local records and objects; remote signature verification does not protect + a store an attacker can modify directly. Never mount a trusted persistent + store writable into an untrusted job. An untrusted process on the same + runner can also tamper with restored outputs and other build state. +- A job holding a signing key must not consume unsigned or untrusted local + cache state and then publish it. Start with a clean store when changing + signing policy or rotating away from a contaminated trust domain. Signed + remote verification is performed on fetch, not on every subsequent local + hit. Existing local entries are not retroactively authenticated. + +Workflow conditions are useful defaults, but malicious code given a write +credential can bypass a save step and call the API itself. Enforce read-only +access on the server and withhold signing secrets at the workflow boundary. +Do not execute PR code in a privileged `pull_request_target` job. + +## GitHub Actions + +GitHub scopes its own cache separately from a shared remote server. A normal +`pull_request` cache is scoped to its merge ref; a trusted main build must +not import that archive through another mechanism. GitHub documents its +[cache access restrictions and low-trust trigger policy](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching). +Those restrictions do not apply to a persistent self-hosted runner directory +or an independent REAPI cache. Do not override low-trust cache restrictions +to let untrusted jobs populate trusted caches. + +For public PRs consuming a shared Rust remote, use a fresh runner/store, +the public verification keys, and read-only server access. For example: + +```yaml +- name: Require trusted remote verification keys + shell: bash + env: + TRUSTED_KEYS: ${{ vars.TINYMOLD_REMOTE_TRUSTED_KEYS }} + run: | + if [[ -z "${TRUSTED_KEYS//[[:space:]]/}" ]]; then + echo "::error::TINYMOLD_REMOTE_TRUSTED_KEYS must be configured" + exit 1 + fi +- uses: tinyhumansai/tinymold@v0 + with: + backend: remote + remote-url: grpcs://cache.example.com + remote-instance: my-repository + remote-trusted-keys: ${{ vars.TINYMOLD_REMOTE_TRUSTED_KEYS }} + # Anonymous reads, or a server-enforced read-only credential. +- run: cargo test --all-features +- uses: tinyhumansai/tinymold/save@v0 + if: always() + with: + push: 'false' +``` + +Configure trusted producers in a separate workflow building trusted refs, +with both the signing secret and the same public verification keys. Do not +pass a writer credential or signing key to the public PR workflow. This +example requires a release containing the protections described below; +`v0` alone does not identify a particular audited commit. + +## Upload and restore protections + +| Boundary | Protection | +| --- | --- | +| Server upload | Streamed into private staging; content-derived names; claimed digests checked before committing | +| REAPI batch reads | Declared total limited to 4 MiB with overflow checks; actual stored sizes checked before bounded reads | +| Server network access | Token scopes distinguish read and write; an unauthenticated listener is restricted to loopback | +| Remote artifact reads | SHA-256 verified on receipt, BLAKE3 verified on insertion | +| Remote authorship | Ed25519 verification of records when trusted keys are configured | +| Remote metadata | Action/pre-key records limited to 16 MiB; signatures to 1 KiB, checked before downloading | +| Remote object list | Parsed action record must authorize exactly the distinct listed objects; extra, duplicate or missing objects refuse the entry before artifact downloads | +| Output filenames | Action parser rejects absolute paths, directory separators, drive separators, `.` and `..` | +| Output ownership | Validate invocation stems and the exact dep-info name before cleanup; overlapping stems cannot claim another unit | +| Text restore | Creates a new destination, refusing an existing file or symlink instead of truncating or following it | +| Binary restore | Reflink or exclusive-create copy, rather than a writable hardlink to the CAS | +| Incremental restore | Session destination must be a direct child of the invocation's incremental directory | + +The text-destination protection assumes the surrounding output directory is +trusted. It does not claim to defeat a malicious local process concurrently +replacing parent directories or modifying files after restoration. + +## Remaining availability and assurance limits + +`--max-body` bounds an individual upload (4 GiB by default), not the total +number of simultaneous uploads. `--max-size` triggers periodic eviction; +it is not a hard admission quota. The Rust client can still buffer one +artifact up to its 4 GiB limit even though ordinary concurrent transfers use +a smaller byte budget. A malicious authorized writer or server can cause +disk, memory, CPU or network pressure within and across these limits. +Use service isolation, filesystem quotas and ingress rate/concurrency limits +when exposing the service to untrusted traffic. There is no claim of zero +availability impact from public uploads. + +This is a source review of upload, remote-fetch and Rust restore boundaries, +with regression tests for the identified gaps. It is not a complete security +audit of every parser, third-party consumer, operating-system race or CI +deployment. No production credentials or repository workflows were changed +as part of this hardening. diff --git a/docs/specs/cache-server.md b/docs/specs/cache-server.md index d617b603..a05eff06 100644 --- a/docs/specs/cache-server.md +++ b/docs/specs/cache-server.md @@ -336,3 +336,14 @@ count. `FindMissingBlobs` and peak memory are not measured yet. - **Wire compression.** REAPI's compressed-blobs (zstd) and HTTP `Content-Encoding`: worth negotiating on localhost, where it only costs? - **Windows.** The native socket needs a named-pipe equivalent. + + +### Untrusted batch reads + +REAPI `BatchReadBlobs` refuses a request whose total declared blob size exceeds +the advertised 4 MiB batch limit, including duplicate digests and integer +overflow. Each stored blob's actual size must match its requested digest +before its bytes are read into memory. Reads are also bounded against file +growth between the size check and reading. Clients use ByteStream for larger +objects. See [cache security](cache-security.md) for the public-repository +trust boundary and remaining availability limits. diff --git a/docs/specs/github-actions.md b/docs/specs/github-actions.md index 2e1721ff..3718917a 100644 --- a/docs/specs/github-actions.md +++ b/docs/specs/github-actions.md @@ -70,14 +70,24 @@ steps: if: always() ``` -With a remote server: +With a remote server (see [cache security](cache-security.md) for public PRs): ```yaml + - name: Require trusted remote verification keys + shell: bash + env: + TRUSTED_KEYS: ${{ vars.TINYMOLD_REMOTE_TRUSTED_KEYS }} + run: | + if [[ -z "${TRUSTED_KEYS//[[:space:]]/}" ]]; then + echo "::error::TINYMOLD_REMOTE_TRUSTED_KEYS must be configured" + exit 1 + fi - uses: tinyhumansai/tinymold@v0 with: backend: both remote-url: grpcs://cache.example.com remote-auth: ${{ secrets.TINYMOLD_REMOTE_AUTH }} + remote-trusted-keys: ${{ vars.TINYMOLD_REMOTE_TRUSTED_KEYS }} ``` ## Inputs diff --git a/docs/specs/remote.md b/docs/specs/remote.md index a2cb563d..dee2782d 100644 --- a/docs/specs/remote.md +++ b/docs/specs/remote.md @@ -83,13 +83,11 @@ sharing a key. zeroed, which forces a rehash. Then try each set as the local lookup would. 3. For the first full key the local store lacks, get the remote action: - 1. fetch every listed object the local store does not hold, refusing a - blob whose SHA-256 is wrong; - 2. insert each into the local CAS, which re-derives its BLAKE3 digest, - and refuse the entry when that digest is not the name it was listed - under; - 3. fetch and decode `.tinymold/action`, and check that every digest it - names is now in the store; if any is missing, it is a miss. + 1. verify the record's signature when trusted keys are configured; + 2. fetch and parse the bounded action record, then check that its distinct + references match the response's object names exactly; + 3. fetch the authorized objects missing locally, checking SHA-256 on + receipt and BLAKE3 on insertion into the local CAS. 4. Write the local action and restore it, as a local hit would. The log outcome is `remote`. @@ -97,8 +95,8 @@ Calls go through ByteStream `Read` for blobs, so blob size is not limited by the gRPC message size. The connection uses HTTP/2 adaptive flow-control windows, so reads from a distant cache are not held to a fixed window per round trip. Once an entry's signature checks out, its -objects and its record are read together, within 32 concurrent calls and -a 32 MiB byte budget, and a pre-key +record is read first; its authorized objects are then read within 32 +concurrent calls and a 32 MiB byte budget. A pre-key lookup reads its signature and record together: each read is a round trip, and a runner far from its cache would otherwise pay one per object on every hit. Each call has the configured timeout, and blob @@ -168,7 +166,7 @@ reads answers `GetCapabilities` whatever the credential. - Only trusted CI holds a write credential. Pull requests from forks get no secrets, and read anonymously when the server allows unauthenticated reads, or run without a remote. -- **A remote can only make a build miss.** Everything it returns is +- **Hashes establish integrity, not authorship.** Everything the remote returns is re-hashed and checked against digests in records the client parsed itself. A server that returns a wrong record for a key is trusted as much as the CI that wrote it, which is why writes are restricted, and why readers @@ -182,7 +180,8 @@ right. One bad bind address or a missing credential file lets anyone who can reach the server plant an entry that decides what a later build links. Signed entries make the client independent of that: a reader that names its trusted keys uses only entries those keys signed, so a server open to -the world can at worst make a build miss. +the world cannot forge a trusted record. It can still withhold entries or +consume resources up to the client limits. - **Keys.** `tinymold remote keygen` prints a fresh ed25519 key pair as the two variables above. The secret goes only to trusted writers, such as CI @@ -222,6 +221,23 @@ anonymous write while this client trusts no keys is refused with poison the cache. Either require a credential for writes or configure trusted keys. +## Untrusted metadata + +The client refuses negative sizes and record blobs larger than 16 MiB before +opening their download stream. Signature blobs are limited to 1 KiB before +verification. Artifacts retain the separate 4 GiB blob limit. + +An action record is downloaded and parsed before its objects. The response's +object names must match exactly the distinct BLAKE3 references in that record; +missing, extra, or duplicate object names refuse the entry, even when the +objects are already cached locally. A valid signature therefore cannot be +reused to authorize unrelated artifact downloads. Objects still download in +parallel, with each SHA-256 checked on receipt and BLAKE3 checked on insertion. +This adds a record-read dependency before artifact downloads. + +See [cache security](cache-security.md) for public-repository trust boundaries, +the local-store limitation, and deployment guidance. + ## Acceptance criteria - With a populated remote and an empty local store, a clean build of this