Skip to content
Merged
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
165 changes: 159 additions & 6 deletions pkgs/id/src/world_net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -989,7 +989,9 @@ impl WorldClient {
///
/// # Errors
///
/// Fails with the host's message if neither credential is accepted.
/// Fails with the host's message if neither credential is accepted,
/// or with "host sent a malformed seed" if the reply's `seed` field
/// is present but not a `u64`.
pub async fn manifest_state(
&mut self,
admin_token: Option<&str>,
Expand All @@ -1005,12 +1007,42 @@ impl WorldClient {
.recv_json()
.await?
.context("host closed without replying")?;
Self::parse_world_state_reply(&reply)
}

/// Validate a `world_state` reply frame and extract the manifest
/// state: a `seed` that is *absent* is the one legitimate `None`
/// (a capability-only read, where the host deliberately hides the
/// seed, #240), but a seed that is present with the wrong type is
/// corruption, not a hidden seed -- reading it with a bare
/// `as_u64()` silently downgraded it to the capability-only shape,
/// and the manifest-capture consumer then baked it in as seed 0
/// (#6626). `schedules` keeps its strict decode. Factored out of
/// [`WorldClient::manifest_state`] (mirroring
/// [`WorldClient::parse_caps_reply`]) so the validation can be
/// unit-tested without a live host sending frames no real host
/// sends.
fn parse_world_state_reply(
reply: &serde_json::Value,
) -> Result<(Option<u64>, std::collections::BTreeMap<String, u64>)> {
match reply["type"].as_str() {
Some("world_state") => Ok((
reply["seed"].as_u64(),
serde_json::from_value(reply["schedules"].clone())
.context("host sent a malformed schedule map")?,
)),
Some("world_state") => {
let seed = match reply.get("seed") {
// Absent, or null: the host serializes a hidden seed
// as null (`ServerFrame::WorldState.seed` is an
// `Option<u64>` with no skip-serializing, and both
// host reply paths set it to
// `admin_ok.then_some(seed)`), so null is the
// legitimate capability-only shape (#240).
None | Some(serde_json::Value::Null) => None,
Some(value) => Some(value.as_u64().context("host sent a malformed seed")?),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve null seeds from capability-only replies

For capability-only reads, the existing host sends "seed": null, not an absent field: ServerFrame::WorldState.seed is an Option<u64> without skip_serializing_if (world_session/types.rs), and both host reply paths set it to admin_ok.then_some(seed) (world_session/mod.rs). This branch now rejects those legitimate replies with host sent a malformed seed, breaking world diff, whose handler calls current_world_state(&client, &capability, None) in commands/world.rs. Continue accepting null as None while rejecting the other mistyped values.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f6e8b87 (pushed to this branch by Lane B, resuming Lane R's parked claim on #6626): parse_world_state_reply now accepts "seed": null (and an absent seed) as None, while string/negative/float/object/array/bool seeds still fail with host sent a malformed seed.

Verified the finding against source before fixing: ServerFrame::WorldState.seed is Option<u64> with no skip_serializing_if (pkgs/id/src/world_session/types.rs), and both host reply paths set seed: admin_ok.then_some(seed) (world_session/mod.rs:1471, :2858) — so capability-only replies do arrive as "seed": null. The regression test world_state_reply_requires_a_u64_seed_when_present now covers the actual host shape (null seed + schedules parse to None); world_net suite 29/29 pass on the laptop.

};
Ok((
seed,
serde_json::from_value(reply["schedules"].clone())
.context("host sent a malformed schedule map")?,
))
}
_ => bail!(
"{}",
reply["message"]
Expand Down Expand Up @@ -2728,6 +2760,127 @@ mod tests {
assert!(refused.err().unwrap().to_string().contains("admin token refused"));
}

#[test]
fn world_state_reply_requires_a_u64_seed_when_present() {
Comment on lines +2763 to +2764

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Cover the reply-parser invariants with property tests

For this parser change, the regression coverage consists only of fixed examples, contrary to the root AGENTS.md testing doctrine requiring property tests for meaningful parser invariants. Add proptest coverage that preserves arbitrary valid u64 seeds and schedule maps, accepts absent/null seeds, and rejects other seed types, using the typed world-state frame contract as the oracle. The existing property tests in this module do not exercise this parser.

AGENTS.md reference: AGENTS.md:L41-L45

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5b53b65: added world_state_reply_seed_and_schedule_invariants, a proptest in the same module (oracle: the typed ServerFrame::WorldState frame contract) that hammers arbitrary u64 seeds and schedule maps (both preserved verbatim), null seeds (read as None), and string/bool/array/object seed shapes (refused as malformed seed). Laptop: cargo test --lib world_net 30/30 pass, including the new property test.

// Issue #6626: a present-but-mistyped `seed` must error, not
// silently read as the capability-only `None` (which the
// manifest-capture consumer then bakes in as seed 0). Only an
// absent seed is `None` outright; a null seed is also `None`,
// because that is how the host serializes a hidden seed
// (`ServerFrame::WorldState.seed`, #240 seed-hiding). Driven
// through the factored reply parser manifest_state() uses.
let parse = WorldClient::parse_world_state_reply;

// Controls: a numeric seed, and the legitimate absent seed.
let (seed, schedules) = parse(&serde_json::json!({
"type": "world_state", "seed": 42, "schedules": {"a": 1},
}))
.unwrap();
assert_eq!(seed, Some(42));
assert_eq!(schedules.get("a"), Some(&1));
let (seed, schedules) = parse(&serde_json::json!({
"type": "world_state", "schedules": {},
}))
.unwrap();
assert_eq!(seed, None);
assert!(schedules.is_empty());
// The host's actual capability-only shape: `"seed": null`.
let (seed, schedules) = parse(&serde_json::json!({
"type": "world_state", "seed": null, "schedules": {"b": 2},
}))
.unwrap();
assert_eq!(seed, None);
assert_eq!(schedules.get("b"), Some(&2));

// Every mistyped shape errors and names the malformed seed.
for bad in [
serde_json::json!("42"),
serde_json::json!(-1),
serde_json::json!(1.5),
serde_json::json!({}),
serde_json::json!([]),
serde_json::json!(true),
] {
let err = parse(&serde_json::json!({
"type": "world_state", "seed": bad, "schedules": {},
}))
.err()
.unwrap_or_else(|| panic!("seed {bad} must be refused"));
assert!(
err.to_string().contains("malformed seed"),
"seed {bad}: {err}"
);
}

// The sibling field keeps its strict decode.
let err = parse(&serde_json::json!({
"type": "world_state", "seed": 42, "schedules": {"a": "x"},
}))
.err()
.unwrap();
assert!(err.to_string().contains("malformed schedule map"), "{err}");

// A refusal frame still surfaces the host's message.
let err = parse(&serde_json::json!({
"type": "error", "message": "admin token refused",
}))
.err()
.unwrap();
assert!(err.to_string().contains("admin token refused"), "{err}");
}

// Property coverage for the same parser (repo testing doctrine:
// a parser's invariants are stated once and hammered with
// generated inputs, not just the examples above). Oracle: the
// typed frame contract — `ServerFrame::WorldState.seed` is an
// `Option<u64>` on the wire (a u64, or null when the host hides
// the seed, #240), and `schedules` is a string→u64 map that
// passes through untouched.
proptest! {
#[test]
fn world_state_reply_seed_and_schedule_invariants(
seed in any::<u64>(),
schedules in proptest::collection::btree_map(any::<String>(), any::<u64>(), 0..8),
mistyped in prop_oneof![
any::<String>().prop_map(serde_json::Value::from),
any::<bool>().prop_map(serde_json::Value::from),
proptest::collection::vec(any::<u64>(), 0..4)
.prop_map(serde_json::Value::from),
proptest::collection::hash_map(any::<String>(), any::<u64>(), 0..4)
.prop_map(|m| serde_json::to_value(m).unwrap()),
],
) {
let frame = |seed_value: serde_json::Value| {
serde_json::json!({
"type": "world_state",
"seed": seed_value,
"schedules": serde_json::to_value(&schedules).unwrap(),
})
};
// A valid u64 seed is preserved; the schedule map passes
// through verbatim.
let (parsed_seed, parsed_schedules) =
WorldClient::parse_world_state_reply(&frame(serde_json::Value::from(seed)))
.unwrap();
prop_assert_eq!(parsed_seed, Some(seed));
prop_assert_eq!(parsed_schedules, schedules.clone());
// Null (the host's hidden-seed shape) reads as None.
let (parsed_seed, _) =
WorldClient::parse_world_state_reply(&frame(serde_json::Value::Null)).unwrap();
prop_assert_eq!(parsed_seed, None);
// Any other seed type is refused as malformed.
let result = WorldClient::parse_world_state_reply(&frame(mistyped));
prop_assert!(result.is_err());
prop_assert!(
result
.err()
.unwrap()
.to_string()
.contains("malformed seed")
);
}
}

#[test]
fn caps_reply_requires_a_valid_report() {
// Issue #6624: a `caps` frame carrying no valid CapsReport must
Expand Down
Loading