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
7 changes: 3 additions & 4 deletions pkgs/id/crates/id-core/src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,10 +292,9 @@ mod tests {

fn captured_load(dir: &Path) -> (Vec<EndpointId>, Vec<String>) {
let captured = std::sync::Arc::new(CapturedEvents::default());
let loaded = tracing::subscriber::with_default(
CaptureSubscriber(captured.clone()),
|| load_allowed_nodes(dir),
);
let loaded = tracing::subscriber::with_default(CaptureSubscriber(captured.clone()), || {
load_allowed_nodes(dir)
});
let lines = captured.lines.lock().unwrap().clone();
(loaded, lines)
}
Expand Down
9 changes: 7 additions & 2 deletions pkgs/id/crates/id-core/src/json_unique.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
/// `serde_json::Value` normally keeps only the last value for a repeated key,
/// which can make routing and later checks observe different bytes than the
/// client sent.
pub fn parse_json_without_duplicate_keys(text: &str) -> Result<serde_json::Value, serde_json::Error> {
pub fn parse_json_without_duplicate_keys(
text: &str,
) -> Result<serde_json::Value, serde_json::Error> {
use serde::Deserialize;
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use std::collections::HashSet;
Expand Down Expand Up @@ -149,7 +151,10 @@ mod tests {
r#"{"a":[{"b":1,"b":2}]}"#,
] {
let err = parse_json_without_duplicate_keys(text).unwrap_err();
assert!(err.to_string().contains("duplicate JSON object key"), "{err}");
assert!(
err.to_string().contains("duplicate JSON object key"),
"{err}"
);
}
}
}
3 changes: 2 additions & 1 deletion pkgs/id/crates/id-core/src/waiting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,8 @@ mod tests {
// and no deps at all. In each, applying the event through another path
// must not hand the same event out again (#4730).
let mut pool = pool();
pool.insert(author(1), 1, [10], "ready-after-dep", 0).unwrap();
pool.insert(author(1), 1, [10], "ready-after-dep", 0)
.unwrap();
assert!(pool.arrived(1, 0).is_empty());
assert!(
pool.take_ready().is_empty(),
Expand Down
5 changes: 1 addition & 4 deletions pkgs/id/src/world/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5136,10 +5136,7 @@ mod tests {
}
// An oversized value hidden behind a small duplicate never reaches
// the size check as a collapsed survivor: the duplicate refuses it.
let hidden = format!(
r#"{{"k":"{}","k":1}}"#,
"v".repeat(MAX_RECORD_VALUE_BYTES)
);
let hidden = format!(r#"{{"k":"{}","k":1}}"#, "v".repeat(MAX_RECORD_VALUE_BYTES));
assert!(parse_records(&hidden).is_err());
// 4097 raw entries collapsing to 4096 distinct keys are refused as
// duplicates, so the count cap can no longer be evaded by collapse.
Expand Down
45 changes: 24 additions & 21 deletions pkgs/id/src/world_net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,9 @@ impl WorldClient {
Some(value) => match value.as_u64() {
Some(sequence) => sequence,
None => {
bail!("host sent a malformed compiled reply: `sequence` is not an unsigned integer")
bail!(
"host sent a malformed compiled reply: `sequence` is not an unsigned integer"
)
}
},
None => bail!("host sent no sequence in compiled reply"),
Expand Down Expand Up @@ -847,16 +849,12 @@ impl WorldClient {
/// [`WorldClient::parse_caps_ceiling_reply`]) so the validation can
/// be unit-tested without a live host sending frames no real host
/// sends.
fn parse_caps_reply(
reply: &serde_json::Value,
refusal: &str,
) -> Result<serde_json::Value> {
fn parse_caps_reply(reply: &serde_json::Value, refusal: &str) -> Result<serde_json::Value> {
if reply["type"] != "caps" {
bail!("{}", reply["message"].as_str().unwrap_or(refusal));
}
let _: crate::world_caps::CapsReport =
serde_json::from_value(reply["report"].clone())
.context("host sent a malformed capability report")?;
let _: crate::world_caps::CapsReport = serde_json::from_value(reply["report"].clone())
.context("host sent a malformed capability report")?;
Ok(reply["report"].clone())
}

Expand Down Expand Up @@ -930,9 +928,8 @@ impl WorldClient {
.unwrap_or("host refused the capability ceiling change")
);
}
let report: crate::world_caps::CapsReport =
serde_json::from_value(reply["report"].clone())
.context("host sent a malformed capability report")?;
let report: crate::world_caps::CapsReport = serde_json::from_value(reply["report"].clone())
.context("host sent a malformed capability report")?;
let mut validated = reply.clone();
validated["report"] =
serde_json::to_value(report).context("re-encode the capability report")?;
Expand Down Expand Up @@ -1811,7 +1808,13 @@ impl WorldClient {
.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))
Ok((
world_id,
module_hash,
current_sequence,
complete,
event_count,
))
}

/// Export the retained journal-order event window and its records as an
Expand Down Expand Up @@ -2758,7 +2761,13 @@ mod tests {
"type": "error",
"message": "admin token refused",
}));
assert!(refused.err().unwrap().to_string().contains("admin token refused"));
assert!(
refused
.err()
.unwrap()
.to_string()
.contains("admin token refused")
);
}

#[test]
Expand Down Expand Up @@ -3895,20 +3904,14 @@ mod tests {
serde_json::json!({"type": "compiled", "module_hash": null, "sequence": 7, "diagnostics": ""}),
] {
let result = parse(bad_reply);
assert!(
result.is_err(),
"mistyped field must error, got {result:?}"
);
assert!(result.is_err(), "mistyped field must error, got {result:?}");
}

// The refusal path still surfaces the host's message.
let result = parse(serde_json::json!({"type": "error", "message": "bad admin token"}));
assert_eq!(result.err().unwrap().to_string(), "bad admin token");
let result = parse(serde_json::json!({"type": "error"}));
assert_eq!(
result.err().unwrap().to_string(),
"host refused to compile"
);
assert_eq!(result.err().unwrap().to_string(), "host refused to compile");
}

