Skip to content
Merged
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
50 changes: 43 additions & 7 deletions src/persist-client/src/internal/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1729,9 +1729,16 @@ pub struct LazyPartStats {

impl Debug for LazyPartStats {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("LazyPartStats")
.field(&self.decode())
.finish()
let mut f = f.debug_tuple("LazyPartStats");
// These bytes come from blob and are never validated on the way in, so
// `Debug` runs on malformed encodings: `Spine::validate` formats the
// whole spine into the message it rejects an untrusted rollup with, and
// `Trace::unflatten` returns that as a decode error. Rendering the
// failure keeps that rejection path a hard error instead of a panic.
match self.try_decode() {
Ok(stats) => f.field(&stats).finish(),
Err(err) => f.field(&format_args!("<undecodable: {err}>")).finish(),
}
}
}

Expand All @@ -1748,11 +1755,26 @@ impl LazyPartStats {
///
/// This does not cache the returned value, it decodes each time it's
/// called.
///
/// Panics if the encoded bytes are malformed. Only call this where the value
/// is known to have come from `Self::encode` rather than straight off blob.
pub fn decode(&self) -> PartStats {
let key = self.key.decode().expect("valid proto");
PartStats {
key: key.into_rust().expect("valid stats"),
}
self.try_decode().expect("valid stats")
}

/// Like [Self::decode], but surfaces a malformed encoding as an error.
///
/// The bytes are stored undecoded (see the [RustType] impl), so a corrupted
/// or crafted blob reaches here intact. Anything running on state that has
/// not been validated yet must use this.
pub fn try_decode(&self) -> Result<PartStats, TryFromProtoError> {
let key = self
.key
.decode()
.map_err(|err| TryFromProtoError::InvalidPersistState(err.to_string()))?;
Ok(PartStats {
key: key.into_rust()?,
})
}
}

Expand Down Expand Up @@ -2630,4 +2652,18 @@ mod tests {
testcase("28.0.0", "26.1000.1", Err(()));
testcase("28.0.0", "27.0.0", Ok(()));
}

/// `LazyPartStats`'s bytes are stored undecoded, so `Debug` runs on
/// encodings that came straight off blob and may be malformed. It must render
/// the failure: `Spine::validate` formats the whole spine into the message
/// with which `Trace::unflatten` rejects an untrusted rollup, so a panic here
/// turns that rejection into an unrecoverable shard.
#[mz_ore::test]
fn lazy_part_stats_debug_does_not_panic_on_garbage() {
// Tag 0 is never a legal protobuf tag.
let stats = LazyPartStats::from_proto(Bytes::from_static(&[0x00, 0xff]))
.expect("stats bytes are stored undecoded");
assert_err!(stats.try_decode());
assert!(format!("{stats:?}").contains("undecodable"));
}
}
50 changes: 49 additions & 1 deletion src/persist-client/src/internal/state_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1267,7 +1267,24 @@ impl ProtoStateFieldDiffs {
));
}

