Skip to content

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

feat(storage): add host-side storage grant enforcement

Steven Enamakel7330582666df
diff --git a/crates/openhuman-core/src/modules/storage_grants.rs b/crates/openhuman-core/src/modules/storage_grants.rs
index 7e7a226f61..4288756138 100644
--- a/crates/openhuman-core/src/modules/storage_grants.rs
+++ b/crates/openhuman-core/src/modules/storage_grants.rs
@@ -86,6 +86,9 @@ pub(crate) enum Plan {
target: String,
/// How to trim the reply.
filter: ReplyFilter,
+ /// Whether the call mutates storage, so the host fence is consulted
+ /// before it goes to the backend.
+ write: bool,
},
/// Answer without calling the backend (the host already ran it).
Answer(Value),
@@ -198,6 +201,7 @@ fn forward(target: impl Into<String>) -> Plan {
Plan::Forward {
target: target.into(),
filter: ReplyFilter::None,
+ write: false,
}
}
@@ -219,12 +223,39 @@ pub(crate) fn authorize(
if !grant.has_object(object) {
return Err(Denied::Object);
}
- match object {
+ let write = is_write(object, selector);
+ if write {
+ writes(grant)?;
+ }
+ let plan = match object {
Object::Documents => documents(grant, selector, request),
Object::Streams => streams(grant, selector, request),
Object::Blobs => blobs(grant, selector, request),
Object::Secrets => secrets(grant, selector, request),
- }
+ }?;
+ Ok(match plan {
+ Plan::Forward { target, filter, .. } => Plan::Forward {
+ target,
+ filter,
+ write,
+ },
+ answered @ Plan::Answer(_) => answered,
+ })
+}
+
+/// Whether `selector` mutates storage.
+fn is_write(object: Object, selector: &str) -> bool {
+ matches!(
+ (object, selector),
+ (
+ Object::Documents,
+ "Put" | "Delete" | "DeleteWhere" | "Claim" | "AtomicBatch" | "AtomicBatchChecked"
+ ) | (
+ Object::Streams,
+ "Append" | "AppendBatch" | "AppendBatchIfOffset" | "TruncateBefore" | "DeleteStream"
+ ) | (Object::Blobs, "Put" | "Delete" | "PresignPut")
+ | (Object::Secrets, "Set" | "Delete")
+ )
}
fn writes(grant: &StorageGrant) -> Result<(), Denied> {
@@ -243,15 +274,11 @@ fn documents(grant: &StorageGrant, selector: &str, request: &Value) -> Result<Pl
Ok(forward(collection))
}
"Put" | "Delete" | "DeleteWhere" | "Claim" => {
- writes(grant)?;
let collection = text(request, "collection")?;
grant.collection(collection)?;
Ok(forward(collection))
}
- "AtomicBatch" | "AtomicBatchChecked" => {
- writes(grant)?;
- batch(grant, request)
- }
+ "AtomicBatch" | "AtomicBatchChecked" => batch(grant, request),
"EnsureCollection" | "ValidateCollectionSpec" => {
// The host ran `ensure_collection` from the declared spec when it
// bound this module. Repeating it is harmless; changing it is not
@@ -275,6 +302,7 @@ fn documents(grant: &StorageGrant, selector: &str, request: &Value) -> Result<Pl
Ok(Plan::Forward {
target: String::new(),
filter: ReplyFilter::GrantedCollections,
+ write: false,
})
}
// Watches are projected to bus signals, which this host does not
@@ -312,7 +340,6 @@ fn streams(grant: &StorageGrant, selector: &str, request: &Value) -> Result<Plan
Ok(forward(name))
}
"Append" | "AppendBatch" | "AppendBatchIfOffset" | "TruncateBefore" | "DeleteStream" => {
- writes(grant)?;
let name = text(request, "stream")?;
StorageGrant::prefixed(&grant.stream_prefixes, name)?;
Ok(forward(name))
@@ -338,7 +365,6 @@ fn blobs(grant: &StorageGrant, selector: &str, request: &Value) -> Result<Plan,
Ok(forward(granted))
}
"Put" | "Delete" | "PresignPut" => {
- writes(grant)?;
let key = text(request, "key")?;
let granted = StorageGrant::prefixed(&grant.blob_prefixes, key)?;
Ok(forward(granted))
@@ -361,7 +387,6 @@ fn secrets(grant: &StorageGrant, selector: &str, request: &Value) -> Result<Plan
Ok(forward(granted))
}
"Set" | "Delete" => {
- writes(grant)?;
let granted =
StorageGrant::prefixed(&grant.secret_prefixes, text(request, "name")?)?;
Ok(forward(granted))
diff --git a/crates/openhuman-core/src/modules/storage_grants_tests.rs b/crates/openhuman-core/src/modules/storage_grants_tests.rs
index 6d2a122bd7..7614da2c15 100644
--- a/crates/openhuman-core/src/modules/storage_grants_tests.rs
+++ b/crates/openhuman-core/src/modules/storage_grants_tests.rs
@@ -155,7 +155,7 @@ fn streams_blobs_and_secrets_are_confined_to_their_prefixes() {
let g = grant();
assert_eq!(
forwarded(authorize(&g, Object::Streams, "Append", &json!({"stream": "log/a"}))),
- "log/"
+ "log/a"
);
assert_eq!(
authorize(&g, Object::Streams, "Append", &json!({"stream": "audit/a"})),
@@ -272,3 +272,21 @@ fn no_module_declares_storage_yet() {
assert!(declared(record.id).is_none(), "{}", record.id);
}
}
+
+#[test]
+fn only_mutating_selectors_ask_for_the_write_fence() {
+ let g = grant();
+ let write_flag = |object, selector: &str, request: Value| match authorize(&g, object, selector, &request) {
+ Ok(Plan::Forward { write, .. }) => write,
+ other => panic!("{selector}: {other:?}"),
+ };
+ assert!(write_flag(Object::Documents, "Put", json!({"collection": "notes"})));
+ assert!(write_flag(Object::Documents, "AtomicBatch", json!({"ops": []})));
+ assert!(write_flag(Object::Streams, "Append", json!({"stream": "log/a"})));
+ assert!(write_flag(Object::Blobs, "Put", json!({"key": "files/a"})));
+ assert!(write_flag(Object::Secrets, "Set", json!({"name": "token.a"})));
+ assert!(!write_flag(Object::Documents, "Get", json!({"collection": "notes"})));
+ assert!(!write_flag(Object::Documents, "Query", json!({"collection": "notes"})));
+ assert!(!write_flag(Object::Streams, "ReadWindow", json!({"stream": "log/a"})));
+ assert!(!write_flag(Object::Blobs, "Get", json!({"key": "files/a"})));
+}
diff --git a/crates/openhuman-core/src/modules/storage_host.rs b/crates/openhuman-core/src/modules/storage_host.rs
index d51f3a8a6b..ad855d8634 100644
--- a/crates/openhuman-core/src/modules/storage_host.rs
+++ b/crates/openhuman-core/src/modules/storage_host.rs
@@ -64,6 +64,7 @@ pub(crate) trait CallerDirectory: Send + Sync {
}
/// What the host decides from, separated so tests can supply their own.
+#[async_trait]
pub(crate) trait Environment: Send + Sync {
/// The installed backend, if the host configured one.
fn backend(&self) -> Option<Arc<dyn StorageBackend>>;
@@ -74,6 +75,10 @@ pub(crate) trait Environment: Send + Sync {
fn grant(&self, module_id: &str) -> Option<StorageGrant>;
/// The key provider for module secrets.
fn keys(&self) -> Result<Arc<dyn KeyProvider>, StorageError>;
+ /// Consults the host's write fence for `scope` before a write is forwarded
+ /// (the backend checks it again). A refusal means the lease behind the
+ /// scope is gone.
+ async fn admit_write(&self, scope: &Scope) -> Result<(), StorageError>;
}
/// One line of the audit trail. Carries no payload by construction.
@@ -263,6 +268,7 @@ impl StorageHost {
return Err(HostError::Denied("no-scope"));
}
};
+ let binding_scope = scope.clone();
let binding = match self.bind(&module, scope).await {
Ok(binding) => binding,
Err(error) => {
@@ -282,7 +288,22 @@ impl StorageHost {
audit("", "answered-by-host");
Ok(reply)
}
- Plan::Forward { target, filter } => {
+ Plan::Forward {
+ target,
+ filter,
+ write,
+ } => {
+ if write {
+ if let Err(refused) = self.environment.admit_write(&binding_scope).await {
+ let kind = if crate::storage::fence::fence_error(&refused).is_some() {
+ StorageKind::Fenced
+ } else {
+ StorageKind::Backend
+ };
+ audit(&target, "fenced");
+ return Err(failure(kind));
+ }
+ }
match binding
.server
.handle(admission, object.as_str(), selector, request)
@@ -475,6 +496,7 @@ impl CallerDirectory for Live {
}
}
+#[async_trait]
impl Environment for Live {
fn backend(&self) -> Option<Arc<dyn StorageBackend>> {
crate::storage::installed()
@@ -496,6 +518,12 @@ impl Environment for Live {
fn keys(&self) -> Result<Arc<dyn KeyProvider>, StorageError> {
crate::storage::secrets::keys()
}
+
+ async fn admit_write(&self, scope: &Scope) -> Result<(), StorageError> {
+ crate::storage::fence::registry()
+ .guard(scope.as_str(), "module-write")
+ .await
+ }
}
pub(super) async fn install(connection: &tinybus::Connection) -> tinybus::Result<()> {