use super::name::{ChannelHash, ChannelId, ChannelName};
use crate::adapter::net::behavior::capability::{CapabilityFilter, CapabilitySet};
use crate::adapter::net::identity::{EntityId, RevocationRegistry, TokenChain, TokenScope};
use crate::adapter::net::mesh_rpc::ServeError;
use dashmap::DashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OriginBinding {
OriginHashHex16,
}
impl OriginBinding {
pub fn authorizes(
self,
name: &str,
matched_prefix: Option<&str>,
pinned_origin: Option<u64>,
) -> bool {
let Some(origin_hash) = pinned_origin else {
return false;
};
self.matches(name, matched_prefix, origin_hash)
}
pub fn matches(self, name: &str, matched_prefix: Option<&str>, origin_hash: u64) -> bool {
let Some(prefix) = matched_prefix else {
return false;
};
let Some(suffix) = name.strip_prefix(prefix) else {
return false;
};
match self {
Self::OriginHashHex16 => suffix == format!("{origin_hash:016x}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum QueueGroupPolicy {
#[default]
Unrestricted,
Deny,
TokenBound,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Visibility {
SubnetLocal,
ParentVisible,
Exported,
#[default]
Global,
}
#[derive(Debug, Clone)]
pub struct ChannelConfig {
pub channel_id: ChannelId,
pub visibility: Visibility,
pub publish_caps: Option<CapabilityFilter>,
pub subscribe_caps: Option<CapabilityFilter>,
pub require_token: bool,
pub token_roots: Vec<EntityId>,
pub subscriber_origin_binding: Option<OriginBinding>,
pub queue_group_policy: QueueGroupPolicy,
pub priority: u8,
pub reliable: bool,
pub max_rate_pps: Option<u32>,
}
impl ChannelConfig {
pub fn new(channel_id: ChannelId) -> Self {
Self {
channel_id,
visibility: Visibility::default(),
publish_caps: None,
subscribe_caps: None,
require_token: false,
token_roots: Vec::new(),
subscriber_origin_binding: None,
queue_group_policy: QueueGroupPolicy::default(),
priority: 0,
reliable: false,
max_rate_pps: None,
}
}
pub fn with_visibility(mut self, visibility: Visibility) -> Self {
self.visibility = visibility;
self
}
pub fn with_publish_caps(mut self, filter: CapabilityFilter) -> Self {
self.publish_caps = Some(filter);
self
}
pub fn with_subscribe_caps(mut self, filter: CapabilityFilter) -> Self {
self.subscribe_caps = Some(filter);
self
}
pub fn with_require_token(mut self, require: bool) -> Self {
self.require_token = require;
self
}
pub fn with_token_roots(mut self, roots: Vec<EntityId>) -> Self {
self.require_token = true;
self.token_roots = roots;
self
}
pub fn token_required(&self) -> bool {
self.require_token || !self.token_roots.is_empty()
}
pub fn with_subscriber_origin_binding(mut self, binding: OriginBinding) -> Self {
self.subscriber_origin_binding = Some(binding);
self
}
pub fn caps_allow_subscribe(&self, node_caps: &CapabilitySet) -> bool {
match self.subscribe_caps {
Some(ref filter) => filter.matches(node_caps),
None => true,
}
}
pub fn with_queue_group_policy(mut self, policy: QueueGroupPolicy) -> Self {
self.queue_group_policy = policy;
self
}
pub fn can_join_queue_group(
&self,
entity_id: &EntityId,
channel: &str,
group: &str,
chain: Option<&TokenChain>,
revocation: &RevocationRegistry,
skew_secs: u64,
) -> bool {
match self.queue_group_policy {
QueueGroupPolicy::Unrestricted => true,
QueueGroupPolicy::Deny => false,
QueueGroupPolicy::TokenBound => {
if self.token_roots.is_empty() {
return false;
}
let Some(chain) = chain else {
return false;
};
chain
.verify_authorizes(
TokenScope::SUBSCRIBE,
super::name::queue_group_hash(channel, group),
entity_id,
&self.token_roots,
revocation,
skew_secs,
)
.is_ok()
}
}
}
pub fn with_priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
pub fn with_reliable(mut self, reliable: bool) -> Self {
self.reliable = reliable;
self
}
pub fn with_rate_limit(mut self, pps: u32) -> Self {
self.max_rate_pps = Some(pps);
self
}
pub fn can_publish(
&self,
node_caps: &CapabilitySet,
entity_id: &EntityId,
channel_hash: ChannelHash,
chain: Option<&TokenChain>,
revocation: &RevocationRegistry,
skew_secs: u64,
) -> bool {
if let Some(ref filter) = self.publish_caps {
if !filter.matches(node_caps) {
return false;
}
}
self.token_gate(
TokenScope::PUBLISH,
entity_id,
channel_hash,
chain,
revocation,
skew_secs,
)
}
pub fn can_subscribe(
&self,
node_caps: &CapabilitySet,
entity_id: &EntityId,
channel_hash: ChannelHash,
chain: Option<&TokenChain>,
revocation: &RevocationRegistry,
skew_secs: u64,
) -> bool {
if let Some(ref filter) = self.subscribe_caps {
if !filter.matches(node_caps) {
return false;
}
}
self.token_gate(
TokenScope::SUBSCRIBE,
entity_id,
channel_hash,
chain,
revocation,
skew_secs,
)
}
fn token_gate(
&self,
action: TokenScope,
entity_id: &EntityId,
channel_hash: ChannelHash,
chain: Option<&TokenChain>,
revocation: &RevocationRegistry,
skew_secs: u64,
) -> bool {
if !self.token_required() {
return true;
}
if self.token_roots.is_empty() {
return false;
}
let Some(chain) = chain else {
return false;
};
chain
.verify_authorizes(
action,
channel_hash,
entity_id,
&self.token_roots,
revocation,
skew_secs,
)
.is_ok()
}
pub fn reverify_subscribe(
&self,
chain: &TokenChain,
entity_id: &EntityId,
channel_hash: ChannelHash,
revocation: &RevocationRegistry,
skew_secs: u64,
) -> bool {
chain
.verify_authorizes(
TokenScope::SUBSCRIBE,
channel_hash,
entity_id,
&self.token_roots,
revocation,
skew_secs,
)
.is_ok()
}
pub fn reverify_subscribe_presigned(
&self,
chain: &TokenChain,
entity_id: &EntityId,
channel_hash: ChannelHash,
revocation: &RevocationRegistry,
skew_secs: u64,
) -> bool {
chain
.verify_authorizes_presigned(
TokenScope::SUBSCRIBE,
channel_hash,
entity_id,
&self.token_roots,
revocation,
skew_secs,
)
.is_ok()
}
}
#[derive(Debug, Clone)]
pub struct ResolvedConfig {
pub config: ChannelConfig,
pub matched_prefix: Option<String>,
}
fn note_if_visibility_only(config: &ChannelConfig) {
let scoped = matches!(
config.visibility,
Visibility::SubnetLocal | Visibility::ParentVisible
);
if scoped && !config.token_required() && config.subscriber_origin_binding.is_none() {
tracing::info!(
channel = config.channel_id.name().as_str(),
visibility = ?config.visibility,
"channel has subnet-scoped visibility but no token gate or \
origin binding: visibility is a propagation filter over \
peer-declared topology, not an access boundary. If this \
channel must exclude anyone, add `with_token_roots(...)`."
);
}
}
fn warn_if_fail_closed(config: &ChannelConfig, is_prefix: bool) {
if config.require_token && config.token_roots.is_empty() {
tracing::warn!(
channel = config.channel_id.name().as_str(),
"channel requires a token but has no token_roots: all publish \
and subscribe will be denied (fail closed). Use \
`with_token_roots(...)` to anchor a root of trust."
);
}
if is_prefix {
return;
}
if config.subscriber_origin_binding.is_some() {
tracing::warn!(
channel = config.channel_id.name().as_str(),
"channel has a subscriber_origin_binding but is registered by \
EXACT name: every subscribe will be denied (fail closed). The \
binding matches a dynamic suffix against the subscriber's own \
pinned origin, which only exists for a prefix registration — \
register it with `insert_prefix(...)` / \
`Mesh::register_channel_prefix(...)`."
);
}
}
pub struct ChannelConfigRegistry {
configs: DashMap<String, ChannelConfig>,
by_hash: DashMap<ChannelHash, Vec<String>>,
by_wire_hash: DashMap<u16, Vec<String>>,
prefix_configs: DashMap<String, ChannelConfig>,
write_lock: parking_lot::Mutex<()>,
}
impl ChannelConfigRegistry {
pub fn new() -> Self {
Self {
configs: DashMap::new(),
by_hash: DashMap::new(),
by_wire_hash: DashMap::new(),
prefix_configs: DashMap::new(),
write_lock: parking_lot::Mutex::new(()),
}
}
pub fn insert_prefix(&self, prefix: impl Into<String>, config: ChannelConfig) {
warn_if_fail_closed(&config, true);
note_if_visibility_only(&config);
self.prefix_configs.insert(prefix.into(), config);
}
pub fn insert_prefix_if_absent(
&self,
prefix: impl Into<String>,
config: ChannelConfig,
) -> bool {
let _w = self.write_lock.lock();
self.insert_prefix_if_absent_locked(prefix, config)
}
fn insert_prefix_if_absent_locked(
&self,
prefix: impl Into<String>,
config: ChannelConfig,
) -> bool {
match self.prefix_configs.entry(prefix.into()) {
dashmap::mapref::entry::Entry::Occupied(_) => false,
dashmap::mapref::entry::Entry::Vacant(slot) => {
warn_if_fail_closed(&config, true);
note_if_visibility_only(&config);
slot.insert(config);
true
}
}
}
pub fn remove_prefix(&self, prefix: &str) -> Option<ChannelConfig> {
self.prefix_configs.remove(prefix).map(|(_, v)| v)
}
pub fn install_rpc_service_defaults(&self, service: &str) -> Result<(), ServeError> {
let invalid = || ServeError::InvalidServiceName(service.to_string());
let Ok(req_channel) = ChannelName::new(&format!("{service}.requests")) else {
return Err(invalid());
};
if ChannelName::new(&format!("{service}.replies.{:016x}", 0u64)).is_err() {
return Err(invalid());
}
let Ok(sentinel) = ChannelName::new(&format!("{service}.replies.prefix")) else {
return Err(invalid());
};
let req_cfg = ChannelConfig::new(ChannelId::new(req_channel));
let reply_cfg = ChannelConfig::new(ChannelId::new(sentinel))
.with_subscriber_origin_binding(OriginBinding::OriginHashHex16);
let _w = self.write_lock.lock();
self.insert_prefix_if_absent_locked(format!("{service}.replies."), reply_cfg);
self.insert_if_absent_locked(req_cfg);
Ok(())
}
pub fn insert(&self, config: ChannelConfig) {
warn_if_fail_closed(&config, false);
note_if_visibility_only(&config);
let name = config.channel_id.name().to_string();
let hash = config.channel_id.hash();
let wire_hash = config.channel_id.wire_hash();
let _w = self.write_lock.lock();
self.configs.insert(name.clone(), config);
self.index_name(hash, wire_hash, name);
}
pub fn insert_if_absent(&self, config: ChannelConfig) -> bool {
let _w = self.write_lock.lock();
self.insert_if_absent_locked(config)
}
fn insert_if_absent_locked(&self, config: ChannelConfig) -> bool {
let name = config.channel_id.name().to_string();
let hash = config.channel_id.hash();
let wire_hash = config.channel_id.wire_hash();
let installed = match self.configs.entry(name.clone()) {
dashmap::mapref::entry::Entry::Occupied(_) => false,
dashmap::mapref::entry::Entry::Vacant(slot) => {
warn_if_fail_closed(&config, false);
note_if_visibility_only(&config);
slot.insert(config);
true
}
};
if installed {
self.index_name(hash, wire_hash, name);
}
installed
}
fn index_name(&self, hash: ChannelHash, wire_hash: u16, name: String) {
let mut by_hash = self.by_hash.entry(hash).or_default();
if !by_hash.iter().any(|n| n == &name) {
by_hash.push(name.clone());
}
drop(by_hash);
let mut by_wire = self.by_wire_hash.entry(wire_hash).or_default();
if !by_wire.iter().any(|n| n == &name) {
by_wire.push(name);
}
}
pub fn get(
&self,
channel_hash: ChannelHash,
) -> Option<dashmap::mapref::one::Ref<'_, String, ChannelConfig>> {
let names = self.by_hash.get(&channel_hash)?;
if names.len() != 1 {
return None;
}
let name = names.first()?;
self.configs.get(name)
}
pub fn get_by_wire_hash(
&self,
wire_hash: u16,
) -> Option<dashmap::mapref::one::Ref<'_, String, ChannelConfig>> {
let names = self.by_wire_hash.get(&wire_hash)?;
if names.len() != 1 {
return None;
}
let name = names.first()?;
self.configs.get(name)
}
pub fn get_by_name(
&self,
name: &str,
) -> Option<dashmap::mapref::one::Ref<'_, String, ChannelConfig>> {
if let Some(exact) = self.configs.get(name) {
return Some(exact);
}
self.prefix_configs
.get(&self.longest_matching_prefix(name)?)
}
fn longest_matching_prefix(&self, name: &str) -> Option<String> {
let mut best_len = 0usize;
let mut best_key: Option<String> = None;
for entry in self.prefix_configs.iter() {
let prefix = entry.key();
if name.starts_with(prefix) && prefix.len() >= best_len {
best_len = prefix.len();
best_key = Some(prefix.clone());
}
}
best_key
}
pub fn resolve_by_name(&self, name: &str) -> Option<ResolvedConfig> {
if let Some(exact) = self.configs.get(name) {
return Some(ResolvedConfig {
config: exact.clone(),
matched_prefix: None,
});
}
let key = self.longest_matching_prefix(name)?;
let config = self.prefix_configs.get(&key)?.clone();
Some(ResolvedConfig {
config,
matched_prefix: Some(key),
})
}
pub fn remove(&self, channel_hash: ChannelHash) -> Option<ChannelConfig> {
let _w = self.write_lock.lock();
let name = {
let names = self.by_hash.get(&channel_hash)?;
if names.len() != 1 {
return None;
}
names.first()?.clone()
};
self.remove_by_name_locked(&name)
}
pub fn remove_by_name(&self, name: &str) -> Option<ChannelConfig> {
let _w = self.write_lock.lock();
self.remove_by_name_locked(name)
}
fn remove_by_name_locked(&self, name: &str) -> Option<ChannelConfig> {
let (_, removed) = self.configs.remove(name)?;
let hash = removed.channel_id.hash();
let wire_hash = removed.channel_id.wire_hash();
if let Some(mut hash_names) = self.by_hash.get_mut(&hash) {
hash_names.retain(|n| n != name);
}
if let Some(mut wire_names) = self.by_wire_hash.get_mut(&wire_hash) {
wire_names.retain(|n| n != name);
}
Some(removed)
}
pub fn len(&self) -> usize {
self.configs.len()
}
pub fn is_empty(&self) -> bool {
self.configs.is_empty()
}
pub fn snapshot(&self) -> Vec<(String, ChannelConfig)> {
let mut out: Vec<(String, ChannelConfig)> = self
.configs
.iter()
.map(|e| (e.key().clone(), e.value().clone()))
.collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
pub fn snapshot_prefixes(&self) -> Vec<(String, ChannelConfig)> {
let mut out: Vec<(String, ChannelConfig)> = self
.prefix_configs
.iter()
.map(|e| (e.key().clone(), e.value().clone()))
.collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
#[inline]
pub fn priority(&self, channel_hash: ChannelHash) -> u8 {
self.get(channel_hash).map(|c| c.priority).unwrap_or(0)
}
}
impl Default for ChannelConfigRegistry {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for ChannelConfigRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChannelConfigRegistry")
.field("channels", &self.configs.len())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::adapter::net::behavior::capability::{GpuInfo, GpuVendor, HardwareCapabilities};
use crate::adapter::net::channel::{channel_hash, queue_group_hash, ChannelName};
use crate::adapter::net::identity::{EntityKeypair, PermissionToken};
fn make_caps(gpu: bool) -> CapabilitySet {
if gpu {
let gpu_info = GpuInfo {
vendor: GpuVendor::Nvidia,
model: "test".to_string(),
vram_gb: 8,
compute_units: 0,
tensor_cores: 0,
fp16_tflops_x10: 0,
};
CapabilitySet::new().with_hardware(HardwareCapabilities::new().with_gpu(gpu_info))
} else {
CapabilitySet::new()
}
}
fn direct_chain(
issuer: &EntityKeypair,
subject: &EntityKeypair,
scope: TokenScope,
channel_hash: ChannelHash,
) -> TokenChain {
TokenChain::single(PermissionToken::issue(
issuer,
subject.entity_id().clone(),
scope,
channel_hash,
3600,
0,
))
}
#[test]
fn test_open_channel() {
let id = ChannelId::parse("sensors/lidar").unwrap();
let config = ChannelConfig::new(id);
let caps = make_caps(false);
let entity = EntityKeypair::generate();
let rev = RevocationRegistry::new();
assert!(config.can_publish(
&caps,
entity.entity_id(),
config.channel_id.hash(),
None,
&rev,
0
));
assert!(config.can_subscribe(
&caps,
entity.entity_id(),
config.channel_id.hash(),
None,
&rev,
0
));
}
#[test]
fn test_capability_restricted_channel() {
let id = ChannelId::parse("compute/gpu-tasks").unwrap();
let config =
ChannelConfig::new(id).with_publish_caps(CapabilityFilter::new().require_gpu());
let entity = EntityKeypair::generate();
let rev = RevocationRegistry::new();
let no_gpu = make_caps(false);
assert!(!config.can_publish(
&no_gpu,
entity.entity_id(),
config.channel_id.hash(),
None,
&rev,
0
));
let with_gpu = make_caps(true);
assert!(config.can_publish(
&with_gpu,
entity.entity_id(),
config.channel_id.hash(),
None,
&rev,
0
));
}
#[test]
fn token_channel_rejects_self_issued_accepts_owner_issued() {
let id = ChannelId::parse("control/estop").unwrap();
let owner = EntityKeypair::generate();
let subject = EntityKeypair::generate();
let config =
ChannelConfig::new(id.clone()).with_token_roots(vec![owner.entity_id().clone()]);
let caps = make_caps(false);
let rev = RevocationRegistry::new();
assert!(!config.can_publish(
&caps,
subject.entity_id(),
config.channel_id.hash(),
None,
&rev,
0
));
let self_chain = direct_chain(&subject, &subject, TokenScope::PUBLISH, id.hash());
assert!(
!config.can_publish(
&caps,
subject.entity_id(),
config.channel_id.hash(),
Some(&self_chain),
&rev,
0
),
"self-issued token must be rejected: its issuer is not a channel root"
);
let owner_chain = direct_chain(&owner, &subject, TokenScope::PUBLISH, id.hash());
assert!(config.can_publish(
&caps,
subject.entity_id(),
config.channel_id.hash(),
Some(&owner_chain),
&rev,
0
));
}
#[test]
fn require_token_with_no_roots_fails_closed() {
let id = ChannelId::parse("control/locked").unwrap();
let config = ChannelConfig::new(id.clone()).with_require_token(true);
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let anyone = EntityKeypair::generate();
let chain = direct_chain(&anyone, &anyone, TokenScope::SUBSCRIBE, id.hash());
assert!(!config.can_subscribe(
&caps,
anyone.entity_id(),
config.channel_id.hash(),
Some(&chain),
&rev,
0
));
assert!(!config.can_subscribe(
&caps,
anyone.entity_id(),
config.channel_id.hash(),
None,
&rev,
0
));
}
#[test]
fn roots_without_require_token_flag_still_enforces() {
let id = ChannelId::parse("control/estop").unwrap();
let owner = EntityKeypair::generate();
let subject = EntityKeypair::generate();
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let mut config = ChannelConfig::new(id.clone());
config.token_roots = vec![owner.entity_id().clone()];
assert!(!config.require_token);
assert!(
config.token_required(),
"named roots must imply enforcement"
);
assert!(!config.can_subscribe(
&caps,
subject.entity_id(),
config.channel_id.hash(),
None,
&rev,
0
));
let owner_chain = direct_chain(&owner, &subject, TokenScope::SUBSCRIBE, id.hash());
assert!(config.can_subscribe(
&caps,
subject.entity_id(),
config.channel_id.hash(),
Some(&owner_chain),
&rev,
0
));
}
#[test]
fn leaf_subject_must_match_presenter() {
let id = ChannelId::parse("control/estop").unwrap();
let owner = EntityKeypair::generate();
let intended = EntityKeypair::generate();
let attacker = EntityKeypair::generate();
let config =
ChannelConfig::new(id.clone()).with_token_roots(vec![owner.entity_id().clone()]);
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let chain = direct_chain(&owner, &intended, TokenScope::SUBSCRIBE, id.hash());
assert!(!config.can_subscribe(
&caps,
attacker.entity_id(),
config.channel_id.hash(),
Some(&chain),
&rev,
0
));
assert!(config.can_subscribe(
&caps,
intended.entity_id(),
config.channel_id.hash(),
Some(&chain),
&rev,
0
));
}
#[test]
fn delegation_chain_accepted() {
let id = ChannelId::parse("fleet/telemetry").unwrap();
let owner = EntityKeypair::generate();
let mid = EntityKeypair::generate();
let leaf = EntityKeypair::generate();
let config =
ChannelConfig::new(id.clone()).with_token_roots(vec![owner.entity_id().clone()]);
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let root = PermissionToken::issue(
&owner,
mid.entity_id().clone(),
TokenScope::SUBSCRIBE.union(TokenScope::DELEGATE),
id.hash(),
3600,
2,
);
let child = root
.delegate(&mid, leaf.entity_id().clone(), TokenScope::SUBSCRIBE)
.expect("delegation should succeed");
let chain = TokenChain {
tokens: vec![root, child],
};
assert!(config.can_subscribe(
&caps,
leaf.entity_id(),
config.channel_id.hash(),
Some(&chain),
&rev,
0
));
}
#[test]
fn delegation_broken_continuity_rejected() {
let id = ChannelId::parse("fleet/telemetry").unwrap();
let owner = EntityKeypair::generate();
let mid = EntityKeypair::generate();
let rogue = EntityKeypair::generate();
let leaf = EntityKeypair::generate();
let config =
ChannelConfig::new(id.clone()).with_token_roots(vec![owner.entity_id().clone()]);
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let root = PermissionToken::issue(
&owner,
mid.entity_id().clone(),
TokenScope::SUBSCRIBE.union(TokenScope::DELEGATE),
id.hash(),
3600,
2,
);
let spliced = PermissionToken::issue(
&rogue,
leaf.entity_id().clone(),
TokenScope::SUBSCRIBE,
id.hash(),
3600,
0,
);
let chain = TokenChain {
tokens: vec![root, spliced],
};
assert!(!config.can_subscribe(
&caps,
leaf.entity_id(),
config.channel_id.hash(),
Some(&chain),
&rev,
0
));
}
#[test]
fn delegation_cannot_broaden_scope() {
let id = ChannelId::parse("fleet/telemetry").unwrap();
let owner = EntityKeypair::generate();
let mid = EntityKeypair::generate();
let leaf = EntityKeypair::generate();
let config =
ChannelConfig::new(id.clone()).with_token_roots(vec![owner.entity_id().clone()]);
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let root = PermissionToken::issue(
&owner,
mid.entity_id().clone(),
TokenScope::SUBSCRIBE.union(TokenScope::DELEGATE),
id.hash(),
3600,
2,
);
let forged_child = PermissionToken::issue(
&mid,
leaf.entity_id().clone(),
TokenScope::PUBLISH,
id.hash(),
3600,
0,
);
let chain = TokenChain {
tokens: vec![root, forged_child],
};
assert!(!config.can_publish(
&caps,
leaf.entity_id(),
config.channel_id.hash(),
Some(&chain),
&rev,
0
));
}
#[test]
fn root_revocation_kills_delegated_chain() {
let id = ChannelId::parse("fleet/telemetry").unwrap();
let owner = EntityKeypair::generate();
let mid = EntityKeypair::generate();
let leaf = EntityKeypair::generate();
let config =
ChannelConfig::new(id.clone()).with_token_roots(vec![owner.entity_id().clone()]);
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let root = PermissionToken::issue(
&owner,
mid.entity_id().clone(),
TokenScope::SUBSCRIBE.union(TokenScope::DELEGATE),
id.hash(),
3600,
2,
);
let child = root
.delegate(&mid, leaf.entity_id().clone(), TokenScope::SUBSCRIBE)
.expect("delegation should succeed");
let chain = TokenChain {
tokens: vec![root, child],
};
assert!(config.can_subscribe(
&caps,
leaf.entity_id(),
config.channel_id.hash(),
Some(&chain),
&rev,
0
));
rev.revoke_below(owner.entity_id(), 1);
assert!(
!config.can_subscribe(
&caps,
leaf.entity_id(),
config.channel_id.hash(),
Some(&chain),
&rev,
0
),
"revoking the root must kill the delegated descendant"
);
}
#[test]
fn test_caps_and_token_combined() {
let id = ChannelId::parse("compute/secure").unwrap();
let owner = EntityKeypair::generate();
let subject = EntityKeypair::generate();
let config = ChannelConfig::new(id.clone())
.with_publish_caps(CapabilityFilter::new().require_gpu())
.with_token_roots(vec![owner.entity_id().clone()]);
let rev = RevocationRegistry::new();
let owner_chain = direct_chain(&owner, &subject, TokenScope::PUBLISH, id.hash());
let with_gpu = make_caps(true);
assert!(!config.can_publish(
&with_gpu,
subject.entity_id(),
config.channel_id.hash(),
None,
&rev,
0
));
let no_gpu = make_caps(false);
assert!(!config.can_publish(
&no_gpu,
subject.entity_id(),
config.channel_id.hash(),
Some(&owner_chain),
&rev,
0
));
assert!(config.can_publish(
&with_gpu,
subject.entity_id(),
config.channel_id.hash(),
Some(&owner_chain),
&rev,
0
));
}
#[test]
fn test_config_registry() {
let reg = ChannelConfigRegistry::new();
let id = ChannelId::parse("sensors/lidar").unwrap();
let config = ChannelConfig::new(id.clone()).with_priority(5);
reg.insert(config);
assert_eq!(reg.len(), 1);
assert_eq!(reg.priority(id.hash()), 5);
let retrieved = reg.get(id.hash()).unwrap();
assert_eq!(retrieved.priority, 5);
}
#[test]
fn test_visibility_default() {
let id = ChannelId::parse("test").unwrap();
let config = ChannelConfig::new(id);
assert_eq!(config.visibility, Visibility::Global);
}
#[test]
fn snapshot_returns_sorted_exact_matches_excludes_prefixes() {
let reg = ChannelConfigRegistry::new();
let zeta = ChannelConfig::new(ChannelId::parse("zeta/c").unwrap())
.with_visibility(Visibility::SubnetLocal);
let alpha = ChannelConfig::new(ChannelId::parse("alpha/a").unwrap())
.with_visibility(Visibility::Global);
let middle = ChannelConfig::new(ChannelId::parse("middle/b").unwrap());
reg.insert(zeta);
reg.insert(alpha);
reg.insert(middle);
reg.insert_prefix(
"rpc.replies.",
ChannelConfig::new(ChannelId::parse("rpc.replies.").unwrap()),
);
let snap = reg.snapshot();
let names: Vec<&str> = snap.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, vec!["alpha/a", "middle/b", "zeta/c"]);
assert!(!names.contains(&"rpc.replies."));
let alpha_cfg = snap.iter().find(|(n, _)| n == "alpha/a").unwrap();
assert_eq!(alpha_cfg.1.visibility, Visibility::Global);
let zeta_cfg = snap.iter().find(|(n, _)| n == "zeta/c").unwrap();
assert_eq!(zeta_cfg.1.visibility, Visibility::SubnetLocal);
let prefixes = reg.snapshot_prefixes();
let prefix_names: Vec<&str> = prefixes.iter().map(|(p, _)| p.as_str()).collect();
assert_eq!(prefix_names, vec!["rpc.replies."]);
}
#[test]
fn test_regression_config_registry_hash_collision_no_overwrite() {
let reg = ChannelConfigRegistry::new();
let id1 = ChannelId::parse("channel/alpha").unwrap();
let id2 = ChannelId::parse("channel/beta").unwrap();
let config1 = ChannelConfig::new(id1.clone()).with_priority(1);
let config2 = ChannelConfig::new(id2.clone()).with_priority(2);
reg.insert(config1);
reg.insert(config2);
assert_eq!(reg.len(), 2, "both channels should exist in registry");
let c1 = reg.get_by_name("channel/alpha").unwrap();
assert_eq!(c1.priority, 1, "channel/alpha priority should be 1");
let c2 = reg.get_by_name("channel/beta").unwrap();
assert_eq!(c2.priority, 2, "channel/beta priority should be 2");
}
#[test]
fn test_regression_config_registry_get_returns_none_on_collision() {
use crate::adapter::net::channel::name::wire_channel_hash;
let mut seen = std::collections::HashMap::<u16, String>::new();
let (name1, name2) = loop {
let name = format!("ch-{}", seen.len());
let wire = wire_channel_hash(&name);
if let Some(existing) = seen.get(&wire) {
break (existing.clone(), name);
}
seen.insert(wire, name);
};
let reg = ChannelConfigRegistry::new();
let id1 = ChannelId::parse(&name1).unwrap();
let id2 = ChannelId::parse(&name2).unwrap();
assert_eq!(
id1.wire_hash(),
id2.wire_hash(),
"precondition: wire hashes must collide"
);
let config1 = ChannelConfig::new(id1.clone()).with_visibility(Visibility::SubnetLocal);
let config2 = ChannelConfig::new(id2.clone()).with_visibility(Visibility::Global);
reg.insert(config1);
reg.insert(config2);
assert!(
reg.get_by_wire_hash(id1.wire_hash()).is_none(),
"get_by_wire_hash() must return None when wire hashes collide between channels"
);
assert_eq!(
reg.get(id1.hash()).unwrap().visibility,
Visibility::SubnetLocal
);
assert_eq!(reg.get(id2.hash()).unwrap().visibility, Visibility::Global);
let c1 = reg.get_by_name(&name1).unwrap();
assert_eq!(c1.visibility, Visibility::SubnetLocal);
let c2 = reg.get_by_name(&name2).unwrap();
assert_eq!(c2.visibility, Visibility::Global);
}
#[test]
fn test_regression_remove_by_wire_hash_safe_on_wire_collision() {
use crate::adapter::net::channel::name::wire_channel_hash;
let mut seen = std::collections::HashMap::<u16, String>::new();
let (name1, name2) = loop {
let name = format!("rm-{}", seen.len());
let wire = wire_channel_hash(&name);
if let Some(existing) = seen.get(&wire) {
break (existing.clone(), name);
}
seen.insert(wire, name);
};
let reg = ChannelConfigRegistry::new();
let id1 = ChannelId::parse(&name1).unwrap();
let id2 = ChannelId::parse(&name2).unwrap();
assert_eq!(
id1.wire_hash(),
id2.wire_hash(),
"precondition: wire hashes must collide"
);
reg.insert(ChannelConfig::new(id1.clone()).with_visibility(Visibility::SubnetLocal));
reg.insert(ChannelConfig::new(id2.clone()).with_visibility(Visibility::Global));
let removed1 = reg.remove(id1.hash()).expect("remove canonical1");
assert_eq!(removed1.visibility, Visibility::SubnetLocal);
assert_eq!(reg.len(), 1, "the other config must still be present");
assert_eq!(
reg.get_by_name(&name2).unwrap().visibility,
Visibility::Global,
"name2 must be untouched by the canonical remove of name1"
);
let removed2 = reg.remove_by_name(&name2).unwrap();
assert_eq!(removed2.visibility, Visibility::Global);
assert_eq!(reg.len(), 0);
}
#[test]
fn prefix_resolution_picks_longest_match_deterministically() {
let reg = ChannelConfigRegistry::new();
reg.insert_prefix(
"foo.",
ChannelConfig::new(ChannelId::parse("foo.sentinel").unwrap()).with_priority(1),
);
reg.insert_prefix(
"foo.bar.",
ChannelConfig::new(ChannelId::parse("foo.bar.sentinel").unwrap()).with_priority(2),
);
reg.insert_prefix(
"foo.bar.baz.",
ChannelConfig::new(ChannelId::parse("foo.bar.baz.sentinel").unwrap()).with_priority(3),
);
let c = reg.get_by_name("foo.bar.baz.qux").unwrap();
assert_eq!(c.priority, 3, "longest matching prefix must win");
let c = reg.get_by_name("foo.bar.something").unwrap();
assert_eq!(c.priority, 2);
let c = reg.get_by_name("foo.something").unwrap();
assert_eq!(c.priority, 1);
assert!(reg.get_by_name("other.thing").is_none());
for _ in 0..100 {
assert_eq!(reg.get_by_name("foo.bar.baz.x").unwrap().priority, 3);
}
}
#[test]
fn test_remove_by_hash_works_when_unique() {
let reg = ChannelConfigRegistry::new();
let id = ChannelId::parse("sensors/only").unwrap();
let hash = id.hash();
reg.insert(ChannelConfig::new(id).with_priority(7));
let removed = reg.remove(hash).unwrap();
assert_eq!(removed.priority, 7);
assert_eq!(reg.len(), 0);
assert!(reg.get(hash).is_none());
}
#[test]
fn remove_racing_reregistration_leaves_the_index_consistent() {
let reg = ChannelConfigRegistry::new();
let id = ChannelId::parse("svc.requests").unwrap();
let hash = id.hash();
let wire = id.wire_hash();
reg.insert(ChannelConfig::new(id.clone()).with_priority(1));
reg.insert(ChannelConfig::new(id.clone()).with_priority(2));
reg.remove_by_name("svc.requests");
assert!(
reg.get(hash).is_none(),
"after a completed remove the channel is gone"
);
reg.insert(ChannelConfig::new(id).with_priority(3));
assert_eq!(
reg.get(hash).map(|c| c.priority),
Some(3),
"a channel re-registered after removal must be reachable by \
canonical hash"
);
assert_eq!(
reg.get_by_wire_hash(wire).map(|c| c.priority),
Some(3),
"…and by wire hash"
);
}
#[test]
fn concurrent_remove_and_reregister_never_strands_the_index() {
use std::sync::Arc as StdArc;
for _ in 0..64 {
let reg = StdArc::new(ChannelConfigRegistry::new());
let id = ChannelId::parse("svc.requests").unwrap();
let hash = id.hash();
reg.insert(ChannelConfig::new(id.clone()));
std::thread::scope(|s| {
let r1 = reg.clone();
s.spawn(move || {
r1.remove_by_name("svc.requests");
});
let r2 = reg.clone();
let id2 = id.clone();
s.spawn(move || {
r2.insert(ChannelConfig::new(id2).with_priority(9));
});
});
if reg.get_by_name("svc.requests").is_some() {
assert!(
reg.get(hash).is_some(),
"config present by name but unreachable by canonical \
hash — the reverse index was stranded"
);
}
}
}
#[test]
fn get_by_name_and_resolve_by_name_agree_on_prefix_resolution() {
let reg = ChannelConfigRegistry::new();
reg.insert_prefix(
"svc.",
ChannelConfig::new(ChannelId::parse("svc.general").unwrap()).with_priority(1),
);
reg.insert_prefix(
"svc.replies.",
ChannelConfig::new(ChannelId::parse("svc.replies.prefix").unwrap()).with_priority(2),
);
reg.insert(ChannelConfig::new(ChannelId::parse("svc.exact").unwrap()).with_priority(3));
for name in ["svc.replies.aa", "svc.other", "svc.exact", "nomatch"] {
let via_get = reg.get_by_name(name).map(|c| c.priority);
let via_resolve = reg.resolve_by_name(name).map(|r| r.config.priority);
assert_eq!(
via_get, via_resolve,
"get_by_name and resolve_by_name disagreed for {name:?}"
);
}
assert_eq!(
reg.resolve_by_name("svc.replies.aa")
.unwrap()
.matched_prefix
.as_deref(),
Some("svc.replies.")
);
}
#[test]
fn queue_group_unrestricted_by_default() {
let peer = EntityKeypair::generate();
let rev = RevocationRegistry::new();
let config = ChannelConfig::new(ChannelId::parse("work/queue").unwrap());
assert_eq!(config.queue_group_policy, QueueGroupPolicy::Unrestricted);
assert!(config.can_join_queue_group(
peer.entity_id(),
"work/queue",
"workers",
None,
&rev,
0
));
}
#[test]
fn queue_group_deny_refuses_even_with_a_valid_chain() {
let owner = EntityKeypair::generate();
let peer = EntityKeypair::generate();
let rev = RevocationRegistry::new();
let config = ChannelConfig::new(ChannelId::parse("work/queue").unwrap())
.with_token_roots(vec![owner.entity_id().clone()])
.with_queue_group_policy(QueueGroupPolicy::Deny);
let chain = direct_chain(
&owner,
&peer,
TokenScope::SUBSCRIBE,
queue_group_hash("work/queue", "workers"),
);
assert!(!config.can_join_queue_group(
peer.entity_id(),
"work/queue",
"workers",
Some(&chain),
&rev,
0
));
}
#[test]
fn queue_group_grant_binds_to_one_specific_group() {
let owner = EntityKeypair::generate();
let worker = EntityKeypair::generate();
let rev = RevocationRegistry::new();
let channel = "work/queue";
let config = ChannelConfig::new(ChannelId::parse(channel).unwrap())
.with_token_roots(vec![owner.entity_id().clone()])
.with_queue_group_policy(QueueGroupPolicy::TokenBound);
let chain = direct_chain(
&owner,
&worker,
TokenScope::SUBSCRIBE,
queue_group_hash(channel, "batch"),
);
assert!(
config.can_join_queue_group(
worker.entity_id(),
channel,
"batch",
Some(&chain),
&rev,
0
),
"the granted group must be joinable"
);
assert!(
!config.can_join_queue_group(
worker.entity_id(),
channel,
"realtime",
Some(&chain),
&rev,
0
),
"a grant for one group must not admit the holder to another — \
that is the work-stealing this policy exists to stop"
);
}
#[test]
fn channel_subscribe_token_is_not_a_queue_group_grant() {
let owner = EntityKeypair::generate();
let reader = EntityKeypair::generate();
let rev = RevocationRegistry::new();
let channel = "work/queue";
let id = ChannelId::parse(channel).unwrap();
let config = ChannelConfig::new(id.clone())
.with_token_roots(vec![owner.entity_id().clone()])
.with_queue_group_policy(QueueGroupPolicy::TokenBound);
let chain = direct_chain(&owner, &reader, TokenScope::SUBSCRIBE, id.hash());
assert!(
config.can_subscribe(
&make_caps(false),
reader.entity_id(),
id.hash(),
Some(&chain),
&rev,
0
),
"precondition: it is a valid subscribe credential"
);
assert!(
!config.can_join_queue_group(
reader.entity_id(),
channel,
"workers",
Some(&chain),
&rev,
0
),
"a read-only subscriber must not be able to steal worker traffic"
);
}
#[test]
fn queue_group_token_bound_fails_closed() {
let owner = EntityKeypair::generate();
let peer = EntityKeypair::generate();
let rev = RevocationRegistry::new();
let channel = "work/queue";
let rooted = ChannelConfig::new(ChannelId::parse(channel).unwrap())
.with_token_roots(vec![owner.entity_id().clone()])
.with_queue_group_policy(QueueGroupPolicy::TokenBound);
assert!(
!rooted.can_join_queue_group(peer.entity_id(), channel, "w", None, &rev, 0),
"no chain presented → refuse"
);
let rootless = ChannelConfig::new(ChannelId::parse(channel).unwrap())
.with_queue_group_policy(QueueGroupPolicy::TokenBound);
let chain = direct_chain(
&owner,
&peer,
TokenScope::SUBSCRIBE,
queue_group_hash(channel, "w"),
);
assert!(
!rootless.can_join_queue_group(peer.entity_id(), channel, "w", Some(&chain), &rev, 0),
"no roots to anchor against → refuse"
);
}
#[test]
fn queue_group_hash_cannot_collide_with_a_channel_name() {
let h = queue_group_hash("work/queue", "workers");
assert!(ChannelName::new("work/queue#workers").is_err());
assert_ne!(h, channel_hash("work/queue"));
assert_ne!(h, channel_hash("work/queueworkers"));
assert_ne!(h, queue_group_hash("work/queue", "other"));
assert_ne!(h, queue_group_hash("work/other", "workers"));
}
#[test]
fn queue_group_hash_is_the_channel_hash_of_the_joined_name() {
for (channel, group) in [
("work/queue", "workers"),
("a", "b"),
("svc.replies.deadbeefdeadbeef", "shard-3"),
] {
assert_eq!(
queue_group_hash(channel, group),
channel_hash(&format!("{channel}#{group}")),
"queue_group_hash({channel:?}, {group:?}) no longer equals the \
canonical hash of \"{channel}#{group}\" — the two have drifted \
into separate hash spaces"
);
}
}
#[test]
fn prefix_config_gate_binds_to_the_requested_channel_not_the_sentinel() {
let owner = EntityKeypair::generate();
let subject = EntityKeypair::generate();
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let sentinel = ChannelId::parse("svc.replies.prefix").unwrap();
let config =
ChannelConfig::new(sentinel.clone()).with_token_roots(vec![owner.entity_id().clone()]);
let mine = channel_hash("svc.replies.aaaa");
let theirs = channel_hash("svc.replies.bbbb");
let chain = direct_chain(&owner, &subject, TokenScope::SUBSCRIBE, mine);
assert!(config.can_subscribe(&caps, subject.entity_id(), mine, Some(&chain), &rev, 0));
assert!(
!config.can_subscribe(&caps, subject.entity_id(), theirs, Some(&chain), &rev, 0),
"a token for one channel must not authorize a sibling under the \
same prefix"
);
let sentinel_chain = direct_chain(&owner, &subject, TokenScope::SUBSCRIBE, sentinel.hash());
assert!(
!config.can_subscribe(
&caps,
subject.entity_id(),
mine,
Some(&sentinel_chain),
&rev,
0
),
"a sentinel-scoped token must not authorize a real channel"
);
}
#[test]
fn prefix_config_publish_gate_binds_to_the_requested_channel() {
let owner = EntityKeypair::generate();
let subject = EntityKeypair::generate();
let caps = make_caps(false);
let rev = RevocationRegistry::new();
let sentinel = ChannelId::parse("svc.requests.prefix").unwrap();
let config = ChannelConfig::new(sentinel).with_token_roots(vec![owner.entity_id().clone()]);
let real = channel_hash("svc.requests.aaaa");
let chain = direct_chain(&owner, &subject, TokenScope::PUBLISH, real);
assert!(config.can_publish(&caps, subject.entity_id(), real, Some(&chain), &rev, 0));
assert!(
!config.can_publish(
&caps,
subject.entity_id(),
channel_hash("svc.requests.bbbb"),
Some(&chain),
&rev,
0
),
"a publish token for one channel must not authorize a sibling"
);
}
#[test]
fn reverify_paths_bind_to_the_requested_channel() {
let owner = EntityKeypair::generate();
let subject = EntityKeypair::generate();
let rev = RevocationRegistry::new();
let sentinel = ChannelId::parse("svc.replies.prefix").unwrap();
let config = ChannelConfig::new(sentinel).with_token_roots(vec![owner.entity_id().clone()]);
let mine = channel_hash("svc.replies.aaaa");
let chain = direct_chain(&owner, &subject, TokenScope::SUBSCRIBE, mine);
for reverify in [
ChannelConfig::reverify_subscribe as fn(&_, &_, &_, u64, &_, u64) -> bool,
ChannelConfig::reverify_subscribe_presigned,
] {
assert!(reverify(
&config,
&chain,
subject.entity_id(),
mine,
&rev,
0
));
assert!(
!reverify(
&config,
&chain,
subject.entity_id(),
channel_hash("svc.replies.bbbb"),
&rev,
0
),
"re-verify must reject a chain that does not authorize the \
channel being published to"
);
}
}
const OB: OriginBinding = OriginBinding::OriginHashHex16;
const OB_PREFIX: &str = "svc.replies.";
#[test]
fn origin_binding_rejects_unpinned_peer() {
let name = format!("{OB_PREFIX}{:016x}", 0xABCD_1234_5678_9ABCu64);
assert!(
!OB.authorizes(&name, Some(OB_PREFIX), None),
"an unpinned peer must never be authorized, even for a \
well-formed name"
);
}
#[test]
fn origin_binding_admits_matching_origin() {
let origin = 0xABCD_1234_5678_9ABCu64;
let name = format!("{OB_PREFIX}{origin:016x}");
assert!(OB.authorizes(&name, Some(OB_PREFIX), Some(origin)));
}
#[test]
fn origin_binding_rejects_other_peers_origin() {
let victim = 0xABCD_1234_5678_9ABCu64;
let attacker = 0x0011_2233_4455_6677u64;
let name = format!("{OB_PREFIX}{victim:016x}");
assert!(
!OB.authorizes(&name, Some(OB_PREFIX), Some(attacker)),
"a peer must not claim a channel naming another peer's origin"
);
}
#[test]
fn origin_binding_without_a_matched_prefix_fails_closed() {
let origin = 0xABCD_1234_5678_9ABCu64;
let name = format!("{OB_PREFIX}{origin:016x}");
assert!(!OB.authorizes(&name, None, Some(origin)));
}
#[test]
fn origin_bound_config_registered_by_exact_name_denies_everyone() {
let reg = ChannelConfigRegistry::new();
let origin = 0xABCD_1234_5678_9ABCu64;
let name = format!("{OB_PREFIX}{origin:016x}");
reg.insert(
ChannelConfig::new(ChannelId::parse(&name).unwrap()).with_subscriber_origin_binding(OB),
);
let resolved = reg.resolve_by_name(&name).expect("exact entry resolves");
assert_eq!(
resolved.matched_prefix, None,
"an exact hit reports no matched prefix — this is the input that \
makes the binding fail closed"
);
assert!(
!OB.authorizes(&name, resolved.matched_prefix.as_deref(), Some(origin)),
"an exact-registered origin binding denies even the peer the name \
encodes; registering it as a prefix is the only working shape"
);
let reg = ChannelConfigRegistry::new();
reg.insert_prefix(
OB_PREFIX,
ChannelConfig::new(ChannelId::parse("svc.replies.prefix").unwrap())
.with_subscriber_origin_binding(OB),
);
let resolved = reg.resolve_by_name(&name).expect("prefix entry resolves");
assert_eq!(resolved.matched_prefix.as_deref(), Some(OB_PREFIX));
assert!(OB.authorizes(&name, resolved.matched_prefix.as_deref(), Some(origin)));
}
#[test]
fn origin_binding_requires_exact_16_hex_suffix() {
let origin = 0x0000_0000_0000_00ABu64;
for bad in [
"ab", "AB", "00000000000000ab0", "00000000000000a", "00000000000000AB", ] {
let name = format!("{OB_PREFIX}{bad}");
assert!(
!OB.authorizes(&name, Some(OB_PREFIX), Some(origin)),
"suffix {bad:?} must not authorize origin {origin:#x}"
);
}
let good = format!("{OB_PREFIX}{origin:016x}");
assert!(OB.authorizes(&good, Some(OB_PREFIX), Some(origin)));
}
#[test]
fn config_without_binding_is_unconstrained() {
let cfg = ChannelConfig::new(ChannelId::parse("svc.replies.prefix").unwrap());
assert!(cfg.subscriber_origin_binding.is_none());
}
#[test]
fn resolve_by_name_reports_the_matched_prefix() {
let reg = ChannelConfigRegistry::new();
let sentinel = ChannelId::parse("svc.replies.prefix").unwrap();
reg.insert_prefix(
OB_PREFIX,
ChannelConfig::new(sentinel).with_subscriber_origin_binding(OB),
);
let resolved = reg
.resolve_by_name("svc.replies.00112233445566aa")
.expect("prefix must resolve");
assert_eq!(resolved.matched_prefix.as_deref(), Some(OB_PREFIX));
assert_eq!(resolved.config.subscriber_origin_binding, Some(OB));
let exact = ChannelId::parse("plain.channel").unwrap();
reg.insert(ChannelConfig::new(exact));
let resolved = reg.resolve_by_name("plain.channel").expect("exact");
assert!(resolved.matched_prefix.is_none());
}
#[test]
fn rpc_service_defaults_are_install_if_absent_and_origin_bound() {
let reg = ChannelConfigRegistry::new();
let root = EntityKeypair::generate();
reg.insert(
ChannelConfig::new(ChannelId::parse("svc.requests").unwrap())
.with_token_roots(vec![root.entity_id().clone()]),
);
reg.insert_prefix(
"svc.replies.",
ChannelConfig::new(ChannelId::parse("svc.replies.prefix").unwrap())
.with_token_roots(vec![root.entity_id().clone()]),
);
reg.install_rpc_service_defaults("svc")
.expect("valid service name");
assert!(
reg.get_by_name("svc.requests").unwrap().token_required(),
"H2: serving must not replace an ACL the operator registered \
first — a replacing insert destroys it silently, leaving a \
posture identical to the default"
);
assert!(
reg.get_by_name("svc.replies.abcdef0123456789")
.unwrap()
.token_required(),
"H2 applies to the reply PREFIX too"
);
let fresh = ChannelConfigRegistry::new();
fresh
.install_rpc_service_defaults("svc")
.expect("valid service name");
assert!(
fresh.get_by_name("svc.requests").is_some(),
"the request channel must be installed when unclaimed"
);
let replies = fresh
.get_by_name("svc.replies.abcdef0123456789")
.expect("the reply prefix must admit a per-caller channel");
assert_eq!(
replies.subscriber_origin_binding,
Some(OriginBinding::OriginHashHex16),
"H3: the reply prefix must be origin-bound. Unbound, any mesh peer \
can hold a live subscription to another caller's reply channel and \
receive that caller's response bodies whenever the server's direct \
route misses and the response falls back to roster fan-out."
);
}
#[test]
fn rpc_service_defaults_fill_only_the_missing_half() {
let root = EntityKeypair::generate();
let reg = ChannelConfigRegistry::new();
reg.insert(
ChannelConfig::new(ChannelId::parse("svc.requests").unwrap())
.with_token_roots(vec![root.entity_id().clone()]),
);
reg.install_rpc_service_defaults("svc").expect("install");
assert!(
reg.get_by_name("svc.requests").unwrap().token_required(),
"the operator's request ACL must survive",
);
assert_eq!(
reg.get_by_name("svc.replies.abcdef0123456789")
.expect("the missing reply prefix must be installed")
.subscriber_origin_binding,
Some(OriginBinding::OriginHashHex16),
);
let reg = ChannelConfigRegistry::new();
reg.insert_prefix(
"svc.replies.",
ChannelConfig::new(ChannelId::parse("svc.replies.prefix").unwrap())
.with_token_roots(vec![root.entity_id().clone()]),
);
reg.install_rpc_service_defaults("svc").expect("install");
assert!(
reg.get_by_name("svc.requests").is_some(),
"the missing request channel must be installed",
);
assert!(
reg.get_by_name("svc.replies.abcdef0123456789")
.unwrap()
.token_required(),
"the operator's reply ACL must survive",
);
}
#[test]
fn rpc_service_defaults_are_idempotent() {
let reg = ChannelConfigRegistry::new();
for _ in 0..5 {
reg.install_rpc_service_defaults("svc").expect("install");
}
assert_eq!(reg.len(), 1, "one exact entry, however many calls");
assert_eq!(reg.snapshot_prefixes().len(), 1, "one prefix entry");
}
#[test]
fn rpc_service_defaults_never_expose_an_unbound_reply_window() {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtomicOrdering};
use parking_lot::Mutex as StdMutex;
use std::sync::Arc as StdArc;
let current = StdArc::new(StdMutex::new(StdArc::new(ChannelConfigRegistry::new())));
let stop = StdArc::new(AtomicBool::new(false));
let saw_unbound_window = StdArc::new(AtomicBool::new(false));
let observations = StdArc::new(AtomicU64::new(0));
let observer = {
let current = StdArc::clone(¤t);
let stop = StdArc::clone(&stop);
let saw = StdArc::clone(&saw_unbound_window);
let observations = StdArc::clone(&observations);
std::thread::spawn(move || {
while !stop.load(AtomicOrdering::Relaxed) {
let reg = {
let guard = current.lock();
StdArc::clone(&guard)
};
let has_request = reg.get_by_name("svc.requests").is_some();
let has_reply = reg.get_by_name("svc.replies.abcdef0123456789").is_some();
observations.fetch_add(1, AtomicOrdering::Relaxed);
if has_request && !has_reply {
saw.store(true, AtomicOrdering::Relaxed);
}
}
})
};
for _ in 0..20_000 {
let fresh = StdArc::new(ChannelConfigRegistry::new());
{
let mut guard = current.lock();
*guard = StdArc::clone(&fresh);
}
fresh.install_rpc_service_defaults("svc").expect("install");
}
stop.store(true, AtomicOrdering::Relaxed);
observer.join().expect("observer thread");
assert!(
observations.load(AtomicOrdering::Relaxed) > 0,
"the observer never ran; this test proves nothing",
);
assert!(
!saw_unbound_window.load(AtomicOrdering::Relaxed),
"a reader observed the request channel configured while the \
reply prefix was still absent — that window leaves replies \
unbound, which is the H3 posture. Install the prefix first.",
);
}
#[test]
fn rpc_service_defaults_install_nothing_for_an_unrepresentable_name() {
use super::super::name::MAX_NAME_LEN;
let no_sentinel = "s".repeat(MAX_NAME_LEN - ".requests".len());
assert!(ChannelName::new(&format!("{no_sentinel}.requests")).is_ok());
assert!(
ChannelName::new(&format!("{no_sentinel}.replies.prefix")).is_err(),
"precondition: band 1 must have an unrepresentable sentinel"
);
let no_real_reply = "s".repeat(MAX_NAME_LEN - ".replies.prefix".len());
assert!(ChannelName::new(&format!("{no_real_reply}.requests")).is_ok());
assert!(
ChannelName::new(&format!("{no_real_reply}.replies.prefix")).is_ok(),
"precondition: band 2's sentinel must VALIDATE — that is what \
makes checking the sentinel insufficient"
);
assert!(
ChannelName::new(&format!("{no_real_reply}.replies.{:016x}", 0u64)).is_err(),
"precondition: …while no real per-caller reply channel fits"
);
for (band, service) in [
("no sentinel", no_sentinel.as_str()),
("no real reply channel", no_real_reply.as_str()),
("invalid characters", "bad name#with/invalid chars"),
] {
let reg = ChannelConfigRegistry::new();
assert!(
reg.install_rpc_service_defaults(service).is_err(),
"[{band}] an unrepresentable service name must report the \
failure, not swallow it — a serve call that succeeds \
against a registry with no policy refuses every request \
later, far from the registration that caused it"
);
assert_eq!(
reg.len(),
0,
"[{band}] installed a request channel the reply side cannot \
match (service len {})",
service.len()
);
assert_eq!(
reg.snapshot_prefixes().len(),
0,
"[{band}] installed a reply prefix no caller can ever use \
(service len {})",
service.len()
);
}
}
#[test]
fn rpc_service_defaults_install_at_the_longest_usable_service_name() {
use super::super::name::MAX_NAME_LEN;
let longest = "s".repeat(MAX_NAME_LEN - ".replies.0123456789abcdef".len());
let reg = ChannelConfigRegistry::new();
reg.install_rpc_service_defaults(&longest)
.expect("the longest representable service name must install");
assert!(
reg.get_by_name(&format!("{longest}.requests")).is_some(),
"the longest fully-usable service name must still get its request \
channel"
);
let reply = format!("{longest}.replies.{:016x}", u64::MAX);
assert_eq!(
ChannelName::new(&reply).map(|_| ()),
Ok(()),
"precondition: this is the longest name where a real reply \
channel still fits"
);
assert_eq!(
reg.get_by_name(&reply)
.expect("the reply prefix must resolve it")
.subscriber_origin_binding,
Some(OriginBinding::OriginHashHex16)
);
}
#[test]
fn insert_if_absent_installs_when_vacant() {
let reg = ChannelConfigRegistry::new();
let id = ChannelId::parse("svc.requests").unwrap();
assert!(reg.insert_if_absent(ChannelConfig::new(id.clone()).with_priority(4)));
assert_eq!(reg.get_by_name("svc.requests").unwrap().priority, 4);
assert_eq!(reg.get(id.hash()).unwrap().priority, 4);
}
#[test]
fn insert_if_absent_preserves_existing_strict_config() {
let reg = ChannelConfigRegistry::new();
let id = ChannelId::parse("svc.requests").unwrap();
let root = EntityKeypair::generate();
reg.insert(ChannelConfig::new(id.clone()).with_token_roots(vec![root.entity_id().clone()]));
let installed = reg.insert_if_absent(ChannelConfig::new(id.clone()));
assert!(!installed, "must report that it did not install");
let cfg = reg.get_by_name("svc.requests").unwrap();
assert!(
cfg.token_required(),
"operator's token gate must survive auto-registration"
);
assert_eq!(cfg.token_roots.len(), 1);
}
#[test]
fn insert_prefix_if_absent_preserves_existing_strict_prefix() {
let reg = ChannelConfigRegistry::new();
let sentinel = ChannelId::parse("svc.replies.prefix").unwrap();
let root = EntityKeypair::generate();
reg.insert_prefix(
"svc.replies.",
ChannelConfig::new(sentinel.clone()).with_token_roots(vec![root.entity_id().clone()]),
);
let installed = reg.insert_prefix_if_absent("svc.replies.", ChannelConfig::new(sentinel));
assert!(!installed);
let cfg = reg.get_by_name("svc.replies.abcdef0123456789").unwrap();
assert!(
cfg.token_required(),
"operator's reply-prefix gate must survive auto-registration"
);
}
#[test]
fn insert_prefix_if_absent_installs_when_vacant() {
let reg = ChannelConfigRegistry::new();
let sentinel = ChannelId::parse("svc.replies.prefix").unwrap();
assert!(reg.insert_prefix_if_absent(
"svc.replies.",
ChannelConfig::new(sentinel).with_priority(2)
));
assert_eq!(reg.get_by_name("svc.replies.deadbeef").unwrap().priority, 2);
}
#[test]
fn repeated_insert_does_not_self_collide_the_hash_index() {
let reg = ChannelConfigRegistry::new();
let id = ChannelId::parse("svc.requests").unwrap();
let hash = id.hash();
reg.insert(ChannelConfig::new(id.clone()).with_priority(1));
reg.insert(ChannelConfig::new(id.clone()).with_priority(2));
reg.insert(ChannelConfig::new(id).with_priority(3));
assert_eq!(reg.len(), 1, "one channel, not three");
let cfg = reg
.get(hash)
.expect("canonical-hash lookup must survive re-registration");
assert_eq!(cfg.priority, 3, "latest config wins");
}
#[test]
fn insert_then_if_absent_leaves_hash_index_unambiguous() {
let reg = ChannelConfigRegistry::new();
let id = ChannelId::parse("svc.requests").unwrap();
let hash = id.hash();
reg.insert(ChannelConfig::new(id.clone()).with_priority(9));
assert!(!reg.insert_if_absent(ChannelConfig::new(id.clone())));
assert!(!reg.insert_if_absent(ChannelConfig::new(id)));
assert_eq!(
reg.get(hash).expect("must stay resolvable").priority,
9,
"the operator's config must remain, and the index unambiguous"
);
}
#[test]
fn concurrent_insert_if_absent_elects_exactly_one_winner() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc as StdArc;
let reg = StdArc::new(ChannelConfigRegistry::new());
let wins = StdArc::new(AtomicUsize::new(0));
let id = ChannelId::parse("svc.requests").unwrap();
std::thread::scope(|s| {
for i in 0..8 {
let reg = reg.clone();
let wins = wins.clone();
let id = id.clone();
s.spawn(move || {
if reg.insert_if_absent(ChannelConfig::new(id).with_priority(i)) {
wins.fetch_add(1, Ordering::Relaxed);
}
});
}
});
assert_eq!(wins.load(Ordering::Relaxed), 1, "exactly one installer");
assert_eq!(reg.len(), 1);
assert!(
reg.get(id.hash()).is_some(),
"hash index must stay unambiguous under concurrent installs"
);
}
#[test]
fn concurrent_registration_and_removal_keep_the_indices_consistent() {
use std::sync::Arc as StdArc;
let names: Vec<String> = (0..4).map(|i| format!("svc.chan{i}")).collect();
for _round in 0..200 {
let reg = StdArc::new(ChannelConfigRegistry::new());
std::thread::scope(|s| {
for name in &names {
for _ in 0..2 {
let reg = reg.clone();
let id = ChannelId::parse(name).unwrap();
s.spawn(move || {
reg.insert(ChannelConfig::new(id.clone()));
reg.remove_by_name(id.name().as_str());
reg.insert(ChannelConfig::new(id));
});
}
}
for name in &names {
let reg = reg.clone();
let name = name.clone();
s.spawn(move || {
reg.remove_by_name(&name);
});
}
});
for name in &names {
let present = reg.get_by_name(name).is_some();
let hash = ChannelId::parse(name).unwrap().hash();
let indexed = reg
.by_hash
.get(&hash)
.is_some_and(|names| names.iter().any(|n| n == name));
assert_eq!(
present, indexed,
"index and `configs` disagree about {name:?}: present={present}, \
indexed={indexed}. Registered-but-unindexed silently stops \
enforcing that channel's ACL on the `get(hash)` path; \
indexed-but-absent poisons the bucket for every channel \
sharing it."
);
}
}
}
}