Skip to content
Open
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
47 changes: 45 additions & 2 deletions crates/tinybus/src/module/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ struct LoadedModule {
descriptor_info: Option<DescriptorInfo>,
lifecycle_busy: bool,
callback_config: Option<[u8; 32]>,
/// Top-level configuration keys the stored callback fingerprint covers.
/// Empty means the fingerprint covers the whole configuration blob,
/// which is the historical behaviour for bindings that declare no keys.
callback_config_keys: Vec<String>,
// Keep operation accounting after routing revocation removes the binding.
callback_state: Option<Arc<callbacks::CallbackState>>,
// Keep the owning capability alive for as long as this admitted module can
Expand Down Expand Up @@ -140,6 +144,37 @@ fn callback_config_fingerprint(bytes: &[u8]) -> [u8; 32] {
hash.finalize().into()
}

/// Fingerprint only the declared callback-bearing keys of a configuration.
///
/// With no keys declared the whole blob is fingerprinted, which is the
/// historical behaviour. Keys are top-level only: the callback destination
/// lives at the top of the module configuration, and anything deeper is the
/// module's own state rather than the host's scope. A declared key that is
/// absent from the configuration contributes nothing, so adding it later
/// counts as a change and a frozen destination cannot be smuggled in by
/// introducing the key. Only key names are retained by the caller; values
/// are hashed, never stored.
fn scoped_callback_config_fingerprint(
bytes: &[u8],
config: &serde_json::Value,
keys: &[String],
) -> [u8; 32] {
if keys.is_empty() {
return callback_config_fingerprint(bytes);
}
let mut scoped = serde_json::Map::new();
if let Some(object) = config.as_object() {
for key in keys {
if let Some(value) = object.get(key) {
scoped.insert(key.clone(), value.clone());
}
}
}
let bytes = serde_json::to_vec(&serde_json::Value::Object(scoped))
.expect("scoped configuration serializes");
callback_config_fingerprint(&bytes)
}

enum PendingModule {
Loaded(Box<LoadedArtifact>),
Lazy(Box<ModuleManifest>),
Expand Down Expand Up @@ -1821,6 +1856,7 @@ impl ModuleHost {
descriptor_info,
lifecycle_busy: false,
callback_config: None,
callback_config_keys: Vec::new(),
callback_state: None,
_callback_binding: None,
});
Expand Down Expand Up @@ -2198,14 +2234,20 @@ impl ModuleControl for ModuleHostInner {
serde_json::to_vec(&config)
.map_err(|_| Error::failed("module configuration is invalid"))?,
);
drop(config);
let fingerprint = callback_config_fingerprint(bytes.expose_secret());
let transport = {
let mut loaded = self.loaded.lock().expect("module list lock");
let module = loaded
.iter_mut()
.find(|module| module.info.name == name)
.ok_or_else(|| Error::failed("module is not loaded"))?;
// The fingerprint covers only the keys the binding declared as
// callback-bearing. The configuration is dropped after this
// block, so no plaintext survives past the comparison.
let fingerprint = scoped_callback_config_fingerprint(
bytes.expose_secret(),
&config,
&module.callback_config_keys,
);
let state = module.snapshot().state;
if module
.callback_config
Expand Down Expand Up @@ -2233,6 +2275,7 @@ impl ModuleControl for ModuleHostInner {
module.lifecycle_busy = true;
module.transport.clone()
};
drop(config);
let _lifecycle_busy = LifecycleBusyGuard::for_reinitialize(self, name);
let reinitialized = transport.reinitialize(bytes).await;
let mut loaded = self.loaded.lock().expect("module list lock");
Expand Down
36 changes: 34 additions & 2 deletions crates/tinybus/src/module/host_callbacks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,10 @@ pub struct HostCallbackBinding {
connection: Connection,
state: Arc<CallbackState>,
transport: Arc<MemoryTransport>,
// Top-level configuration keys whose values are callback-bearing and
// stay frozen across reinitialization. Empty means the whole
// configuration blob is frozen, which is the historical behaviour.
frozen_config_keys: Vec<String>,
// Bounded test observers only; neither hook supplies production authority.
#[cfg(test)]
after_attach: Mutex<Option<Box<dyn FnOnce() + Send>>>,
Expand Down Expand Up @@ -414,6 +418,24 @@ impl HostCallbackBinding {
&self.state.destination
}

/// Freeze only these top-level configuration keys across
/// reinitialization, so a callback-bound module can take a
/// non-callback configuration update.
///
/// The declared keys are the callback-bearing ones, such as the
/// destination the caller supplies in the module configuration; any
/// other key may change freely. With no keys declared the whole
/// configuration blob stays frozen, which is the historical behaviour.
pub fn with_frozen_config_keys(mut self, keys: &[&str]) -> Self {
self.frozen_config_keys = keys.iter().map(|key| key.to_string()).collect();
self
}

/// The top-level configuration keys frozen across reinitialization.
pub(crate) fn frozen_config_keys(&self) -> &[String] {
&self.frozen_config_keys
}

/// Accept a stream opened by this binding's currently authorized module.
///
/// The raw connection remains private. The callback context supplies the
Expand Down Expand Up @@ -623,6 +645,7 @@ impl HostCallbackBinding {
connection,
state: child,
transport,
frozen_config_keys: Vec::new(),
#[cfg(test)]
after_attach: Mutex::new(None),
#[cfg(test)]
Expand Down Expand Up @@ -1093,6 +1116,7 @@ impl ModuleHost {
broker: self.inner.broker.clone(),
connection,
transport,
frozen_config_keys: Vec::new(),
#[cfg(test)]
after_attach: Mutex::new(None),
#[cfg(test)]
Expand Down Expand Up @@ -1129,7 +1153,9 @@ impl ModuleHost {
/// Load a hash-verified file and bind its exact peer before any initialization.
///
/// All endpoints must already be served. The binding is single-use even on
/// failure. Configuration is frozen for reinitialization. Generic load APIs
/// failure. Configuration is frozen for reinitialization: by default the
/// whole blob, or only the keys declared with
/// [`HostCallbackBinding::with_frozen_config_keys`]. Generic load APIs
/// grant no callback authority. The caller supplies the binding's unique
/// destination in its domain-specific configuration; it cannot change scope.
pub async fn load_file_with_host_callbacks(
Expand Down Expand Up @@ -1324,7 +1350,12 @@ impl ModuleHost {
// deferred even for an eager module until routes and identity exist.
let bytes = serde_json::to_vec(&config)
.map_err(|_| Error::failed("module configuration is invalid"))?;
let fingerprint = callback_config_fingerprint(&bytes);
// Only the keys the binding declared as callback-bearing are
// frozen; the rest of the configuration may change on
// reinitialization. The configuration is dropped below, so no
// plaintext survives past this fingerprint.
let fingerprint =
scoped_callback_config_fingerprint(&bytes, &config, binding.frozen_config_keys());
drop(config);
let trusted_host = self.inner.broker.restricted_module_controller_binding();
let pre_ready_routes = self
Expand Down Expand Up @@ -1405,6 +1436,7 @@ impl ModuleHost {
state.active = true;
}
module.callback_config = Some(fingerprint);
module.callback_config_keys = binding.frozen_config_keys().to_vec();
module.callback_state = Some(binding.state.clone());
self.inner
.broker
Expand Down
38 changes: 38 additions & 0 deletions crates/tinybus/src/module/host_callbacks_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1351,6 +1351,44 @@ fn configuration_fingerprints_preserve_json_equality_without_normalizing_strings
);
}

#[test]
fn scoped_configuration_fingerprints_cover_only_the_declared_keys() {
fn fingerprint(value: &serde_json::Value, keys: &[String]) -> [u8; 32] {
let bytes = serde_json::to_vec(value).unwrap();
scoped_callback_config_fingerprint(&bytes, value, keys)
}
let keys = vec!["host".to_string()];
let base = serde_json::json!({
"host": ":1.42",
"credential": "private-test-secret",
"nested": [{"zero": -0.0}],
});
let mut changed_credential = base.clone();
changed_credential["credential"] = serde_json::json!("rotated-test-secret");
let mut changed_nested = base.clone();
changed_nested["nested"][0]["zero"] = serde_json::json!(0.0);
let mut changed_host = base.clone();
changed_host["host"] = serde_json::json!(":1.999");
let mut dropped_host = base.clone();
dropped_host.as_object_mut().unwrap().remove("host");
assert_eq!(
fingerprint(&base, &keys),
fingerprint(&changed_credential, &keys)
);
assert_eq!(
fingerprint(&base, &keys),
fingerprint(&changed_nested, &keys)
);
assert_ne!(fingerprint(&base, &keys), fingerprint(&changed_host, &keys));
assert_ne!(fingerprint(&base, &keys), fingerprint(&dropped_host, &keys));
// With no keys declared the whole blob is covered, as before.
let no_keys: Vec<String> = Vec::new();
assert_ne!(
fingerprint(&base, &no_keys),
fingerprint(&changed_credential, &no_keys)
);
}

// Private fixture-only release ownership. Drop never joins or asserts.
struct ControlledRelease {
barrier: Arc<super::super::super::transport::tests::NativeBarrier>,
Expand Down
69 changes: 69 additions & 0 deletions crates/tinybus/src/module/host_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3437,6 +3437,75 @@ async fn eager_native_setup_callbacks_are_bound_before_ready_and_failures_rollba
}
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires TINYBUS_TEST_HOST_CALLBACK_MODULE to point at the built cdylib"]
async fn frozen_config_keys_allow_non_callback_config_changes_on_reinitialize() {
let artifact = PathBuf::from(std::env::var_os("TINYBUS_TEST_HOST_CALLBACK_MODULE").unwrap());
let hash = crate::module::hash::file_hex(std::fs::File::open(&artifact).unwrap()).unwrap();
let (_dir, artifact) = staged_module(&artifact, &hash);
let broker = Broker::new();
let modules = ModuleHost::new(broker.clone());
let binding = modules
.prepare_host_callbacks(vec![crate::module::HostCallbackEndpoint {
path: "/callback".parse().unwrap(),
interface: "org.example.Callback".parse().unwrap(),
members: vec!["Observe".parse().unwrap()],
}])
.await
.unwrap()
.with_frozen_config_keys(&["host"]);
let calls = Arc::new(AtomicUsize::new(0));
let guard = binding.guard();
let sender_lookup = modules.sender_lookup();
binding
.serve_at(
"/callback".parse().unwrap(),
BoundNativeCallback {
calls: calls.clone(),
guard: guard.clone(),
sender_lookup,
},
)
.await
.unwrap();
let config = serde_json::json!({
"host": binding.unique_name(), "fail": false,
"credential": "callback-secret-must-not-be-retained",
"nested": [{"zero": -0.0, "literal": "\"-0.0\""}],
});
let info = modules
.load_file_with_host_callbacks(artifact, config.clone(), &binding)
.await
.unwrap();
assert!(matches!(info.state, ModuleState::Ready));
assert_eq!(calls.load(Ordering::SeqCst), 1);
// A non-callback field may change freely.
let mut rotated = config.clone();
rotated["credential"] = serde_json::json!("rotated-test-secret");
modules.reinitialize(&info.name, rotated).await.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 2);
let mut literal = config.clone();
literal["nested"][0]["literal"] = serde_json::json!("\"0.0\"");
modules.reinitialize(&info.name, literal).await.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 3);
// The frozen callback destination may not change, and dropping it
// counts as a change.
let mut moved = config.clone();
moved["host"] = serde_json::json!(":1.999");
assert!(modules.reinitialize(&info.name, moved).await.is_err());
let mut dropped = config.clone();
dropped.as_object_mut().unwrap().remove("host");
assert!(modules.reinitialize(&info.name, dropped).await.is_err());
assert_eq!(calls.load(Ordering::SeqCst), 3);
// An equivalent configuration still reinitializes.
let mut equivalent = config.clone();
equivalent["nested"][0]["zero"] = serde_json::json!(0.0);
modules.reinitialize(&info.name, equivalent).await.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 4);
modules.reinitialize(&info.name, config).await.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 5);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires TINYBUS_TEST_HOST_CALLBACK_MODULE to point at the built cdylib"]
async fn an_eager_setup_callback_resolves_its_admitted_module_before_ready() {
Expand Down
Loading