let expected_data_bytes = usize::cast_from(self.data_lens.iter().copied().sum::<u64>());
// NOTE: A crafted diff can declare lengths whose sum exceeds `u64::MAX`.
// Overflow checks are off in release/optimized builds, so an unchecked
// sum would wrap to a small value, match `data_bytes.len()`, and let the
// diff past validation. `ProtoStateFieldDiffsIter` would then slice
// `data_bytes` far out of range and panic.
let Some(expected_data_bytes) = self
.data_lens
.iter()
.copied()
.try_fold(0u64, |acc, len| acc.checked_add(len))
.and_then(|sum| usize::try_from(sum).ok())
else {
return Err(format!(
"data_lens sum overflows, got {} lens over {} data bytes",
self.data_lens.len(),
self.data_bytes.len()
));
};
if expected_data_bytes != self.data_bytes.len() {
return Err(format!(
"expected {} data bytes got {}",
Expand Down Expand Up @@ -1381,6 +1398,37 @@ mod tests {
);
}

#[mz_ore::test]
#[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function on OS `linux`
fn proto_state_diff_data_lens_overflow_is_error() {
// `data_lens` entries that sum past `u64::MAX` are the one shape that can
// get *past* `validate()`: with overflow checks off the sum wraps to 0,
// matching an empty `data_bytes`, and the iterator then slices
// `0..u64::MAX` out of an empty slice.
use crate::internal::state::ProtoStateDiff;
use mz_proto::ProtoType;

let proto = ProtoStateDiff {
applier_version: "0.1.2".into(),
seqno_from: 0,
seqno_to: 1,
walltime_ms: 0,
latest_rollup_key: "rollup".into(),
field_diffs: Some(ProtoStateFieldDiffs {
fields: vec![ProtoStateField::Hostname.into()],
// Insert expects two data slices: the key and the new value.
diff_types: vec![ProtoStateFieldDiffType::Insert.into()],
data_lens: vec![u64::MAX, 1],
data_bytes: Bytes::new(),
}),
};
let result: Result<StateDiff<u64>, _> = proto.into_rust();
assert!(
result.is_err(),
"data_lens that overflow must be a decode error"
);
}

/// Model a situation where a "leader" is constantly making changes to its state, and a "follower"
/// is applying those changes as diffs.
#[mz_ore::test]
Expand Down
65 changes: 53 additions & 12 deletions src/persist-client/src/internal/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1581,12 +1581,17 @@ impl<T: Timestamp + Lattice> FuelingMerge<T> {
///
/// If `fuel` is non-zero after the call, the merging is complete and one
/// should call `done` to extract the merged results.
// TODO(benesch): rewrite to avoid usage of `as`.
#[allow(clippy::as_conversions)]
fn work(&mut self, _: &[SpineBatch<T>], fuel: &mut isize) {
let used = std::cmp::min(*fuel as usize, self.remaining_work);
// A negative `fuel` means a caller already overspent, so there is
// nothing to spend here. Reading it as a `usize` instead would wrap to a
// huge budget, spend `remaining_work` against it, and then underflow the
// subtraction below.
let available = usize::try_from(*fuel).unwrap_or(0);
let used = std::cmp::min(available, self.remaining_work);
self.remaining_work = self.remaining_work.saturating_sub(used);
*fuel -= used as isize;
// `used <= available <= isize::MAX`, so neither conversion nor the
// subtraction can overflow.
*fuel -= isize::try_from(used).expect("used is bounded by fuel");
}

/// Extracts merged results.
Expand Down Expand Up @@ -1922,14 +1927,21 @@ impl<T: Timestamp + Lattice> Spine<T> {
// batches. We could try and make this be less, or be scaled to merges
// based on their deficit at time of instantiation. For now, we remain
// conservative.
let mut fuel = 8 << batch_index;
// Scale up by the effort parameter, which is calibrated to one as the
// minimum amount of effort.
fuel *= self.effort;
// Convert to an `isize` so we can observe any fuel shortfall.
// TODO(benesch): avoid dangerous usage of `as`.
#[allow(clippy::as_conversions)]
let fuel = fuel as isize;
//
// `batch_index` is derived from a batch's `len`, which for a trace
// reconstructed from an untrusted blob can be large enough that
// `8 << batch_index` overflows. Saturate at `isize::MAX` rather than
// wrapping: fuel is a budget, so more of it only completes merges sooner,
// whereas a wrapped value can land negative and starve them. The result
// is an `isize` so a fuel shortfall stays observable.
let fuel = u32::try_from(batch_index)
.ok()
.and_then(|shift| 8usize.checked_shl(shift))
// Scale up by the effort parameter, which is calibrated to one as the
// minimum amount of effort.
.and_then(|fuel| fuel.checked_mul(self.effort))
.and_then(|fuel| isize::try_from(fuel).ok())
.unwrap_or(isize::MAX);

// Step 1. Apply fuel to each in-progress merge.
//
Expand Down Expand Up @@ -2749,4 +2761,33 @@ pub(crate) mod tests {
assert_eq!(sb_too_big.parts.len(), 3);
assert_eq!(sb_too_big.len(), 30);
}

/// Inserting a batch whose `len` is large enough to saturate the fuel
/// computation must not disturb an in-progress merge's accounting.
///
/// `introduce_batch` derives its fuel from `8 << batch_index`, where
/// `batch_index` is `len.next_power_of_two().trailing_zeros()`. A `len` near
/// `2^60` pushes that past what an `isize` holds, and `Trace::unflatten`
/// accepts such a `len` from an untrusted blob: its `MAX_TOTAL_LEN` guard
/// only caps the total at `usize::MAX >> 3`.
#[mz_ore::test]
fn spine_fuel_isize_overflow() {
let mut trace = Trace::<u64>::default();
let mut push = |lower, upper, key: &str, len| {
trace.push_batch_no_merge_reqs(crate::internal::state::tests::hollow::<u64>(
lower,
upper,
&[key],
len,
));
};
// Two same-size batches fill a level and begin a merge whose
// `remaining_work` (the sum of their lens) far exceeds the `8 << 0` fuel
// that a subsequent len-1 batch delivers, so the merge is still in
// progress when the saturating batch arrives.
push(0, 1, "a", 100);
push(1, 2, "b", 100);
push(2, 3, "c", 1);
push(3, 4, "d", 1 << 60);
}
}
Loading