Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

test(storage): cover host stream and cdylib watch paths

Steven Enamakele58d3421b609
diff --git a/crates/openhuman-core/src/modules/storage_host_cdylib_stream_tests.rs b/crates/openhuman-core/src/modules/storage_host_cdylib_stream_tests.rs
new file mode 100644
index 0000000000..e9030fb874
--- /dev/null
+++ b/crates/openhuman-core/src/modules/storage_host_cdylib_stream_tests.rs
@@ -0,0 +1,263 @@
+//! Streamed blobs and watch signals against a REAL loaded module (#7786).
+
+use super::*;
+
+const MIB: u64 = 1024 * 1024;
+
+impl Rig {
+ /// One of the probe's own members.
+ async fn member(&self, member: &str, args: impl serde::Serialize) -> Value {
+ self.probe
+ .call(member, args)
+ .await
+ .expect("the probe answers")
+ }
+
+ fn peer_proxy(&self, n: usize, object: &str) -> Proxy {
+ self.peers[n]
+ .proxy(
+ STORAGE_INTERFACE,
+ format!("/ai/tinyhumans/tinystorage/{object}"),
+ STORAGE_INTERFACE,
+ )
+ .unwrap()
+ .with_timeout(std::time::Duration::from_secs(10))
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_blob_over_the_bus_frame_round_trips_through_a_peer_bound_stream() {
+ let _turn = TURN.lock().await;
+ let rig = rig("tinyjuice").await;
+ // 20 MiB: over the 16 MiB frame no inline call could carry.
+ let len = 20 * MIB;
+ let stored = rig
+ .member("StreamPut", ("tinyjuice_ccr/streamed", len))
+ .await;
+ assert_eq!(stored["ok"]["len"], len, "{stored}");
+ // It is in the module's own scope, byte for byte.
+ let handle = rig.backend.for_scope(&rig.scope("tinyjuice")).unwrap();
+ let meta = handle
+ .blobs()
+ .head("tinyjuice_ccr/streamed")
+ .await
+ .unwrap()
+ .expect("the streamed blob is stored");
+ assert_eq!(meta.len, len);
+ let bytes = handle
+ .blobs()
+ .get_range("tinyjuice_ccr/streamed", 0..1024)
+ .await
+ .unwrap()
+ .expect("range");
+ assert!(bytes.iter().all(|byte| *byte == 0xAB));
+ // And it comes back whole by `GetStream`.
+ let read = rig.member("StreamGet", ("tinyjuice_ccr/streamed",)).await;
+ assert_eq!(read["ok"]["len"], len, "{read}");
+ assert_eq!(read["ok"]["meta_len"], len, "{read}");
+ assert_eq!(read["ok"]["all_fill"], true, "{read}");
+ // A key that is not there is `null`, not an error.
+ let missing = rig.member("StreamGet", ("tinyjuice_ccr/absent",)).await;
+ assert!(missing["ok"].is_null() && missing.get("ok").is_some(), "{missing}");
+ let trail = rig.trail.0.lock().unwrap().clone();
+ assert!(trail
+ .iter()
+ .any(|r| r.op == "PutStream" && r.outcome == "ok" && r.module == "tinyjuice"));
+ assert!(trail
+ .iter()
+ .any(|r| r.op == "GetStream" && r.outcome == "ok" && r.module == "tinyjuice"));
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_streamed_blob_is_still_bound_by_the_grant_and_the_length() {
+ let _turn = TURN.lock().await;
+ let rig = rig("tinyjuice").await;
+ // Outside the CCR prefix: refused before anything is stored.
+ let outside = rig.member("StreamPut", ("tinyjuice_other/x", 2 * MIB)).await;
+ assert!(outside.get("err").is_some(), "{outside}");
+ let handle = rig.backend.for_scope(&rig.scope("tinyjuice")).unwrap();
+ assert!(handle.blobs().head("tinyjuice_other/x").await.unwrap().is_none());
+ let denied_get = rig.member("StreamGet", ("tinyjuice_other/x",)).await;
+ assert!(
+ denied_get["err"].to_string().contains("target-not-granted"),
+ "{denied_get}"
+ );
+ // The module keeps working after a refusal.
+ let after = rig.member("StreamPut", ("tinyjuice_ccr/after", 3 * MIB)).await;
+ assert_eq!(after["ok"]["len"], 3 * MIB, "{after}");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn an_inline_blob_no_frame_can_carry_fails_fast_instead_of_hanging() {
+ let _turn = TURN.lock().await;
+ let rig = rig("tinyjuice").await;
+ // 5 000 000 bytes as a JSON array of numbers (`255,` each) is a 20 MB
+ // frame, over the 16 MiB cap.
+ let started = std::time::Instant::now();
+ let big: Value = rig
+ .member("PutBlob", ("tinyjuice_ccr/over-frame", 5_000_000usize))
+ .await;
+ assert!(big.get("err").is_some(), "an oversized frame must fail: {big}");
+ assert!(
+ started.elapsed() < std::time::Duration::from_secs(60),
+ "took {:?}",
+ started.elapsed()
+ );
+ let handle = rig.backend.for_scope(&rig.scope("tinyjuice")).unwrap();
+ assert!(handle
+ .blobs()
+ .head("tinyjuice_ccr/over-frame")
+ .await
+ .unwrap()
+ .is_none());
+ let after: Value = rig.member("PutBlob", ("tinyjuice_ccr/after", 2048usize)).await;
+ assert!(after.get("ok").is_some(), "the module keeps working: {after}");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_watch_signal_reaches_the_module_that_opened_the_watch() {
+ let _turn = TURN.lock().await;
+ let rig = rig("tinymcp").await;
+ let seen = rig.member("WatchPut", ("mcp_servers", "watched")).await;
+ assert_eq!(seen["ok"], "invalidated", "{seen}");
+ // A collection the grant never declared cannot be watched.
+ let refused = rig
+ .call(
+ "Documents",
+ "WatchOpen",
+ json!({"collection": "never_declared", "filter": {"op": "all"}, "interval_ms": 50}),
+ )
+ .await;
+ assert!(denied(&refused, "target-not-granted"), "{refused}");
+ let trail = rig.trail.0.lock().unwrap().clone();
+ assert!(trail
+ .iter()
+ .any(|r| r.op == "WatchOpen" && r.outcome == "ok" && r.module == "tinymcp"));
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_second_module_cannot_receive_the_first_modules_watch_signals() {
+ let _turn = TURN.lock().await;
+ // The probe stands for tinymcp; peer 0 stands for tinychannels, which also
+ // holds documents.
+ let rig = rig_with_peers("tinymcp", &["tinychannels"]).await;
+ let theirs = declared("tinychannels").unwrap().collections[0].name.clone();
+ // The second module listens to every watch signal the host sends anyone
+ // (any path), and opens a watch of its own as a positive control.
+ let mut everything = rig.peers[0]
+ .add_match(
+ tinybus::MatchRule::new()
+ .signals()
+ .interface(tinybus::InterfaceName::new(STORAGE_INTERFACE).unwrap()),
+ )
+ .await
+ .unwrap();
+ let documents = rig.peer_proxy(0, "Documents");
+ let own: Value = documents
+ .call(
+ "WatchOpen",
+ (json!({"collection": theirs, "filter": {"op": "all"}, "interval_ms": 50}),),
+ )
+ .await
+ .unwrap();
+ let own_id = own["watch_id"].as_str().unwrap().to_string();
+ // The first module opens a watch and changes its document.
+ let first = rig.member("WatchPut", ("mcp_servers", "w1")).await;
+ assert_eq!(first["ok"], "invalidated", "{first}");
+ // The second module's own change reaches the second module.
+ let _: Value = documents
+ .call(
+ "Put",
+ (put(&theirs, "d", &json!({"v": 1})),),
+ )
+ .await
+ .unwrap();
+ let mut ids = Vec::new();
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ while std::time::Instant::now() < deadline && !ids.contains(&own_id) {
+ if let Ok(Ok(message)) =
+ tokio::time::timeout(std::time::Duration::from_millis(200), everything.recv()).await
+ {
+ ids.push(message.body[0]["watch_id"].as_str().unwrap().to_string());
+ }
+ }
+ assert!(ids.contains(&own_id), "its own signal never arrived: {ids:?}");
+ // Nothing else did: the first module's watch id is not among them.
+ assert!(
+ ids.iter().all(|id| *id == own_id),
+ "a signal for another module's watch leaked: {ids:?}"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_second_module_cannot_read_or_take_the_first_modules_streams() {
+ let _turn = TURN.lock().await;
+ // The probe and peer 0 both stand for tinyjuice (same grant, same scope),
+ // so only the peer binding keeps the second out; peer 1 stands for tinymcp,
+ // which has no blobs at all.
+ let rig = rig_with_peers("tinyjuice", &["tinyjuice", "tinymcp"]).await;
+ let stored = rig
+ .member("StreamPut", ("tinyjuice_ccr/private", 2 * MIB))
+ .await;
+ assert_eq!(stored["ok"]["len"], 2 * MIB, "{stored}");
+
+ // A module without blob rights is refused outright.
+ let nosy: tinybus::Result<Value> = rig
+ .peer_proxy(1, "Blobs")
+ .call("GetStream", (json!({"key": "tinyjuice_ccr/private"}),))
+ .await;
+ match nosy {
+ Err(tinybus::Error::MethodFailed { name, message }) => {
+ assert_eq!(name, "ai.tinyhumans.tinystorage.Error.Denied");
+ assert_eq!(message, "object-not-granted");
+ }
+ other => panic!("expected a refusal, got {other:?}"),
+ }
+
+ // Taking a stream the probe opened toward the host: the peer is granted
+ // the key, but the host reads an upload only from the peer that opened it.
+ let opened = rig.member("OpenStream", (MIB,)).await;
+ let reference: tinybus::StreamRef = serde_json::from_value(opened["ok"].clone())
+ .unwrap_or_else(|_| panic!("a stream reference: {opened}"));
+ let hijack: tinybus::Result<Value> = rig
+ .peer_proxy(0, "Blobs")
+ .call(
+ "PutStream",
+ (json!({"key": "tinyjuice_ccr/hijacked", "len": MIB}), reference),
+ )
+ .await;
+ assert!(hijack.is_err(), "a peer took another peer's stream: {hijack:?}");
+ let handle = rig.backend.for_scope(&rig.scope("tinyjuice")).unwrap();
+ assert!(handle
+ .blobs()
+ .head("tinyjuice_ccr/hijacked")
+ .await
+ .unwrap()
+ .is_none());
+ // The refused attempt did not spend the stream: its owner still uses it.
+ let used = rig.member("UseStream", ("tinyjuice_ccr/owned", MIB)).await;
+ assert!(used.get("ok").is_some(), "the owner lost its stream: {used}");
+ assert_eq!(
+ handle
+ .blobs()
+ .head("tinyjuice_ccr/owned")
+ .await
+ .unwrap()
+ .expect("stored by the owner")
+ .len,
+ MIB
+ );
+
+ // A download the host opened toward the probe is not readable by a peer.
+ let reply = rig
+ .member("RawGetStream", ("tinyjuice_ccr/private",))
+ .await;
+ let download: tinybus::StreamRef = serde_json::from_value(reply["ok"][1].clone())
+ .unwrap_or_else(|_| panic!("a download reference: {reply}"));
+ assert!(
+ rig.peers[0]
+ .accept_stream_from(&download, &rig.host)
+ .is_err(),
+ "a peer accepted a stream opened toward another peer"
+ );
+}
diff --git a/crates/openhuman-core/src/modules/storage_host_cdylib_tests.rs b/crates/openhuman-core/src/modules/storage_host_cdylib_tests.rs
index 17a92fd66a..2dbe243dd2 100644
--- a/crates/openhuman-core/src/modules/storage_host_cdylib_tests.rs
+++ b/crates/openhuman-core/src/modules/storage_host_cdylib_tests.rs
@@ -20,7 +20,6 @@
//! * a second module can neither read the first module's blobs nor take the
//! stream the first opened.
-use super::*;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
@@ -587,266 +586,6 @@ async fn a_blob_over_the_inline_cap_is_refused_and_stores_nothing() {
assert!(denied(&outside, "target-not-granted"), "{outside}");
}
-const MIB: u64 = 1024 * 1024;
-
-impl Rig {
- /// One of the probe's own members.
- async fn member(&self, member: &str, args: impl serde::Serialize) -> Value {
- self.probe
- .call(member, args)
- .await
- .expect("the probe answers")
- }
-
- fn peer_proxy(&self, n: usize, object: &str) -> Proxy {
- self.peers[n]
- .proxy(
- STORAGE_INTERFACE,
- format!("/ai/tinyhumans/tinystorage/{object}"),
- STORAGE_INTERFACE,
- )
- .unwrap()
- .with_timeout(std::time::Duration::from_secs(10))
- }
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn a_blob_over_the_bus_frame_round_trips_through_a_peer_bound_stream() {
- let _turn = TURN.lock().await;
- let rig = rig("tinyjuice").await;
- // 20 MiB: over the 16 MiB frame no inline call could carry.
- let len = 20 * MIB;
- let stored = rig
- .member("StreamPut", ("tinyjuice_ccr/streamed", len))
- .await;
- assert_eq!(stored["ok"]["len"], len, "{stored}");
- // It is in the module's own scope, byte for byte.
- let handle = rig.backend.for_scope(&rig.scope("tinyjuice")).unwrap();
- let meta = handle
- .blobs()
- .head("tinyjuice_ccr/streamed")
- .await
- .unwrap()
- .expect("the streamed blob is stored");
- assert_eq!(meta.len, len);
- let bytes = handle
- .blobs()
- .get_range("tinyjuice_ccr/streamed", 0..1024)
- .await
- .unwrap()
- .expect("range");
- assert!(bytes.iter().all(|byte| *byte == 0xAB));
- // And it comes back whole by `GetStream`.
- let read = rig.member("StreamGet", ("tinyjuice_ccr/streamed",)).await;
- assert_eq!(read["ok"]["len"], len, "{read}");
- assert_eq!(read["ok"]["meta_len"], len, "{read}");
- assert_eq!(read["ok"]["all_fill"], true, "{read}");
- // A key that is not there is `null`, not an error.
- let missing = rig.member("StreamGet", ("tinyjuice_ccr/absent",)).await;
- assert!(missing["ok"].is_null() && missing.get("ok").is_some(), "{missing}");
- let trail = rig.trail.0.lock().unwrap().clone();
- assert!(trail
- .iter()
- .any(|r| r.op == "PutStream" && r.outcome == "ok" && r.module == "tinyjuice"));
- assert!(trail
- .iter()
- .any(|r| r.op == "GetStream" && r.outcome == "ok" && r.module == "tinyjuice"));
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn a_streamed_blob_is_still_bound_by_the_grant_and_the_length() {
- let _turn = TURN.lock().await;
- let rig = rig("tinyjuice").await;
- // Outside the CCR prefix: refused before anything is stored.
- let outside = rig.member("StreamPut", ("tinyjuice_other/x", 2 * MIB)).await;
- assert!(outside.get("err").is_some(), "{outside}");
- let handle = rig.backend.for_scope(&rig.scope("tinyjuice")).unwrap();
- assert!(handle.blobs().head("tinyjuice_other/x").await.unwrap().is_none());
- let denied_get = rig.member("StreamGet", ("tinyjuice_other/x",)).await;
- assert!(
- denied_get["err"].to_string().contains("target-not-granted"),
- "{denied_get}"
- );
- // The module keeps working after a refusal.
- let after = rig.member("StreamPut", ("tinyjuice_ccr/after", 3 * MIB)).await;
- assert_eq!(after["ok"]["len"], 3 * MIB, "{after}");
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn an_inline_blob_no_frame_can_carry_fails_fast_instead_of_hanging() {
- let _turn = TURN.lock().await;
- let rig = rig("tinyjuice").await;
- // 5 000 000 bytes as a JSON array of numbers (`255,` each) is a 20 MB
- // frame, over the 16 MiB cap.
- let started = std::time::Instant::now();
- let big: Value = rig
- .member("PutBlob", ("tinyjuice_ccr/over-frame", 5_000_000usize))
- .await;
- assert!(big.get("err").is_some(), "an oversized frame must fail: {big}");
- assert!(
- started.elapsed() < std::time::Duration::from_secs(60),
- "took {:?}",
- started.elapsed()
- );
- let handle = rig.backend.for_scope(&rig.scope("tinyjuice")).unwrap();
- assert!(handle
- .blobs()
- .head("tinyjuice_ccr/over-frame")
- .await
- .unwrap()
- .is_none());
- let after: Value = rig.member("PutBlob", ("tinyjuice_ccr/after", 2048usize)).await;
- assert!(after.get("ok").is_some(), "the module keeps working: {after}");
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn a_watch_signal_reaches_the_module_that_opened_the_watch() {
- let _turn = TURN.lock().await;
- let rig = rig("tinymcp").await;
- let seen = rig.member("WatchPut", ("mcp_servers", "watched")).await;
- assert_eq!(seen["ok"], "invalidated", "{seen}");
- // A collection the grant never declared cannot be watched.
- let refused = rig
- .call(
- "Documents",
- "WatchOpen",
- json!({"collection": "never_declared", "filter": {"op": "all"}, "interval_ms": 50}),
- )
- .await;
- assert!(denied(&refused, "target-not-granted"), "{refused}");
- let trail = rig.trail.0.lock().unwrap().clone();
- assert!(trail
- .iter()
- .any(|r| r.op == "WatchOpen" && r.outcome == "ok" && r.module == "tinymcp"));
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn a_second_module_cannot_receive_the_first_modules_watch_signals() {
- let _turn = TURN.lock().await;
- // The probe stands for tinymcp; peer 0 stands for tinychannels, which also
- // holds documents.
- let rig = rig_with_peers("tinymcp", &["tinychannels"]).await;
- let theirs = declared("tinychannels").unwrap().collections[0].name.clone();
- // The second module listens to every watch signal the host sends anyone
- // (any path), and opens a watch of its own as a positive control.
- let mut everything = rig.peers[0]
- .add_match(
- tinybus::MatchRule::new()
- .signals()
- .interface(tinybus::InterfaceName::new(STORAGE_INTERFACE).unwrap()),
- )
- .await
- .unwrap();
- let documents = rig.peer_proxy(0, "Documents");
- let own: Value = documents
- .call(
- "WatchOpen",
- (json!({"collection": theirs, "filter": {"op": "all"}, "interval_ms": 50}),),
- )
- .await
- .unwrap();
- let own_id = own["watch_id"].as_str().unwrap().to_string();
- // The first module opens a watch and changes its document.
- let first = rig.member("WatchPut", ("mcp_servers", "w1")).await;
- assert_eq!(first["ok"], "invalidated", "{first}");
- // The second module's own change reaches the second module.
- let _: Value = documents
- .call(
- "Put",
- (put(&theirs, "d", &json!({"v": 1})),),
- )
- .await
- .unwrap();
- let mut ids = Vec::new();
- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
- while std::time::Instant::now() < deadline && !ids.contains(&own_id) {
- if let Ok(Ok(message)) =
- tokio::time::timeout(std::time::Duration::from_millis(200), everything.recv()).await
- {
- ids.push(message.body[0]["watch_id"].as_str().unwrap().to_string());
- }
- }
- assert!(ids.contains(&own_id), "its own signal never arrived: {ids:?}");
- // Nothing else did: the first module's watch id is not among them.
- assert!(
- ids.iter().all(|id| *id == own_id),
- "a signal for another module's watch leaked: {ids:?}"
- );
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn a_second_module_cannot_read_or_take_the_first_modules_streams() {
- let _turn = TURN.lock().await;
- // The probe and peer 0 both stand for tinyjuice (same grant, same scope),
- // so only the peer binding keeps the second out; peer 1 stands for tinymcp,
- // which has no blobs at all.
- let rig = rig_with_peers("tinyjuice", &["tinyjuice", "tinymcp"]).await;
- let stored = rig
- .member("StreamPut", ("tinyjuice_ccr/private", 2 * MIB))
- .await;
- assert_eq!(stored["ok"]["len"], 2 * MIB, "{stored}");
-
- // A module without blob rights is refused outright.
- let nosy: tinybus::Result<Value> = rig
- .peer_proxy(1, "Blobs")
- .call("GetStream", (json!({"key": "tinyjuice_ccr/private"}),))
- .await;
- match nosy {
- Err(tinybus::Error::MethodFailed { name, message }) => {
- assert_eq!(name, "ai.tinyhumans.tinystorage.Error.Denied");
- assert_eq!(message, "object-not-granted");
- }
- other => panic!("expected a refusal, got {other:?}"),
- }
-
- // Taking a stream the probe opened toward the host: the peer is granted
- // the key, but the host reads an upload only from the peer that opened it.
- let opened = rig.member("OpenStream", (MIB,)).await;
- let reference: tinybus::StreamRef = serde_json::from_value(opened["ok"].clone())
- .unwrap_or_else(|_| panic!("a stream reference: {opened}"));
- let hijack: tinybus::Result<Value> = rig
- .peer_proxy(0, "Blobs")
- .call(
- "PutStream",
- (json!({"key": "tinyjuice_ccr/hijacked", "len": MIB}), reference),
- )
- .await;
- assert!(hijack.is_err(), "a peer took another peer's stream: {hijack:?}");
- let handle = rig.backend.for_scope(&rig.scope("tinyjuice")).unwrap();
- assert!(handle
- .blobs()
- .head("tinyjuice_ccr/hijacked")
- .await
- .unwrap()
- .is_none());
- // The refused attempt did not spend the stream: its owner still uses it.
- let used = rig.member("UseStream", ("tinyjuice_ccr/owned", MIB)).await;
- assert!(used.get("ok").is_some(), "the owner lost its stream: {used}");
- assert_eq!(
- handle
- .blobs()
- .head("tinyjuice_ccr/owned")
- .await
- .unwrap()
- .expect("stored by the owner")
- .len,
- MIB
- );
-
- // A download the host opened toward the probe is not readable by a peer.
- let reply = rig
- .member("RawGetStream", ("tinyjuice_ccr/private",))
- .await;
- let download: tinybus::StreamRef = serde_json::from_value(reply["ok"][1].clone())
- .unwrap_or_else(|_| panic!("a download reference: {reply}"));
- assert!(
- rig.peers[0]
- .accept_stream_from(&download, &rig.host)
- .is_err(),
- "a peer accepted a stream opened toward another peer"
- );
-}
-
#[tokio::test(flavor = "multi_thread")]
async fn every_call_is_audited_under_the_module_id_without_a_payload() {
let _turn = TURN.lock().await;
@@ -875,3 +614,6 @@ async fn every_call_is_audited_under_the_module_id_without_a_payload() {
.any(|record| record.outcome == "target-not-granted"));
assert!(!format!("{trail:?}").contains("PAYLOAD-MARKER"));
}
+
+#[path = "storage_host_cdylib_stream_tests.rs"]
+mod streams;
diff --git a/crates/openhuman-core/src/modules/storage_host_stream_tests.rs b/crates/openhuman-core/src/modules/storage_host_stream_tests.rs
new file mode 100644
index 0000000000..67e6940695
--- /dev/null
+++ b/crates/openhuman-core/src/modules/storage_host_stream_tests.rs
@@ -0,0 +1,170 @@
+//! Streamed blobs and watch signals, decided by the host without a bus.
+
+use super::*;
+
+fn blob_body(bytes: Vec<u8>) -> BlobReader {
+ Box::pin(std::io::Cursor::new(bytes))
+}
+
+fn head(key: &str, len: u64) -> PutBlobStreamRequest {
+ serde_json::from_value(json!({"key": key, "len": len})).unwrap()
+}
+
+#[tokio::test]
+async fn a_streamed_blob_is_stored_in_the_callers_scope_and_read_back() {
+ let rig = rig();
+ let bytes = vec![7u8; 3 * 1024 * 1024];
+ let stored = rig
+ .host
+ .put_blob_stream(
+ Some(&alpha()),
+ head("files/big", bytes.len() as u64),
+ blob_body(bytes.clone()),
+ )
+ .await
+ .unwrap();
+ assert_eq!(stored["len"], bytes.len());
+ let (meta, mut reader) = rig
+ .host
+ .get_blob_stream(
+ Some(&alpha()),
+ serde_json::from_value(json!({"key": "files/big"})).unwrap(),
+ )
+ .await
+ .unwrap()
+ .expect("the blob is there");
+ assert_eq!(meta.meta.len, bytes.len() as u64);
+ let mut read = Vec::new();
+ tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut read)
+ .await
+ .unwrap();
+ assert_eq!(read, bytes);
+ // Another module never sees it, even by the same key.
+ let other = rig
+ .host
+ .get_blob_stream(
+ Some(&beta()),
+ serde_json::from_value(json!({"key": "files/big"})).unwrap(),
+ )
+ .await
+ .unwrap();
+ assert!(other.is_none());
+ let trail = rig.trail.0.lock().unwrap().clone();
+ assert!(trail
+ .iter()
+ .any(|r| r.op == "PutStream" && r.outcome == "ok" && r.module == "alpha"));
+}
+
+#[tokio::test]
+async fn a_streamed_blob_is_decided_like_any_other_call() {
+ let rig = rig();
+ let put = |sender: Option<BusName>, key: &'static str, len: u64| {
+ let host = &rig.host;
+ async move {
+ host.put_blob_stream(sender.as_ref(), head(key, len), blob_body(vec![1; 4]))
+ .await
+ }
+ };
+ assert_eq!(
+ put(None, "files/a", 4).await,
+ Err(HostError::Denied("unauthenticated-caller"))
+ );
+ assert_eq!(
+ put(Some(stranger()), "files/a", 4).await,
+ Err(HostError::Denied("unknown-caller"))
+ );
+ assert_eq!(
+ put(Some(alpha()), "elsewhere/a", 4).await,
+ Err(HostError::Denied("target-not-granted"))
+ );
+ assert_eq!(
+ put(Some(alpha()), "files/a", MAX_STREAMED_BLOB_BYTES + 1).await,
+ Err(HostError::Denied("blob-too-large"))
+ );
+ let missing = rig
+ .host
+ .get_blob_stream(
+ Some(&alpha()),
+ serde_json::from_value(json!({"key": "elsewhere/a"})).unwrap(),
+ )
+ .await;
+ assert!(matches!(missing, Err(HostError::Denied("target-not-granted"))));
+ // Nothing was stored by any of the refusals.
+ let scope = rig.env.module_scope("alpha").unwrap();
+ assert!(rig
+ .backend
+ .for_scope(&scope)
+ .unwrap()
+ .blobs()
+ .head("files/a")
+ .await
+ .unwrap()
+ .is_none());
+}
+
+#[tokio::test]
+async fn a_read_only_grant_cannot_stream_a_blob_in() {
+ let mut read_only = grant("notes");
+ read_only.writable = false;
+ let rig = rig_with("alpha", read_only);
+ let refused = rig
+ .host
+ .put_blob_stream(Some(&alpha()), head("files/a", 4), blob_body(vec![1; 4]))
+ .await;
+ assert_eq!(refused, Err(HostError::Denied("read-only-grant")));
+}
+
+#[tokio::test]
+async fn a_watch_signal_reaches_only_the_callers_own_relay() {
+ let rig = rig();
+ // The bus endpoint asks for each caller's signals before its first
+ // `WatchOpen` reaches the host.
+ let mut alpha_signals = rig.host.watch_signals(&alpha()).unwrap();
+ let mut beta_signals = rig.host.watch_signals(&beta()).unwrap();
+ let opened = call(
+ &rig,
+ &alpha(),
+ Object::Documents,
+ "WatchOpen",
+ json!({"collection": "notes", "filter": {"op": "all"}, "interval_ms": 20}),
+ )
+ .await
+ .unwrap();
+ let watch_id = opened["watch_id"].as_str().unwrap().to_string();
+ // Bind beta too, so a leak could only come from the host's routing.
+ call(&rig, &beta(), Object::Documents, "Collections", json!({}))
+ .await
+ .unwrap();
+ call(
+ &rig,
+ &alpha(),
+ Object::Documents,
+ "Put",
+ put("notes", "a", json!({"v": 1})),
+ )
+ .await
+ .unwrap();
+ let signal = tokio::time::timeout(std::time::Duration::from_secs(5), alpha_signals.recv())
+ .await
+ .expect("a signal arrives")
+ .unwrap();
+ assert_eq!(signal.watch_id, watch_id);
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(200), beta_signals.recv())
+ .await
+ .is_err(),
+ "another module's relay must stay silent"
+ );
+ // A collection outside the grant cannot be watched.
+ assert_eq!(
+ call(
+ &rig,
+ &alpha(),
+ Object::Documents,
+ "WatchOpen",
+ json!({"collection": "other", "filter": {"op": "all"}, "interval_ms": 20}),
+ )
+ .await,
+ denied("target-not-granted")
+ );
+}
diff --git a/crates/openhuman-core/src/modules/storage_host_tests.rs b/crates/openhuman-core/src/modules/storage_host_tests.rs
index ecd794bd10..3f2249461a 100644
--- a/crates/openhuman-core/src/modules/storage_host_tests.rs
+++ b/crates/openhuman-core/src/modules/storage_host_tests.rs
@@ -539,173 +539,6 @@ async fn streams_and_blobs_stay_inside_their_prefixes() {
);
}
-fn blob_body(bytes: Vec<u8>) -> BlobReader {
- Box::pin(std::io::Cursor::new(bytes))
-}
-
-fn head(key: &str, len: u64) -> PutBlobStreamRequest {
- serde_json::from_value(json!({"key": key, "len": len})).unwrap()
-}
-
-#[tokio::test]
-async fn a_streamed_blob_is_stored_in_the_callers_scope_and_read_back() {
- let rig = rig();
- let bytes = vec![7u8; 3 * 1024 * 1024];
- let stored = rig
- .host
- .put_blob_stream(
- Some(&alpha()),
- head("files/big", bytes.len() as u64),
- blob_body(bytes.clone()),
- )
- .await
- .unwrap();
- assert_eq!(stored["len"], bytes.len());
- let (meta, mut reader) = rig
- .host
- .get_blob_stream(
- Some(&alpha()),
- serde_json::from_value(json!({"key": "files/big"})).unwrap(),
- )
- .await
- .unwrap()
- .expect("the blob is there");
- assert_eq!(meta.meta.len, bytes.len() as u64);
- let mut read = Vec::new();
- tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut read)
- .await
- .unwrap();
- assert_eq!(read, bytes);
- // Another module never sees it, even by the same key.
- let other = rig
- .host
- .get_blob_stream(
- Some(&beta()),
- serde_json::from_value(json!({"key": "files/big"})).unwrap(),
- )
- .await
- .unwrap();
- assert!(other.is_none());
- let trail = rig.trail.0.lock().unwrap().clone();
- assert!(trail
- .iter()
- .any(|r| r.op == "PutStream" && r.outcome == "ok" && r.module == "alpha"));
-}
-
-#[tokio::test]
-async fn a_streamed_blob_is_decided_like_any_other_call() {
- let rig = rig();
- let put = |sender: Option<BusName>, key: &'static str, len: u64| {
- let host = &rig.host;
- async move {
- host.put_blob_stream(sender.as_ref(), head(key, len), blob_body(vec![1; 4]))
- .await
- }
- };
- assert_eq!(
- put(None, "files/a", 4).await,
- Err(HostError::Denied("unauthenticated-caller"))
- );
- assert_eq!(
- put(Some(stranger()), "files/a", 4).await,
- Err(HostError::Denied("unknown-caller"))
- );
- assert_eq!(
- put(Some(alpha()), "elsewhere/a", 4).await,
- Err(HostError::Denied("target-not-granted"))
- );
- assert_eq!(
- put(Some(alpha()), "files/a", MAX_STREAMED_BLOB_BYTES + 1).await,
- Err(HostError::Denied("blob-too-large"))
- );
- let missing = rig
- .host
- .get_blob_stream(
- Some(&alpha()),
- serde_json::from_value(json!({"key": "elsewhere/a"})).unwrap(),
- )
- .await;
- assert!(matches!(missing, Err(HostError::Denied("target-not-granted"))));
- // Nothing was stored by any of the refusals.
- let scope = rig.env.module_scope("alpha").unwrap();
- assert!(rig
- .backend
- .for_scope(&scope)
- .unwrap()
- .blobs()
- .head("files/a")
- .await
- .unwrap()
- .is_none());
-}
-
-#[tokio::test]
-async fn a_read_only_grant_cannot_stream_a_blob_in() {
- let mut read_only = grant("notes");
- read_only.writable = false;
- let rig = rig_with("alpha", read_only);
- let refused = rig
- .host
- .put_blob_stream(Some(&alpha()), head("files/a", 4), blob_body(vec![1; 4]))
- .await;
- assert_eq!(refused, Err(HostError::Denied("read-only-grant")));
-}
-
-#[tokio::test]
-async fn a_watch_signal_reaches_only_the_callers_own_relay() {
- let rig = rig();
- // The bus endpoint asks for each caller's signals before its first
- // `WatchOpen` reaches the host.
- let mut alpha_signals = rig.host.watch_signals(&alpha()).unwrap();
- let mut beta_signals = rig.host.watch_signals(&beta()).unwrap();
- let opened = call(
- &rig,
- &alpha(),
- Object::Documents,
- "WatchOpen",
- json!({"collection": "notes", "filter": {"op": "all"}, "interval_ms": 20}),
- )
- .await
- .unwrap();
- let watch_id = opened["watch_id"].as_str().unwrap().to_string();
- // Bind beta too, so a leak could only come from the host's routing.
- call(&rig, &beta(), Object::Documents, "Collections", json!({}))
- .await
- .unwrap();
- call(
- &rig,
- &alpha(),
- Object::Documents,
- "Put",
- put("notes", "a", json!({"v": 1})),
- )
- .await
- .unwrap();
- let signal = tokio::time::timeout(std::time::Duration::from_secs(5), alpha_signals.recv())
- .await
- .expect("a signal arrives")
- .unwrap();
- assert_eq!(signal.watch_id, watch_id);
- assert!(
- tokio::time::timeout(std::time::Duration::from_millis(200), beta_signals.recv())
- .await
- .is_err(),
- "another module's relay must stay silent"
- );
- // A collection outside the grant cannot be watched.
- assert_eq!(
- call(
- &rig,
- &alpha(),
- Object::Documents,
- "WatchOpen",
- json!({"collection": "other", "filter": {"op": "all"}, "interval_ms": 20}),
- )
- .await,
- denied("target-not-granted")
- );
-}
-
#[tokio::test]
async fn secrets_need_a_confidential_caller_and_a_granted_prefix() {
let rig = rig();
@@ -867,6 +700,9 @@ mod bus;
#[path = "storage_host_cdylib_tests.rs"]
mod cdylib;
+#[cfg(test)]
+#[path = "storage_host_stream_tests.rs"]
+mod streams;
async fn set_secret(rig: &Rig) -> Result<Value, HostError> {
let who = alpha();
diff --git a/crates/openhuman-core/src/modules/storage_host_watching.rs b/crates/openhuman-core/src/modules/storage_host_watching.rs
index 474b6dcbf9..be7c9fe02e 100644
--- a/crates/openhuman-core/src/modules/storage_host_watching.rs
+++ b/crates/openhuman-core/src/modules/storage_host_watching.rs
@@ -78,13 +78,11 @@ struct Feed(broadcast::Receiver<()>);
#[async_trait]
impl DocumentWatch for Feed {
async fn next(&mut self) -> Result<Option<WatchNotice>> {
- loop {
- match self.0.recv().await {
- Ok(()) | Err(broadcast::error::RecvError::Lagged(_)) => {
- return Ok(Some(WatchNotice::Invalidated { cursor: None }));
- }
- Err(broadcast::error::RecvError::Closed) => return Ok(None),
+ match self.0.recv().await {
+ Ok(()) | Err(broadcast::error::RecvError::Lagged(_)) => {
+ Ok(Some(WatchNotice::Invalidated { cursor: None }))
}
+ Err(broadcast::error::RecvError::Closed) => Ok(None),
}
}
}