#[test]
Expand Down
3 changes: 1 addition & 2 deletions pkgs/id/src/world_session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ use serde::Serialize;
use subtle::ConstantTimeEq as _;
use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock, Semaphore, broadcast};

pub(crate) use id_core::json_unique::parse_json_without_duplicate_keys;
use crate::directory_auth::Signed;
use crate::time::unix_ms;
use crate::world::{
Expand All @@ -39,6 +38,7 @@ use crate::world_compile::Compiler;
#[cfg(feature = "sandbox")]
use crate::world_compile::{COMPILE_TIMEOUT, CompileSpec};
use crate::world_hub::{WorldHub, WorldLease};
pub(crate) use id_core::json_unique::parse_json_without_duplicate_keys;

/// Bound the extra presentation latency while coalescing view-only redraws.
const VIEW_COALESCE_WINDOW: Duration = Duration::from_millis(5);
Expand Down Expand Up @@ -874,7 +874,6 @@ pub(crate) fn frame_admin_token(frame: &ClientFrame) -> Option<&str> {
}
}


/// Run one session to completion.
///
/// The first frame names the world (`"world": "<name>"`, default world if
Expand Down
14 changes: 9 additions & 5 deletions pkgs/id/tests/worlds_default_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
//! sends a string (ServerFrame::Worlds), so only a scripted peer can
//! produce the malformed shapes.
use id::frames::{read_frame, write_frame};
use id::world_net::{WorldClient, WORLD_ALPN};
use id::world_net::{WORLD_ALPN, WorldClient};
use iroh::{
endpoint::{presets, RelayMode},
protocol::{AcceptError, ProtocolHandler, Router},
Endpoint, EndpointAddr,
endpoint::{RelayMode, presets},
protocol::{AcceptError, ProtocolHandler, Router},
};

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -43,7 +43,9 @@ async fn endpoint() -> Endpoint {
.unwrap()
}

async fn run_case(reply: serde_json::Value) -> anyhow::Result<(String, Vec<(String, bool, usize)>)> {
async fn run_case(
reply: serde_json::Value,
) -> anyhow::Result<(String, Vec<(String, bool, usize)>)> {
let server_ep = endpoint().await;
let router = Router::builder(server_ep.clone())
.accept(WORLD_ALPN, ScriptedHost { reply })
Expand Down Expand Up @@ -91,7 +93,9 @@ async fn worlds_reply_default_must_be_a_string() {
// Shape is what the parser judges, not the name's content.
let mut reply = worlds_reply();
reply["default"] = serde_json::json!("");
let (default, _) = run_case(reply).await.expect("empty-string default must succeed");
let (default, _) = run_case(reply)
.await
.expect("empty-string default must succeed");
assert_eq!(default, "");

// Missing or mistyped defaults are malformed replies: refused with
Expand Down
Loading