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
181 changes: 165 additions & 16 deletions pkgs/id/src/world_net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1719,6 +1719,56 @@ impl WorldClient {
}
}

/// Parse the head fields of an `event_history_begin` frame.
///
/// Factored out of [`WorldClient::admin_event_history`] so the frame
/// validation can be unit-tested without a rogue host. Every field is
/// strict: the host's typed frame (`ServerFrame::EventHistoryBegin`)
/// serializes `module_hash` as a string or `null`, so a present
/// non-string, non-null `module_hash` is a malformed reply (#6641),
/// never "this world has no module" — the same match-and-bail pattern
/// `parse_module_info_reply` applies to the `module_info` reply (#6633).
/// Returns `(world_id, module_hash, current_sequence, complete, event_count)`.
fn parse_event_history_begin(
begin: &serde_json::Value,
) -> Result<(String, Option<String>, u64, bool, usize)> {
let world_id = begin["world_id"]
.as_str()
.context("history reply has no world ID")?
.to_owned();
let module_hash = match begin.get("module_hash") {
None | Some(serde_json::Value::Null) => None,
Some(value) => {
if let Some(hash) = value.as_str() {
Some(hash.to_owned())
} else {
bail!(
"history reply has a malformed module_hash: expected string or null, got {}",
match value {
serde_json::Value::Bool(_) => "boolean",
serde_json::Value::Number(_) => "number",
serde_json::Value::Array(_) => "array",
serde_json::Value::Object(_) => "object",
_ => "unknown",
}
);
}
}
};
let current_sequence = begin["current_sequence"]
.as_u64()
.context("history reply has no sequence")?;
let complete = begin["complete"]
.as_bool()
.context("history reply has no completeness flag")?;
let event_count = begin["event_count"]
.as_u64()
.and_then(|count| usize::try_from(count).ok())
.filter(|count| *count <= crate::world::MAX_ADMIN_HISTORY_EVENTS)
.context("history reply has an invalid event count")?;
Ok((world_id, module_hash, current_sequence, complete, event_count))
}

/// Export the retained journal-order event window and its records as an
/// administrator. Join capabilities cannot request this frame.
///
Expand Down Expand Up @@ -1748,22 +1798,8 @@ impl WorldClient {
.unwrap_or("host refused admin history export")
);
}
let world_id = begin["world_id"]
.as_str()
.context("history reply has no world ID")?
.to_owned();
let module_hash = begin["module_hash"].as_str().map(str::to_owned);
let current_sequence = begin["current_sequence"]
.as_u64()
.context("history reply has no sequence")?;
let complete = begin["complete"]
.as_bool()
.context("history reply has no completeness flag")?;
let event_count = begin["event_count"]
.as_u64()
.and_then(|count| usize::try_from(count).ok())
.filter(|count| *count <= crate::world::MAX_ADMIN_HISTORY_EVENTS)
.context("history reply has an invalid event count")?;
let (world_id, module_hash, current_sequence, complete, event_count) =
Self::parse_event_history_begin(&begin)?;
let mut events = Vec::with_capacity(event_count);
for _ in 0..event_count {
let (frame, frame_bytes) = self
Expand Down Expand Up @@ -2146,6 +2182,8 @@ mod tests {
protocol::Router,
};

use proptest::prelude::*;

use super::*;
use crate::world::{WorldCore, WorldHandle, WorldLimits, WorldScopes};
use crate::world_session::{INVITE_MAX_SECS, WorldService};
Expand Down Expand Up @@ -3643,4 +3681,115 @@ mod tests {
"host refused to create the world"
);
}

