Skip to content
Merged
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
139 changes: 126 additions & 13 deletions rs/moq-net/src/model/origin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1708,6 +1708,9 @@ struct OriginScope {
allowed: Patterns,
// The subtrees that resolve elsewhere; see [`Producer::mount`]. Disjoint.
mounts: Arc<[Mount]>,
// The subtrees this handle never reaches despite `allowed`, absolute and
// named as the handle sees them; see [`Consumer::exclude`].
excluded: Arc<[Path]>,
}

/// A subtree a handle reads from elsewhere on the origin: `at/rest` resolves at
Expand Down Expand Up @@ -1784,6 +1787,7 @@ impl OriginScope {
Self {
allowed: Patterns::new(),
mounts: Arc::from([]),
excluded: Arc::from([]),
}
}

Expand All @@ -1795,7 +1799,7 @@ impl OriginScope {
} else {
Some(Self {
allowed,
mounts: self.mounts.clone(),
..self.clone()
})
}
}
Expand All @@ -1822,7 +1826,26 @@ impl OriginScope {

/// Whether this view reaches the absolute `path`.
fn permits(&self, path: &Path) -> bool {
self.allowed.matches(path.as_str())
self.allowed.matches(path.as_str()) && !self.excluded.iter().any(|excluded| path.has_prefix(excluded))
}

/// The excluded subtrees a cursor must not present, in the space it reads: the
/// origin's own, or `mount`'s target. `None` when an exclusion covers the whole mount.
fn holes(&self, mount: Option<&Mount>) -> Option<Vec<Path>> {
let Some(mount) = mount else {
return Some(self.excluded.to_vec());
};
let mut holes = Vec::new();
for excluded in self.excluded.iter() {
if mount.at.has_prefix(excluded) {
return None;
}
if excluded.has_prefix(&mount.at) {
// Too deep for the mount to resolve, nothing beneath is nameable anyway.
holes.extend(mount.resolve(excluded));
}
}
Some(holes)
}

/// What this view reaches, named from `root`.
Expand All @@ -1836,6 +1859,7 @@ impl Default for OriginScope {
Self {
allowed: Patterns::from(Pattern::all()),
mounts: Arc::from([]),
excluded: Arc::from([]),
}
}
}
Expand Down Expand Up @@ -2489,8 +2513,8 @@ impl Producer {
.collect();
Ok(Producer {
scope: OriginScope {
allowed: self.scope.allowed.clone(),
mounts,
..self.scope.clone()
},
..self.clone()
})
Expand Down Expand Up @@ -6163,6 +6187,17 @@ impl Consumer {
self
}

/// A clone that never reaches the subtree at `prefix`, relative to this root:
/// [`announced`](Self::announced) leaves out the routes at or beneath it and a
/// request for a path there fails with [`Error::Unauthorized`]. A route
/// announced above `prefix` is still reported. [`allowed`](Self::allowed) is unchanged.
pub fn exclude(&self, prefix: impl TryInto<Path, Error: Into<Error>>) -> Result<Self, Error> {
let prefix = self.root.join(&path::convert(prefix)?)?;
let mut consumer = self.clone();
consumer.scope.excluded = self.scope.excluded.iter().cloned().chain([prefix]).collect();
Ok(consumer)
}

/// Set wire discovery visibility relative to this consumer's requested root.
#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
pub(crate) fn discovery(mut self, hidden: bool) -> Self {
Expand Down Expand Up @@ -6245,8 +6280,9 @@ impl Consumer {
// A root at or beneath a mount reads only the mount: one cursor, re-rooted
// onto the target.
if let Some(mount) = self.scope.mount(&self.root) {
// A root the mount resolves past the depth limit has nothing to announce.
let Some(root) = mount.resolve(&self.root) else {
// A root the mount resolves past the depth limit, or an excluded one, has
// nothing to announce.
let (Some(root), Some(holes)) = (mount.resolve(&self.root), self.scope.holes(Some(mount))) else {
return AnnounceConsumer::new(
self.root.clone(),
Vec::new(),
Expand All @@ -6262,7 +6298,7 @@ impl Consumer {
self.hidden.translate(mount),
Some(mount),
Path::default(),
Vec::new(),
holes,
)];
return AnnounceConsumer::new(
self.root.clone(),
Expand All @@ -6274,16 +6310,19 @@ impl Consumer {
);
}

// Otherwise the consumer's own cursor, minus the mounted subtrees, plus one
// cursor per mount beneath the root it may discover, presenting under it.
// Otherwise the consumer's own cursor, minus the mounted and excluded subtrees,
// plus one cursor per mount beneath the root it may discover, presenting under it.
let heads = interest_prefixes(&self.scope.allowed);
let mut holes = Vec::new();
let mut holes = self.scope.holes(None).unwrap_or_default();
let mut cursors = Vec::new();
for mount in self.scope.mounts.iter() {
let Some(under) = mount.at.strip_prefix(&self.root) else {
continue;
};
holes.push(mount.at.clone());
let Some(mount_holes) = self.scope.holes(Some(mount)) else {
continue;
};
let allowed = mount.translate(&self.scope.allowed);
// Hidden at the mount point means hidden throughout: the dot segment is above
// everything the mount holds. A top-up feed's rule moves onto the target.
Expand All @@ -6301,7 +6340,7 @@ impl Consumer {
self.hidden.translate(mount),
Some(mount),
under.clone(),
Vec::new(),
mount_holes,
));
}
cursors.insert(
Expand Down Expand Up @@ -6388,7 +6427,7 @@ impl Consumer {

// `scope` keeps narrower permissions intact: on a consumer limited to
// `foo/specific`, no route can ever cover `foo`.
if !consumer.allowed().matches(path.as_str()) {
if !consumer.scope.permits(&consumer.root.join(&path)?) {
return Err(Error::Unauthorized);
}

Expand Down Expand Up @@ -6429,9 +6468,13 @@ impl Consumer {

/// [`Self::routed_broadcast`], refusing any instance but `epoch` when one is pinned.
pub(super) fn routing(&self, path: Path, epoch: Option<crate::Epoch>) -> Routing {
// `allowed` keeps narrower permissions intact: if the whole path is not
// The scope keeps narrower permissions intact: if the whole path is not
// reachable, no route can ever cover it, so bail rather than loop forever.
let request = (!self.allowed().matches(path.as_str())).then(|| Requesting::failed(Error::Unauthorized));
let request = match self.root.join(&path) {
Ok(named) if self.scope.permits(&named) => None,
Ok(_) => Some(Requesting::failed(Error::Unauthorized)),
Err(err) => Some(Requesting::failed(err.into())),
};
Routing {
consumer: self.clone(),
path,
Expand Down Expand Up @@ -7712,6 +7755,76 @@ mod tests {
assert_eq!(resolved.info().path.as_str(), ".stats/node");
}

/// An excluded subtree is neither discovered nor resolved, even under a route
/// covering it, while its hidden siblings and the covering route still show.
#[moq_clock::test]
#[cfg(feature = "async")]
async fn exclude_hides_and_refuses_the_subtree() {
let producer = origin(1).produce();
let _claim = producer.announce("p1", Route::default()).unwrap();
let _cam = producer.publish("p1/cam", Route::default()).unwrap();
let _private = producer.publish("p1/.private/cam", Route::default()).unwrap();
let _overlay = producer.publish("p1/.pro/cam", Route::default()).unwrap();
let consumer = producer
.consume()
.scope("p1", &Patterns::from(Pattern::all()))
.unwrap()
.with_hidden(true)
.exclude(".pro")
.unwrap();

let mut announced = consumer.announced();
announced.expect_next_active("").await;
announced.expect_next_active(".private/cam").await;
announced.expect_next_active("cam").await;
announced.assert_next_wait();

consumer.request_broadcast("cam", None).await.expect("resolves");
for path in [".pro", ".pro/cam", ".pro/cam/.pro/transcode.hang"] {
let refused = consumer
.request_broadcast(path, None)
.now_or_never()
.expect("refused at once");
assert!(matches!(refused, Err(Error::Unauthorized)), "{path}");
let refused = consumer.routed_broadcast(path).now_or_never().expect("refused at once");
assert!(matches!(refused, Err(Error::Unauthorized)), "{path}");
assert!(matches!(consumer.follow(path), Err(Error::Unauthorized)), "{path}");
}
// Only whole segments: a sibling sharing the prefix text is untouched.
let _sibling = producer.publish("p1/.prod", Route::default()).unwrap();
announced.expect_next_active(".prod").await;
}

/// An exclusion inside a mount carves the target, and one over the mount point
/// drops the mount.
#[moq_clock::test]
async fn exclude_reaches_into_a_mount() {
let producer = origin(1).produce();
let _foo = producer.publish(".svc/p1/foo", Route::default()).unwrap();
let _bar = producer.publish(".svc/p1/bar", Route::default()).unwrap();
let _cam = producer.publish("p1/cam", Route::default()).unwrap();
let project = mounted(&producer, "p1", &["**"]).with_hidden(true);

let mut announced = project.exclude(".svc/foo").unwrap().announced();
announced.expect_next_active("cam").await;
announced.expect_next_active(".svc/bar").await;
announced.assert_next_wait();

let mut announced = project.exclude(".svc").unwrap().announced();
announced.expect_next_active("cam").await;
announced.assert_next_wait();

// Rooted inside the mount, the exclusion moves onto the target.
let mut inside = project
.scope(".svc", &Patterns::from(Pattern::all()))
.unwrap()
.exclude("foo")
.unwrap()
.announced();
inside.expect_next_active("bar").await;
inside.assert_next_wait();
}

/// A project-rooted handle reading `.svc` from the fleet-wide `.svc/<pid>`.
fn mounted(producer: &Producer, pid: &str, patterns: &[&str]) -> Consumer {
let patterns: Patterns = patterns.iter().map(|pattern| pattern.parse().unwrap()).collect();
Expand Down
Loading