use crate::rollback::epoch_days;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Policy {
pub months: u32,
}
impl Policy {
pub fn for_channel(channel: &str) -> Option<Policy> {
match channel {
"rolling" => Some(Policy { months: 1 }),
"qualified" => Some(Policy { months: 24 }),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SupportError {
UnknownChannel(String),
BadDate {
field: &'static str,
value: String,
},
IncludeStatesNoWindow {
layer: String,
realm: String,
},
OverrideWithoutReason,
IncludeExpired {
layer: String,
realm: String,
until: String,
issued_at: String,
},
}
impl fmt::Display for SupportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SupportError::UnknownChannel(c) => write!(
f,
"no support policy is stated for channel `{c}` (known: rolling, \
qualified). Refusing to invent one: a horizon nobody decided \
is a promise nobody made."
),
SupportError::BadDate { field, value } => write!(
f,
"{field} `{value}` is not a date (expected YYYY-MM-DD). This \
field has never been validated, so an unparseable value would \
sign cleanly and then be unusable by everything that reads it."
),
SupportError::IncludeStatesNoWindow { layer, realm } => write!(
f,
"included layer {layer} (realm '{realm}') states no support window, so \
nothing bounds how long this composition may promise to support it. \
Refusing rather than skipping it: the include nobody vouched for is \
the one that would have set the cap."
),
SupportError::OverrideWithoutReason => write!(
f,
"promising support past an included layer's window needs a reason on \
the record; an empty one is not a decision"
),
SupportError::IncludeExpired {
layer,
realm,
until,
issued_at,
} => write!(
f,
"included layer {layer} (realm '{realm}') was supported until {until}, before \
this composition's issue date {issued_at}. Signing it would promise support \
over bytes their own realm no longer vouches for; move the include to a \
supported layer (its next line, if this one has ended) and deposit again. No \
--past-includes reason overrides this."
),
}
}
}
impl std::error::Error for SupportError {}
pub fn horizon(issued_at: &str, channel: &str) -> Result<String, SupportError> {
let policy =
Policy::for_channel(channel).ok_or_else(|| SupportError::UnknownChannel(channel.into()))?;
let date = issued_at.split_once('T').map_or(issued_at, |(d, _)| d);
if epoch_days(date).is_none() {
return Err(SupportError::BadDate {
field: "issued-at",
value: issued_at.to_string(),
});
}
let y: i64 = date[0..4].parse().expect("checked by epoch_days");
let m: i64 = date[5..7].parse().expect("checked by epoch_days");
let d: i64 = date[8..10].parse().expect("checked by epoch_days");
let total = (m - 1) + i64::from(policy.months);
let (ny, nm) = (y + total / 12, total % 12 + 1);
let nd = d.min(days_in_month(ny, nm));
Ok(format!("{ny:04}-{nm:02}-{nd:02}"))
}
fn days_in_month(y: i64, m: i64) -> i64 {
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
match m {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
_ => {
if leap {
29
} else {
28
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeWindow {
pub layer: String,
pub realm: String,
pub support_until: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Bound {
Own,
Include { layer: String, realm: String },
PastIncludes { earliest: String, reason: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Capped {
pub until: String,
pub bound_by: Bound,
}
pub fn cap_by_includes(
own: &str,
includes: &[IncludeWindow],
past_includes: Option<&str>,
issued_at: &str,
) -> Result<Capped, SupportError> {
let own_days = epoch_days(own).ok_or_else(|| SupportError::BadDate {
field: "support-until",
value: own.to_string(),
})?;
let issued_date = issued_at.get(..10).unwrap_or(issued_at);
let issued_days = epoch_days(issued_date).ok_or_else(|| SupportError::BadDate {
field: "issued-at",
value: issued_at.to_string(),
})?;
let mut earliest: Option<(i64, &IncludeWindow, &str)> = None;
for inc in includes {
let until =
inc.support_until
.as_deref()
.ok_or_else(|| SupportError::IncludeStatesNoWindow {
layer: inc.layer.clone(),
realm: inc.realm.clone(),
})?;
let days = epoch_days(until).ok_or_else(|| SupportError::BadDate {
field: "include support-until",
value: until.to_string(),
})?;
if earliest.is_none_or(|(e, _, _)| days < e) {
earliest = Some((days, inc, until));
}
}
if let Some((days, inc, until)) = earliest
&& days < issued_days
{
return Err(SupportError::IncludeExpired {
layer: inc.layer.clone(),
realm: inc.realm.clone(),
until: until.to_string(),
issued_at: issued_date.to_string(),
});
}
let own_stands = Capped {
until: own.to_string(),
bound_by: Bound::Own,
};
let Some((_, inc, until)) = earliest.filter(|(d, _, _)| *d < own_days) else {
return Ok(own_stands);
};
match past_includes {
Some(reason) if reason.trim().is_empty() => Err(SupportError::OverrideWithoutReason),
Some(reason) => Ok(Capped {
until: own.to_string(),
bound_by: Bound::PastIncludes {
earliest: until.to_string(),
reason: reason.trim().to_string(),
},
}),
None => Ok(Capped {
until: until.to_string(),
bound_by: Bound::Include {
layer: inc.layer.clone(),
realm: inc.realm.clone(),
},
}),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeWindowError {
pub include: String,
pub realm: String,
pub reason: String,
pub retry_elsewhere: bool,
}
impl fmt::Display for IncludeWindowError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"cannot read the support window of included layer {} (realm '{}'): {}",
self.include, self.realm, self.reason
)
}
}
impl std::error::Error for IncludeWindowError {}
pub fn include_window(
source: &dyn crate::source::LayerSource,
verifier: &dyn crate::install::ManifestVerifier,
trust: &crate::keyroles::RealmTrust,
digest: &str,
realm: &str,
) -> Result<IncludeWindow, IncludeWindowError> {
window_and_includes(source, source, true, verifier, trust, digest, realm).map(|(w, _)| w)
}
fn window_and_includes(
source: &dyn crate::source::LayerSource,
primary: &dyn crate::source::LayerSource,
source_is_primary: bool,
verifier: &dyn crate::install::ManifestVerifier,
trust: &crate::keyroles::RealmTrust,
digest: &str,
realm: &str,
) -> Result<(IncludeWindow, Vec<crate::compose::Include>), IncludeWindowError> {
let fail = |reason: String| IncludeWindowError {
include: digest.to_string(),
realm: realm.to_string(),
reason,
retry_elsewhere: true,
};
let layer_ref = crate::source::LayerRef::Digest(digest.to_string());
let fetched = source
.fetch_manifest(&layer_ref)
.map_err(|e| fail(format!("fetching its manifest: {e}")))?;
let payload = verifier
.verify(&fetched)
.map_err(|e| fail(format!("its manifest does not verify: {}", e.0)))?;
if crate::store::manifest_digest(&payload) != digest {
return Err(fail(
"the manifest served for this digest hashes to something else".to_string(),
));
}
let manifest = crate::manifest::LayerManifest::parse(&payload)
.map_err(|e| fail(format!("its manifest does not parse: {e}")))?;
let includes = crate::compose::view(&payload)
.map_err(|e| fail(format!("its includes do not read: {e}")))?
.includes;
let line = manifest.layer.line();
let from_primary = |what: &str, e: crate::source::SourceError| {
if source_is_primary {
fail(format!(
"layer {}: cannot read {what} for line {line}: {e}",
manifest.layer
))
} else {
IncludeWindowError {
retry_elsewhere: false,
..fail(format!(
"layer {}: the support window could not be established: status documents \
(the baseline and any correction) are only taken from the realm's primary, \
and it could not supply {what} for line {line} ({e})",
manifest.layer
))
}
}
};
let baseline = primary
.fetch_line_status(&layer_ref)
.map_err(|e| from_primary("the layer's baseline status", e))?;
let correction = primary
.fetch_published_line_status(&line.to_string())
.map_err(|e| from_primary("a published correction", e))?;
let status =
crate::linestatus::current_line_status_from_documents(baseline, correction, line, trust)
.map_err(|e| IncludeWindowError {
retry_elsewhere: false,
..fail(format!("layer {}: its line-status: {e}", manifest.layer))
})?;
Ok((
IncludeWindow {
layer: manifest.layer.to_string(),
realm: realm.to_string(),
support_until: status
.and_then(|(_, doc)| doc.report_for(&manifest.layer).support_until),
},
includes,
))
}
pub enum RealmSource<'a> {
Single(&'a dyn crate::source::LayerSource),
Failover(&'a crate::mirror::Mirrors),
}
pub struct RealmView<'a> {
pub source: RealmSource<'a>,
pub verifier: &'a dyn crate::install::ManifestVerifier,
pub trust: &'a crate::keyroles::RealmTrust,
}
pub trait RealmAccess {
fn open(&self, realm: &str) -> Result<RealmView<'_>, String>;
}
const MAX_INCLUDE_DEPTH: usize = 16;
const MAX_INCLUDE_NODES: usize = 256;
pub fn include_window_deep(
access: &dyn RealmAccess,
digest: &str,
realm: &str,
) -> Result<IncludeWindow, IncludeWindowError> {
let mut seen = std::collections::BTreeMap::new();
let mut opened = 0;
deep_window(access, digest, realm, 0, &mut seen, &mut opened)
}
fn deep_window(
access: &dyn RealmAccess,
digest: &str,
realm: &str,
depth: usize,
seen: &mut std::collections::BTreeMap<(String, String), IncludeWindow>,
opened: &mut usize,
) -> Result<IncludeWindow, IncludeWindowError> {
let key = (realm.to_string(), digest.to_string());
if let Some(w) = seen.get(&key) {
return Ok(w.clone());
}
let fail = |reason: String| IncludeWindowError {
include: digest.to_string(),
realm: realm.to_string(),
reason,
retry_elsewhere: false,
};
if depth > MAX_INCLUDE_DEPTH {
return Err(fail(format!(
"the composition is nested deeper than {MAX_INCLUDE_DEPTH} layers"
)));
}
*opened += 1;
if *opened > MAX_INCLUDE_NODES {
return Err(fail(format!(
"the composition reaches more than {MAX_INCLUDE_NODES} distinct layers"
)));
}
let view = access.open(realm).map_err(fail)?;
let (own, nested) = match view.source {
RealmSource::Single(source) => window_and_includes(
source,
source,
true,
view.verifier,
view.trust,
digest,
realm,
)?,
RealmSource::Failover(sources) => {
let primary = sources
.primary()
.ok_or_else(|| fail("this realm declares no sources at all".to_string()))?;
sources
.attempt(
|source, is_primary| {
window_and_includes(
source,
primary,
is_primary,
view.verifier,
view.trust,
digest,
realm,
)
},
|e| e.retry_elsewhere,
)
.map_err(|failures| all_sources_failed(digest, realm, failures))?
}
};
let mut best = own;
for inc in nested {
let r = inc.realm.as_deref().unwrap_or(realm);
let sub = deep_window(access, &inc.digest, r, depth + 1, seen, opened)?;
best = earlier(best, sub);
}
seen.insert(key, best.clone());
Ok(best)
}
fn all_sources_failed(
digest: &str,
realm: &str,
mut failures: Vec<(String, IncludeWindowError)>,
) -> IncludeWindowError {
let terminal = failures.last().is_some_and(|(_, e)| !e.retry_elsewhere);
if terminal || failures.len() == 1 {
return failures.pop().expect("a failed attempt has a failure").1;
}
let listing = failures
.iter()
.map(|(label, e)| format!("\n {label}: {}", e.reason))
.collect::<String>();
IncludeWindowError {
include: digest.to_string(),
realm: realm.to_string(),
reason: format!(
"no source of the realm supplied a verifiable window. Tried {} source(s) in \
order:{listing}",
failures.len()
),
retry_elsewhere: false,
}
}
fn earlier(a: IncludeWindow, b: IncludeWindow) -> IncludeWindow {
let day = |w: &IncludeWindow| w.support_until.as_deref().and_then(epoch_days);
match (day(&a), day(&b)) {
(None, _) => a,
(_, None) => b,
(Some(x), Some(y)) if y < x => b,
_ => a,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Standing {
Supported { days_left: i64 },
Expired { days_ago: i64 },
}
impl Standing {
pub fn is_expired(self) -> bool {
matches!(self, Standing::Expired { .. })
}
}
pub fn standing(support_until: &str, today: &str) -> Result<Standing, SupportError> {
let until = epoch_days(support_until).ok_or_else(|| SupportError::BadDate {
field: "support-until",
value: support_until.to_string(),
})?;
let now = epoch_days(today).ok_or_else(|| SupportError::BadDate {
field: "today",
value: today.to_string(),
})?;
if now <= until {
Ok(Standing::Supported {
days_left: until - now,
})
} else {
Ok(Standing::Expired {
days_ago: now - until,
})
}
}
pub fn advisory(layer: &str, support_until: &str, standing: Standing) -> String {
match standing {
Standing::Expired { days_ago } => format!(
"layer {layer} passed its stated support window on {support_until}, \
{days_ago} day(s) ago. It still installs and still verifies — \
nothing about the bytes has changed. What has changed is that no \
one has undertaken to publish advisories or fixes for it, so a \
problem found tomorrow will not be announced against this layer. \
Move to a supported layer when you can."
),
Standing::Supported { days_left } if days_left <= 30 => format!(
"layer {layer} is supported until {support_until}, {days_left} \
day(s) from now."
),
Standing::Supported { days_left } => {
format!("layer {layer} is supported until {support_until} ({days_left} days)")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_horizon_is_derived_from_the_channel_not_typed_by_hand() {
assert_eq!(
horizon("2026-09-03T00:00:00Z", "rolling").unwrap(),
"2026-10-03"
);
assert_eq!(
horizon("2026-09-03T00:00:00Z", "qualified").unwrap(),
"2028-09-03"
);
assert_eq!(horizon("2026-09-03", "rolling").unwrap(), "2026-10-03");
}
#[test]
fn a_horizon_that_would_fall_on_a_day_that_does_not_exist_is_clamped() {
assert_eq!(horizon("2026-08-31", "rolling").unwrap(), "2026-09-30");
assert_eq!(horizon("2027-01-31", "rolling").unwrap(), "2027-02-28");
assert_eq!(horizon("2028-01-31", "rolling").unwrap(), "2028-02-29");
for d in ["2026-08-31", "2026-10-31", "2027-08-31", "2026-12-31"] {
let h = horizon(d, "rolling").unwrap();
assert!(epoch_days(&h).is_some(), "{d} -> {h} does not parse");
}
}
#[test]
fn a_thirty_one_day_target_month_keeps_all_thirty_one_days() {
assert_eq!(horizon("2026-12-31", "rolling").unwrap(), "2027-01-31");
assert_eq!(horizon("2026-03-31", "rolling").unwrap(), "2026-04-30");
assert_eq!(horizon("2026-07-31", "rolling").unwrap(), "2026-08-31");
assert_eq!(horizon("2026-01-31", "qualified").unwrap(), "2028-01-31");
}
#[test]
fn february_follows_the_whole_gregorian_leap_rule() {
assert_eq!(horizon("2024-01-31", "rolling").unwrap(), "2024-02-29");
assert_eq!(horizon("2100-01-31", "rolling").unwrap(), "2100-02-28");
assert_eq!(horizon("2000-01-31", "rolling").unwrap(), "2000-02-29");
assert_eq!(horizon("2026-01-31", "rolling").unwrap(), "2026-02-28");
}
#[test]
fn a_supported_layer_does_not_report_itself_expired() {
assert!(!standing("2027-03-03", "2026-09-03").unwrap().is_expired());
assert!(!standing("2026-09-03", "2026-09-03").unwrap().is_expired());
assert!(standing("2026-09-02", "2026-09-03").unwrap().is_expired());
}
#[test]
fn the_year_rolls_over_correctly() {
assert_eq!(horizon("2026-12-15", "rolling").unwrap(), "2027-01-15");
assert_eq!(horizon("2026-12-31", "rolling").unwrap(), "2027-01-31");
assert_eq!(horizon("2026-01-15", "qualified").unwrap(), "2028-01-15");
}
#[test]
fn an_unknown_channel_gets_no_horizon_rather_than_a_guessed_one() {
let e = horizon("2026-09-03", "experimental").expect_err("must refuse");
assert!(matches!(e, SupportError::UnknownChannel(_)), "{e:?}");
assert!(e.to_string().contains("a promise nobody made"), "{e}");
assert_eq!(Policy::for_channel("nope"), None);
}
#[test]
fn an_unparseable_horizon_is_refused_rather_than_compared() {
for bad in [
"",
"next year",
"2028-13-45",
"2028-02-30",
"28-01-01",
"2028/01/01",
] {
let e = standing(bad, "2026-09-03").expect_err(bad);
assert!(matches!(e, SupportError::BadDate { .. }), "{bad}: {e:?}");
}
assert!(horizon("not-a-date", "rolling").is_err());
}
#[test]
fn the_stated_day_is_still_supported_and_the_next_one_is_not() {
assert_eq!(
standing("2027-03-03", "2027-03-03").unwrap(),
Standing::Supported { days_left: 0 }
);
assert_eq!(
standing("2027-03-03", "2027-03-04").unwrap(),
Standing::Expired { days_ago: 1 }
);
assert_eq!(
standing("2027-03-03", "2027-03-02").unwrap(),
Standing::Supported { days_left: 1 }
);
}
#[test]
fn an_expired_layer_is_explained_rather_than_refused() {
let s = standing("2026-01-01", "2026-09-03").unwrap();
assert!(s.is_expired());
let msg = advisory("2026.01.0", "2026-01-01", s);
assert!(msg.contains("still installs and still verifies"), "{msg}");
assert!(msg.contains("245 day(s) ago"), "{msg}");
assert!(msg.contains("advisories"), "{msg}");
}
#[test]
fn a_window_closing_soon_reads_differently_from_one_far_off() {
let soon = advisory(
"x",
"2026-09-20",
standing("2026-09-20", "2026-09-03").unwrap(),
);
assert!(soon.contains("17 day(s) from now"), "{soon}");
let far = advisory(
"x",
"2027-09-20",
standing("2027-09-20", "2026-09-03").unwrap(),
);
assert!(far.contains("(382 days)"), "{far}");
}
fn inc(layer: &str, until: Option<&str>) -> IncludeWindow {
IncludeWindow {
layer: layer.to_string(),
realm: "wasm".to_string(),
support_until: until.map(str::to_string),
}
}
#[test]
fn a_composition_is_capped_at_its_earliest_include() {
let got = cap_by_includes(
"2026-11-02",
&[
inc("2026.10.0", Some("2026-10-24")),
inc("2026.10.3", Some("2026-10-30")),
],
None,
"2026-01-01",
)
.unwrap();
assert_eq!(got.until, "2026-10-24");
assert_eq!(
got.bound_by,
Bound::Include {
layer: "2026.10.0".into(),
realm: "wasm".into()
}
);
}
#[test]
fn the_earliest_include_binds_wherever_it_is_listed() {
let got = cap_by_includes(
"2026-11-02",
&[
inc("late", Some("2026-10-30")),
inc("early", Some("2026-10-24")),
inc("tied", Some("2026-10-24")),
],
None,
"2026-01-01",
)
.unwrap();
assert_eq!(got.until, "2026-10-24");
assert_eq!(
got.bound_by,
Bound::Include {
layer: "early".into(),
realm: "wasm".into()
}
);
}
#[test]
fn the_own_window_stands_when_it_is_already_the_shortest() {
let got = cap_by_includes(
"2026-11-02",
&[inc("x", Some("2027-01-01"))],
None,
"2026-01-01",
)
.unwrap();
assert_eq!(
(got.until.as_str(), &got.bound_by),
("2026-11-02", &Bound::Own)
);
let alone = cap_by_includes("2026-11-02", &[], None, "2026-01-01").unwrap();
assert_eq!(
(alone.until.as_str(), &alone.bound_by),
("2026-11-02", &Bound::Own)
);
}
#[test]
fn an_include_ending_the_same_day_is_not_a_cap() {
let got = cap_by_includes(
"2026-11-02",
&[inc("x", Some("2026-11-02"))],
None,
"2026-01-01",
)
.unwrap();
assert_eq!(got.bound_by, Bound::Own);
}
#[test]
fn an_include_that_states_no_window_refuses_rather_than_being_skipped() {
let err = cap_by_includes(
"2026-11-02",
&[inc("a", Some("2026-12-01")), inc("b", None)],
None,
"2026-01-01",
)
.unwrap_err();
assert_eq!(
err,
SupportError::IncludeStatesNoWindow {
layer: "b".into(),
realm: "wasm".into()
}
);
assert!(err.to_string().contains("b"), "{err}");
}
#[test]
fn an_unparseable_include_window_refuses() {
let err = cap_by_includes("2026-11-02", &[inc("a", Some("soon"))], None, "2026-01-01")
.unwrap_err();
assert!(matches!(err, SupportError::BadDate { .. }), "{err:?}");
}
#[test]
fn exceeding_the_cap_takes_a_stated_reason() {
let got = cap_by_includes(
"2026-11-02",
&[inc("2026.10.0", Some("2026-10-24"))],
Some("wasm-layers 2026.11.0 is staged and carries the same tools"),
"2026-01-01",
)
.unwrap();
assert_eq!(got.until, "2026-11-02");
assert_eq!(
got.bound_by,
Bound::PastIncludes {
earliest: "2026-10-24".into(),
reason: "wasm-layers 2026.11.0 is staged and carries the same tools".into()
}
);
}
#[test]
fn an_override_without_a_reason_is_refused() {
let err = cap_by_includes(
"2026-11-02",
&[inc("a", Some("2026-10-24"))],
Some(" "),
"2026-01-01",
)
.unwrap_err();
assert_eq!(err, SupportError::OverrideWithoutReason);
assert!(!err.to_string().is_empty());
}
#[test]
fn an_unneeded_override_is_not_recorded() {
let got = cap_by_includes(
"2026-11-02",
&[inc("a", Some("2027-01-01"))],
Some("because"),
"2026-01-01",
)
.unwrap();
assert_eq!(got.bound_by, Bound::Own);
}
#[test]
fn an_include_already_expired_at_issue_refuses_the_horizon() {
let inc = IncludeWindow {
layer: "2026.09.0".into(),
realm: "wasm".into(),
support_until: Some("2026-10-24".into()),
};
for past in [None, Some("we know")] {
let err = cap_by_includes("2026-11-30", std::slice::from_ref(&inc), past, "2026-10-27")
.unwrap_err();
assert_eq!(
err,
SupportError::IncludeExpired {
layer: "2026.09.0".into(),
realm: "wasm".into(),
until: "2026-10-24".into(),
issued_at: "2026-10-27".into(),
}
);
assert!(err.to_string().contains("2026-10-24"), "{err}");
}
assert!(
cap_by_includes("2026-11-30", std::slice::from_ref(&inc), None, "2026-10-24").is_ok()
);
}
mod from_source {
use super::super::*;
use crate::install::{ManifestVerifier, VerifyError};
use crate::linestatus::LineStatus;
use crate::manifest::fixtures::manifest_with_tools;
use crate::source::MemorySource;
use crate::store::manifest_digest;
use crate::verify::generate_root_keypair;
struct AcceptAll;
impl ManifestVerifier for AcceptAll {
fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
Ok(fetched.to_vec())
}
}
struct RejectAll;
impl ManifestVerifier for RejectAll {
fn verify(&self, _: &[u8]) -> Result<Vec<u8>, VerifyError> {
Err(VerifyError("untrusted signature (test)".into()))
}
}
fn wasm_layer() -> Vec<u8> {
manifest_with_tools("2026.10.0", "rolling", 0, "2026-09-24T00:00:00Z", &[])
}
fn status(counter: u64, until: Option<&str>) -> LineStatus {
LineStatus {
min_counter: None,
line: "2026.10".into(),
counter,
issued_at: "2026-09-24T00:00:00Z".into(),
support_until: until.map(str::to_string),
yanked: Default::default(),
known_problems: Vec::new(),
}
}
fn including(layer: &str, includes: &[(&str, &str)]) -> Vec<u8> {
let entries = includes
.iter()
.map(|(digest, realm)| {
format!(
r#"{{"mediaType":"application/vnd.oci.image.index.v1+json","digest":"{digest}","size":0,"annotations":{{"eu.pulseengine.varve.kind":"layer","{}":"{realm}"}}}}"#,
crate::compose::ANN_INCLUDE_REALM
)
})
.collect::<Vec<_>>()
.join(",");
format!(
r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","artifactType":"application/vnd.pulseengine.varve.layer.v1+json","annotations":{{"eu.pulseengine.varve.layer":"{layer}","eu.pulseengine.varve.line":"{line}","eu.pulseengine.varve.channel":"rolling","eu.pulseengine.varve.counter":"0","org.opencontainers.image.created":"2026-09-24T00:00:00Z"}},"manifests":[{entries}]}}"#,
line = &layer[..layer.rfind('.').unwrap()],
)
.into_bytes()
}
struct TwoRealms {
mid: MemorySource,
deep: MemorySource,
pk: Vec<u8>,
}
impl RealmAccess for TwoRealms {
fn open(&self, realm: &str) -> Result<RealmView<'_>, String> {
let source: &dyn crate::source::LayerSource = match realm {
"mid" => &self.mid,
"deep" => &self.deep,
other => return Err(format!("realm '{other}' is not defined here")),
};
Ok(RealmView {
source: RealmSource::Single(source),
verifier: &AcceptAll,
trust: crate::keyroles::test_support::leak_rt(&self.pk),
})
}
}
fn two_realms(mid_until: &str, deep_until: &str) -> (TwoRealms, String) {
let (sk, pk) = generate_root_keypair();
let deep_bytes = wasm_layer();
let deep_digest = manifest_digest(&deep_bytes);
let mid_bytes = including("2026.10.3", &[(&deep_digest, "deep")]);
let st = |until: &str| {
status(1, Some(until))
.sign(&sk, "k")
.unwrap()
.as_bytes()
.to_vec()
};
let realms = TwoRealms {
mid: MemorySource::new()
.with_manifest(&mid_bytes)
.with_line_status(&st(mid_until)),
deep: MemorySource::new()
.with_manifest(&deep_bytes)
.with_line_status(&st(deep_until)),
pk,
};
(realms, manifest_digest(&mid_bytes))
}
#[test]
fn a_window_deeper_in_the_composition_caps_the_include() {
let (realms, mid) = two_realms("2026-12-31", "2026-11-01");
let w = include_window_deep(&realms, &mid, "mid").unwrap();
assert_eq!(w.support_until.as_deref(), Some("2026-11-01"), "{w:?}");
assert_eq!((w.layer.as_str(), w.realm.as_str()), ("2026.10.0", "deep"));
let (realms, mid) = two_realms("2026-10-30", "2026-11-01");
let w = include_window_deep(&realms, &mid, "mid").unwrap();
assert_eq!(w.support_until.as_deref(), Some("2026-10-30"));
assert_eq!(w.realm, "mid");
}
struct OneRealm {
source: MemorySource,
pk: Vec<u8>,
}
impl RealmAccess for OneRealm {
fn open(&self, _: &str) -> Result<RealmView<'_>, String> {
Ok(RealmView {
source: RealmSource::Single(&self.source),
verifier: &AcceptAll,
trust: crate::keyroles::test_support::leak_rt(&self.pk),
})
}
}
fn chain(n: usize) -> (OneRealm, String) {
let (sk, pk) = generate_root_keypair();
let mut source = MemorySource::new().with_line_status(
status(1, Some("2026-12-31"))
.sign(&sk, "k")
.unwrap()
.as_bytes(),
);
let mut below = wasm_layer();
source = source.with_manifest(&below);
for k in 1..n {
let next = including(
&format!("2026.10.{k}"),
&[(&manifest_digest(&below), "one")],
);
source = source.with_manifest(&next);
below = next;
}
(OneRealm { source, pk }, manifest_digest(&below))
}
#[test]
fn the_walk_is_bounded_at_exactly_max_include_depth() {
let (realm, top) = chain(MAX_INCLUDE_DEPTH + 1);
assert!(include_window_deep(&realm, &top, "one").is_ok());
let (realm, top) = chain(MAX_INCLUDE_DEPTH + 2);
let err = include_window_deep(&realm, &top, "one").unwrap_err();
assert!(err.to_string().contains("nested deeper than 16"), "{err}");
}
#[test]
fn a_composition_wider_than_the_node_cap_is_refused() {
let (sk, pk) = generate_root_keypair();
let mut source = MemorySource::new().with_line_status(
status(1, Some("2026-12-31"))
.sign(&sk, "k")
.unwrap()
.as_bytes(),
);
let mut leaves = Vec::new();
for k in 0..MAX_INCLUDE_NODES {
let leaf = including(&format!("2026.10.{k}"), &[]);
source = source.with_manifest(&leaf);
leaves.push(manifest_digest(&leaf));
}
let refs: Vec<(&str, &str)> = leaves.iter().map(|d| (d.as_str(), "one")).collect();
let wide = including("2026.10.999", &refs);
source = source.with_manifest(&wide);
let realm = OneRealm { source, pk };
let err = include_window_deep(&realm, &manifest_digest(&wide), "one").unwrap_err();
assert!(
err.to_string().contains("more than 256 distinct layers"),
"{err}"
);
let (sk2, pk2) = generate_root_keypair();
let mut s2 = MemorySource::new().with_line_status(
status(1, Some("2026-12-31"))
.sign(&sk2, "k")
.unwrap()
.as_bytes(),
);
let mut l2 = Vec::new();
for k in 0..MAX_INCLUDE_NODES - 1 {
let leaf = including(&format!("2026.10.{k}"), &[]);
s2 = s2.with_manifest(&leaf);
l2.push(manifest_digest(&leaf));
}
let r2: Vec<(&str, &str)> = l2.iter().map(|d| (d.as_str(), "one")).collect();
let fits = including("2026.10.999", &r2);
s2 = s2.with_manifest(&fits);
let realm2 = OneRealm {
source: s2,
pk: pk2,
};
assert!(include_window_deep(&realm2, &manifest_digest(&fits), "one").is_ok());
}
#[test]
fn a_diamond_reads_its_shared_base_once() {
let (sk, pk) = generate_root_keypair();
let base = wasm_layer();
let bd = manifest_digest(&base);
let left = including("2026.10.1", &[(&bd, "one")]);
let right = including("2026.10.2", &[(&bd, "one")]);
let top = including(
"2026.10.3",
&[
(&manifest_digest(&left), "one"),
(&manifest_digest(&right), "one"),
],
);
let source = MemorySource::new()
.with_line_status(
status(1, Some("2026-12-31"))
.sign(&sk, "k")
.unwrap()
.as_bytes(),
)
.with_manifest(&base)
.with_manifest(&left)
.with_manifest(&right)
.with_manifest(&top);
let counting = Counting {
inner: OneRealm { source, pk },
opens: std::cell::Cell::new(0),
};
include_window_deep(&counting, &manifest_digest(&top), "one").unwrap();
assert_eq!(
counting.opens.get(),
4,
"top, left, right, and the base ONCE"
);
}
struct Counting {
inner: OneRealm,
opens: std::cell::Cell<usize>,
}
impl RealmAccess for Counting {
fn open(&self, realm: &str) -> Result<RealmView<'_>, String> {
self.opens.set(self.opens.get() + 1);
self.inner.open(realm)
}
}
#[test]
fn earlier_prefers_the_unstated_then_the_earliest_then_the_first() {
let w = |l: &str, u: Option<&str>| IncludeWindow {
layer: l.into(),
realm: "r".into(),
support_until: u.map(str::to_string),
};
assert_eq!(earlier(w("a", None), w("b", Some("2026-01-01"))).layer, "a");
assert_eq!(earlier(w("a", None), w("b", None)).layer, "a");
assert_eq!(
earlier(w("a", Some("2026-01-01")), w("b", Some("soon"))).layer,
"b"
);
assert_eq!(
earlier(w("a", Some("soon")), w("b", Some("2026-01-01"))).layer,
"a"
);
assert_eq!(earlier(w("a", Some("2026-01-01")), w("b", None)).layer, "b");
assert_eq!(
earlier(w("a", Some("2026-02-01")), w("b", Some("2026-01-01"))).layer,
"b"
);
assert_eq!(
earlier(w("a", Some("2026-01-01")), w("b", Some("2026-02-01"))).layer,
"a"
);
assert_eq!(
earlier(w("a", Some("2026-01-01")), w("b", Some("2026-01-01"))).layer,
"a"
);
}
#[test]
fn a_nested_include_in_an_unknown_realm_is_refused_by_name() {
let (realms, mid) = two_realms("2026-12-31", "2026-11-01");
let only_mid = OnlyMid(&realms);
let err = include_window_deep(&only_mid, &mid, "mid").unwrap_err();
assert!(err.to_string().contains("deep"), "{err}");
}
struct OnlyMid<'a>(&'a TwoRealms);
impl RealmAccess for OnlyMid<'_> {
fn open(&self, realm: &str) -> Result<RealmView<'_>, String> {
if realm == "mid" {
self.0.open(realm)
} else {
Err(format!("realm '{realm}' is not defined here"))
}
}
}
#[test]
fn an_include_window_comes_from_its_own_signed_status() {
let (sk, pk) = generate_root_keypair();
let bytes = wasm_layer();
let source = MemorySource::new().with_manifest(&bytes).with_line_status(
status(1, Some("2026-10-24"))
.sign(&sk, "k")
.unwrap()
.as_bytes(),
);
let w = include_window(
&source,
&AcceptAll,
&crate::keyroles::test_support::rt(&pk),
&manifest_digest(&bytes),
"wasm",
)
.unwrap();
assert_eq!(
w,
IncludeWindow {
layer: "2026.10.0".into(),
realm: "wasm".into(),
support_until: Some("2026-10-24".into()),
}
);
}
#[test]
fn a_published_correction_overtakes_the_baseline_window() {
let (sk, pk) = generate_root_keypair();
let bytes = wasm_layer();
let source = MemorySource::new()
.with_manifest(&bytes)
.with_line_status(
status(1, Some("2026-10-24"))
.sign(&sk, "k")
.unwrap()
.as_bytes(),
)
.with_published_line_status(
status(5, Some("2026-10-10"))
.sign(&sk, "k")
.unwrap()
.as_bytes(),
);
let w = include_window(
&source,
&AcceptAll,
&crate::keyroles::test_support::rt(&pk),
&manifest_digest(&bytes),
"wasm",
)
.unwrap();
assert_eq!(w.support_until.as_deref(), Some("2026-10-10"));
}
#[test]
fn a_status_not_signed_by_the_includes_realm_is_refused() {
let (sk_other, _) = generate_root_keypair();
let (_, pk) = generate_root_keypair();
let bytes = wasm_layer();
let source = MemorySource::new().with_manifest(&bytes).with_line_status(
status(1, Some("2027-12-31"))
.sign(&sk_other, "k")
.unwrap()
.as_bytes(),
);
let err = include_window(
&source,
&AcceptAll,
&crate::keyroles::test_support::rt(&pk),
&manifest_digest(&bytes),
"wasm",
)
.unwrap_err();
assert!(
err.to_string().contains("2026.10.0") || err.to_string().contains("sha256:"),
"{err}"
);
}
#[test]
fn a_correction_that_cannot_be_fetched_refuses_rather_than_reading_as_none() {
use crate::source::{LayerRef, LayerSource, SourceError};
struct CorrectionUnreachable(MemorySource);
impl LayerSource for CorrectionUnreachable {
fn fetch_manifest(&self, l: &LayerRef) -> Result<Vec<u8>, SourceError> {
self.0.fetch_manifest(l)
}
fn fetch_blob(&self, d: &str) -> Result<Vec<u8>, SourceError> {
self.0.fetch_blob(d)
}
fn fetch_line_status(&self, l: &LayerRef) -> Result<Option<Vec<u8>>, SourceError> {
self.0.fetch_line_status(l)
}
fn fetch_published_line_status(
&self,
_: &str,
) -> Result<Option<Vec<u8>>, SourceError> {
Err(SourceError::Transport("connection reset".into()))
}
}
let (sk, pk) = generate_root_keypair();
let bytes = wasm_layer();
let source = CorrectionUnreachable(
MemorySource::new().with_manifest(&bytes).with_line_status(
status(1, Some("2026-10-24"))
.sign(&sk, "k")
.unwrap()
.as_bytes(),
),
);
let err = include_window(
&source,
&AcceptAll,
&crate::keyroles::test_support::rt(&pk),
&manifest_digest(&bytes),
"wasm",
)
.unwrap_err();
assert!(err.reason.contains("connection reset"), "{err}");
}
#[test]
fn an_include_with_no_status_states_no_window() {
let (_, pk) = generate_root_keypair();
let bytes = wasm_layer();
let source = MemorySource::new().with_manifest(&bytes);
let w = include_window(
&source,
&AcceptAll,
&crate::keyroles::test_support::rt(&pk),
&manifest_digest(&bytes),
"wasm",
)
.unwrap();
assert_eq!(w.support_until, None);
assert!(cap_by_includes("2026-11-02", &[w], None, "2026-01-01").is_err());
}
#[test]
fn an_include_whose_manifest_does_not_verify_is_refused() {
let (sk, pk) = generate_root_keypair();
let bytes = wasm_layer();
let source = MemorySource::new().with_manifest(&bytes).with_line_status(
status(1, Some("2026-10-24"))
.sign(&sk, "k")
.unwrap()
.as_bytes(),
);
assert!(
include_window(
&source,
&RejectAll,
&crate::keyroles::test_support::rt(&pk),
&manifest_digest(&bytes),
"wasm"
)
.is_err()
);
}
}
mod mirrored {
use super::super::*;
use crate::install::{ManifestVerifier, VerifyError};
use crate::linestatus::LineStatus;
use crate::manifest::fixtures::manifest_with_tools;
use crate::mirror::{Mirror, Mirrors};
use crate::source::MemorySource;
use crate::store::manifest_digest;
use crate::verify::generate_root_keypair;
use std::cell::Cell;
struct RejectsFirst(Cell<bool>);
impl ManifestVerifier for RejectsFirst {
fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
if self.0.replace(true) {
Ok(fetched.to_vec())
} else {
Err(VerifyError("No valid signatures (test)".into()))
}
}
}
struct Realm<'a> {
mirrors: &'a Mirrors,
verifier: &'a dyn ManifestVerifier,
pk: &'a [u8],
}
impl RealmAccess for Realm<'_> {
fn open(&self, _: &str) -> Result<RealmView<'_>, String> {
Ok(RealmView {
source: RealmSource::Failover(self.mirrors),
verifier: self.verifier,
trust: crate::keyroles::test_support::leak_rt(self.pk),
})
}
}
fn status_doc(until: &str, sk: &[u8], counter: u64) -> Vec<u8> {
LineStatus {
min_counter: None,
line: "2026.10".into(),
counter,
issued_at: "2026-09-24T00:00:00Z".into(),
support_until: Some(until.into()),
yanked: Default::default(),
known_problems: Vec::new(),
}
.sign(sk, "k")
.unwrap()
.into_bytes()
}
fn mirror(label: &str, source: MemorySource) -> Mirror {
Mirror {
label: label.into(),
source: Box::new(source),
}
}
fn window_with(
primary_baseline: Option<(&str, u64)>,
primary_correction: Option<(&str, u64)>,
mirror_baseline: Option<(&str, u64)>,
mirror_correction: Option<(&str, u64)>,
) -> (Result<IncludeWindow, String>, Mirrors) {
let (sk, pk) = generate_root_keypair();
let bytes = manifest_with_tools("2026.10.0", "rolling", 0, "2026-09-24T00:00:00Z", &[]);
let digest = manifest_digest(&bytes);
let carry = |mut source: MemorySource,
baseline: Option<(&str, u64)>,
correction: Option<(&str, u64)>| {
if let Some((until, counter)) = baseline {
source = source.with_line_status(&status_doc(until, &sk, counter));
}
if let Some((until, counter)) = correction {
source = source.with_published_line_status(&status_doc(until, &sk, counter));
}
source
};
let primary = carry(
MemorySource::new().with_manifest(&bytes),
primary_baseline,
primary_correction,
);
let second = carry(
MemorySource::new().with_manifest(&bytes),
mirror_baseline,
mirror_correction,
);
let mirrors = Mirrors::new(vec![mirror("primary", primary), mirror("mirror", second)]);
let verifier = RejectsFirst(Cell::new(false));
let r = {
let realm = Realm {
mirrors: &mirrors,
verifier: &verifier,
pk: &pk,
};
include_window_deep(&realm, &digest, "acme").map_err(|e| e.to_string())
};
(r, mirrors)
}
#[test]
fn the_layer_may_come_from_a_mirror_but_the_window_is_the_primarys() {
let (w, mirrors) =
window_with(Some(("2026-11-20", 5)), None, Some(("2026-12-01", 1)), None);
assert_eq!(
w.unwrap().support_until.as_deref(),
Some("2026-11-20"),
"the primary's baseline decides"
);
assert_eq!(mirrors.served_by().as_deref(), Some("mirror"));
let (w, _) = window_with(
Some(("2026-11-20", 5)),
Some(("2026-11-15", 6)),
Some(("2026-12-01", 1)),
None,
);
assert_eq!(w.unwrap().support_until.as_deref(), Some("2026-11-15"));
}
#[test]
fn nothing_a_mirror_holds_about_status_is_ever_used() {
let (w, _) = window_with(
Some(("2026-11-20", 5)),
None,
Some(("2027-06-01", 9)),
Some(("2027-06-01", 9)),
);
assert_eq!(w.unwrap().support_until.as_deref(), Some("2026-11-20"));
let (w, _) = window_with(None, None, Some(("2027-06-01", 9)), None);
assert_eq!(w.unwrap().support_until, None);
}
struct Down;
impl crate::source::LayerSource for Down {
fn fetch_manifest(
&self,
_: &crate::source::LayerRef,
) -> Result<Vec<u8>, crate::source::SourceError> {
Err(crate::source::SourceError::Transport("down".into()))
}
fn fetch_blob(&self, _: &str) -> Result<Vec<u8>, crate::source::SourceError> {
Err(crate::source::SourceError::Transport("down".into()))
}
fn fetch_published_line_status(
&self,
_: &str,
) -> Result<Option<Vec<u8>>, crate::source::SourceError> {
Err(crate::source::SourceError::Transport("down".into()))
}
}
#[test]
fn a_primary_status_that_does_not_verify_is_terminal_not_retried_on_a_mirror() {
let (sk, pk) = generate_root_keypair();
let (other_sk, _) = generate_root_keypair();
let bytes = manifest_with_tools("2026.10.0", "rolling", 0, "2026-09-24T00:00:00Z", &[]);
let digest = manifest_digest(&bytes);
let primary = MemorySource::new()
.with_manifest(&bytes)
.with_line_status(&status_doc("2026-11-20", &other_sk, 5));
let second = MemorySource::new()
.with_manifest(&bytes)
.with_line_status(&status_doc("2026-12-01", &sk, 1));
let mirrors = Mirrors::new(vec![mirror("primary", primary), mirror("mirror", second)]);
let verifier = RejectsFirst(Cell::new(false));
let realm = Realm {
mirrors: &mirrors,
verifier: &verifier,
pk: &pk,
};
let err = include_window_deep(&realm, &digest, "acme")
.expect_err("the primary's status is unverifiable");
assert!(!err.retry_elsewhere);
assert!(!err.to_string().contains("Tried"), "{err}");
}
#[test]
fn when_the_primary_cannot_answer_for_corrections_the_window_is_not_established() {
let (sk, pk) = generate_root_keypair();
let bytes = manifest_with_tools("2026.10.0", "rolling", 0, "2026-09-24T00:00:00Z", &[]);
let digest = manifest_digest(&bytes);
let second = MemorySource::new()
.with_manifest(&bytes)
.with_line_status(&status_doc("2026-12-01", &sk, 1))
.with_published_line_status(&status_doc("2026-10-24", &sk, 2));
let mirrors = Mirrors::new(vec![
Mirror {
label: "primary".into(),
source: Box::new(Down),
},
mirror("mirror", second),
]);
let realm = Realm {
mirrors: &mirrors,
verifier: &RejectsNone,
pk: &pk,
};
let err = include_window_deep(&realm, &digest, "acme")
.expect_err("a mirror cannot stand in for the primary's corrections");
let text = err.to_string();
assert!(text.contains("could not be established"), "{text}");
assert!(
text.contains("only taken from the realm's primary"),
"{text}"
);
assert!(!err.retry_elsewhere);
assert!(!text.contains("Tried"), "{text}");
}
#[test]
fn a_primary_that_answers_no_correction_establishes_absence_for_itself() {
let (sk, pk) = generate_root_keypair();
let bytes = manifest_with_tools("2026.10.0", "rolling", 0, "2026-09-24T00:00:00Z", &[]);
let digest = manifest_digest(&bytes);
let mirrors = Mirrors::new(vec![mirror(
"primary",
MemorySource::new()
.with_manifest(&bytes)
.with_line_status(&status_doc("2026-11-20", &sk, 1)),
)]);
let realm = Realm {
mirrors: &mirrors,
verifier: &RejectsNone,
pk: &pk,
};
let w = include_window_deep(&realm, &digest, "acme").unwrap();
assert_eq!(w.support_until.as_deref(), Some("2026-11-20"));
}
struct RejectsNone;
impl ManifestVerifier for RejectsNone {
fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
Ok(fetched.to_vec())
}
}
#[test]
fn when_every_source_fails_the_error_lists_each_in_order() {
let (_sk, pk) = generate_root_keypair();
let bytes = manifest_with_tools("2026.10.0", "rolling", 0, "2026-09-24T00:00:00Z", &[]);
let digest = manifest_digest(&bytes);
let mirrors = Mirrors::new(vec![
mirror("primary", MemorySource::new().with_manifest(&bytes)),
mirror("mirror", MemorySource::new().with_manifest(&bytes)),
]);
struct RejectAll;
impl ManifestVerifier for RejectAll {
fn verify(&self, _: &[u8]) -> Result<Vec<u8>, VerifyError> {
Err(VerifyError("forged (test)".into()))
}
}
let realm = Realm {
mirrors: &mirrors,
verifier: &RejectAll,
pk: &pk,
};
let err = include_window_deep(&realm, &digest, "acme").unwrap_err();
let text = err.to_string();
let (p, m) = (text.find("primary"), text.find("mirror"));
assert!(p.is_some() && m.is_some() && p < m, "{text}");
assert!(text.contains("forged (test)"), "{text}");
}
fn failure(reason: &str, retry: bool) -> IncludeWindowError {
IncludeWindowError {
include: "sha256:x".into(),
realm: "acme".into(),
reason: reason.into(),
retry_elsewhere: retry,
}
}
#[test]
fn a_terminal_failure_stands_alone_and_one_source_keeps_its_own_error() {
let terminal = all_sources_failed(
"sha256:x",
"acme",
vec![
("a".into(), failure("down", true)),
("b".into(), failure("verdict", false)),
],
);
assert_eq!(terminal.reason, "verdict");
let single = all_sources_failed(
"sha256:x",
"acme",
vec![("a".into(), failure("down", true))],
);
assert_eq!(single.reason, "down");
let many = all_sources_failed(
"sha256:x",
"acme",
vec![
("a".into(), failure("down", true)),
("b".into(), failure("also down", true)),
],
);
assert!(
many.reason.contains("a: down")
&& many.reason.contains("b: also down")
&& many.reason.contains("2 source(s)"),
"{}",
many.reason
);
assert!(!many.retry_elsewhere);
}
}
}