#[test]
fn admin_event_history_begin_requires_a_string_or_null_module_hash() {
Comment on lines +3685 to +3686

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 Add property coverage for the begin-frame parser

The new parser regression test uses only fixed examples, but the root AGENTS.md testing doctrine explicitly requires property tests for meaningful parser invariants and says examples do not replace them. Add proptest coverage asserting that arbitrary string hashes are preserved, missing/null hashes become None, other JSON types are rejected, and valid sibling fields remain unchanged. This supplies the repository-required invariant coverage rather than checking only the selected literals.

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

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 44e106a's follow-up commit (this PR): added , a proptest over asserting exactly the invariants you named — arbitrary string hashes preserved verbatim with sibling fields (world_id, current_sequence, complete, event_count) unchanged, null → None, and generated number/bool/array/object hashes refused with the malformed-module_hash error. Oracle is the typed frame contract (ServerFrame::EventHistoryBegin serializes the hash as string-or-null). Verified on the laptop: both the example test and the proptest pass (cargo test -p id --lib admin_event_history, serial). — queue worker lane code-a

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correction to my previous reply (its code-formatted names were eaten by shell quoting): the follow-up commit is 5202006845, adding the proptest admin_event_history_begin_module_hash_invariants over WorldClient::parse_event_history_begin. Both it and the example test pass on the laptop (cargo test -p id --lib admin_event_history, serial).

// Issue #6641 (duplicate: #6642): a present, mistyped `module_hash`
// in the begin frame is a malformed reply, not "no module".
// Oracle: every sibling field of the same frame is strict, and the
// host's ServerFrame::EventHistoryBegin serializes the hash as a
// string or null only.
let begin_with = |hash: serde_json::Value| {
serde_json::json!({
"type": "event_history_begin",
"world_id": "test:world",
"module_hash": hash,
"current_sequence": 7,
"complete": true,
"event_count": 0,
})
};
let parse = |begin: serde_json::Value| WorldClient::parse_event_history_begin(&begin);

let (world_id, module_hash, seq, complete, count) =
parse(begin_with(serde_json::json!("abc123"))).unwrap();
assert_eq!(world_id, "test:world");
assert_eq!(module_hash, Some("abc123".to_string()));
assert_eq!(seq, 7);
assert!(complete);
assert_eq!(count, 0);

// Null and missing both read as None (legitimate no-module / older hosts).
let (_, module_hash, ..) = parse(begin_with(serde_json::Value::Null)).unwrap();
assert_eq!(module_hash, None);
let mut missing = begin_with(serde_json::Value::Null);
missing.as_object_mut().unwrap().remove("module_hash");
let (_, module_hash, ..) = parse(missing).unwrap();
assert_eq!(module_hash, None);

// Mistyped shapes are refused, naming the field.
for bad in [
serde_json::json!(123),
serde_json::json!(true),
serde_json::json!(["abc"]),
serde_json::json!({"hash": "abc"}),
] {
let result = parse(begin_with(bad));
assert!(result.is_err(), "mistyped module_hash must be refused");
let err = result.err().unwrap();
assert!(
err.to_string().contains("malformed module_hash"),
"unexpected error: {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 — `module_hash` is a string or null on the wire, and the
// sibling fields pass through untouched.
proptest! {
#[test]
fn admin_event_history_begin_module_hash_invariants(
hash in any::<String>(),
world_id in "[a-z][a-z0-9:_-]{0,20}",
seq in any::<u64>(),
complete in any::<bool>(),
count in 0u64..=1000,
mistyped in prop_oneof![
any::<i64>().prop_map(serde_json::Value::from),
any::<bool>().prop_map(serde_json::Value::from),
proptest::collection::vec(any::<String>(), 0..4)
.prop_map(serde_json::Value::from),
proptest::collection::hash_map(any::<String>(), any::<String>(), 0..4)
.prop_map(|m| serde_json::to_value(m).unwrap()),
],
) {
let begin = |module_hash: serde_json::Value| {
serde_json::json!({
"type": "event_history_begin",
"world_id": world_id,
"module_hash": module_hash,
"current_sequence": seq,
"complete": complete,
"event_count": count,
})
};
// Any string hash is preserved verbatim; siblings pass through.
let (w, h, s, c, n) = WorldClient::parse_event_history_begin(
&begin(serde_json::Value::String(hash.clone())),
)
.unwrap();
prop_assert_eq!(w.as_str(), world_id.as_str());
prop_assert_eq!(h.as_deref(), Some(hash.as_str()));
prop_assert_eq!(s, seq);
prop_assert_eq!(c, complete);
prop_assert_eq!(n, count as usize);
// Null reads as no module.
let (_, h, ..) =
WorldClient::parse_event_history_begin(&begin(serde_json::Value::Null)).unwrap();
prop_assert_eq!(h, None);
// Any other JSON type is refused as malformed.
let result = WorldClient::parse_event_history_begin(&begin(mistyped));
prop_assert!(result.is_err());
prop_assert!(
result
.err()
.unwrap()
.to_string()
.contains("malformed module_hash")
);
}
}
}
Loading