1use std::sync::Arc;
8
9use async_trait::async_trait;
10use hyprstream_rpc::Subject;
11use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Namespace, ReadMountTarget, Stat};
12
13use crate::server::state::ServerState;
14use crate::services::remote_registry_mount::RemoteRegistryMount;
15
16const QTDIR: u8 = 0x80;
17
18fn canonicalize_path(repo: &str, worktree: &str, path: &[&str]) -> Result<Vec<String>, MountError> {
19 if path
20 .iter()
21 .any(|part| part.is_empty() || *part == "." || *part == ".." || part.contains('/'))
22 {
23 return Err(MountError::PermissionDenied(
24 "invalid canonical path".into(),
25 ));
26 }
27 match path {
28 [] => Ok(vec![]),
29 ["worktree", rest @ ..] => {
30 let mut result = vec![
31 "srv".to_owned(),
32 "registry".to_owned(),
33 repo.to_owned(),
34 worktree.to_owned(),
35 ];
36 result.extend(rest.iter().map(|part| (*part).to_owned()));
37 Ok(result)
38 }
39 ["srv"] | ["srv", "registry"] => Ok(path.iter().map(|p| (*p).to_owned()).collect()),
40 ["srv", "registry", name, rest @ ..] if *name == repo => {
41 if rest.first().is_some_and(|first| *first != worktree) {
42 return Err(MountError::PermissionDenied("wrong worktree".into()));
43 }
44 Ok(path.iter().map(|p| (*p).to_owned()).collect())
45 }
46 _ => Err(MountError::PermissionDenied(
47 "path outside canonical export".into(),
48 )),
49 }
50}
51
52struct CanonicalFid {
53 path: Vec<String>,
54 canonical: Vec<String>,
55 target: Option<ReadMountTarget>,
56 inner: Option<Fid>,
57}
58
59pub(super) struct CanonicalReadMount {
60 namespace: Namespace,
61 gate: RegistryGate,
62 subject: Subject,
63 repo: String,
64 worktree: String,
65}
66
67enum RegistryGate {
68 Live(Arc<RemoteRegistryMount>),
69 #[cfg(test)]
70 Test,
71}
72
73impl CanonicalReadMount {
74 pub(super) fn new(
75 state: &ServerState,
76 subject: Subject,
77 bearer: String,
78 ) -> Result<Self, MountError> {
79 let export =
80 state.config.ninep_canonical_read.as_ref().ok_or_else(|| {
81 MountError::PermissionDenied("canonical export is disabled".into())
82 })?;
83 let pep = state.ninep_vfs_pep.as_ref().ok_or_else(|| {
84 MountError::PermissionDenied("canonical export PEP is unavailable".into())
85 })?;
86 let registry = Arc::new(RemoteRegistryMount::for_holder(
87 Clone::clone(&state.registry),
88 state.policy_client.clone(),
89 subject.clone(),
90 bearer,
91 export,
92 ));
93 let mut namespace = Namespace::new();
94 namespace
95 .mount("/srv/registry", registry.clone())
96 .map_err(|_| MountError::PermissionDenied("canonical namespace setup failed".into()))?;
97 namespace.set_pep(Arc::clone(pep));
98 Ok(Self {
99 namespace,
100 gate: RegistryGate::Live(registry),
101 subject,
102 repo: export.repo_name.clone(),
103 worktree: export.worktree.clone(),
104 })
105 }
106
107 #[cfg(test)]
108 pub(super) fn test_new(
109 subject: Subject,
110 repo: &str,
111 worktree: &str,
112 mount: Arc<dyn Mount>,
113 ) -> Self {
114 let mut namespace = Namespace::new();
115 assert!(namespace.mount("/srv/registry", mount).is_ok());
116 Self {
117 namespace,
118 gate: RegistryGate::Test,
119 subject,
120 repo: repo.to_owned(),
121 worktree: worktree.to_owned(),
122 }
123 }
124
125 fn canonicalize(&self, path: &[&str]) -> Result<Vec<String>, MountError> {
126 canonicalize_path(&self.repo, &self.worktree, path)
127 }
128
129 async fn authorize(&self, canonical: &[String], caller: &Subject) -> Result<(), MountError> {
130 if caller != &self.subject {
131 return Err(MountError::PermissionDenied("9P holder changed".into()));
132 }
133 match &self.gate {
134 RegistryGate::Live(registry) => registry.authorize(caller).await?,
135 #[cfg(test)]
136 RegistryGate::Test => {}
137 }
138 let path = format!("/{}", canonical.join("/"));
139 self.namespace
140 .authorize_read_path(&path, caller)
141 .await
142 .map_err(|_| MountError::PermissionDenied("canonical VFS read denied".into()))
143 }
144
145 fn directory_entry(name: &str) -> DirEntry {
146 DirEntry {
147 name: name.to_owned(),
148 is_dir: true,
149 size: 0,
150 stat: None,
151 }
152 }
153
154 fn synthetic_child(&self, canonical: &[String]) -> Option<&str> {
155 match canonical {
156 [] => Some("srv"),
157 [srv] if srv == "srv" => Some("registry"),
158 [srv, registry] if srv == "srv" && registry == "registry" => Some(&self.repo),
159 [srv, registry, repo]
160 if srv == "srv" && registry == "registry" && repo == &self.repo =>
161 {
162 Some(&self.worktree)
163 }
164 _ => None,
165 }
166 }
167
168 fn state<'a>(&self, fid: &'a Fid) -> Result<&'a CanonicalFid, MountError> {
169 fid.downcast_ref::<CanonicalFid>()
170 .ok_or_else(|| MountError::InvalidArgument("foreign canonical fid".into()))
171 }
172}
173
174#[async_trait]
175impl Mount for CanonicalReadMount {
176 async fn walk(&self, components: &[&str], caller: &Subject) -> Result<Fid, MountError> {
177 let canonical = self.canonicalize(components)?;
178 self.authorize(&canonical, caller).await?;
179 let (target, inner) = if canonical.len() >= 4 {
180 let path = format!("/{}", canonical.join("/"));
181 let (targets, relative) = self
182 .namespace
183 .resolve_read_targets(&path, caller)
184 .await
185 .map_err(|_| MountError::PermissionDenied("canonical VFS read denied".into()))?;
186 let target = targets
187 .into_iter()
188 .next()
189 .ok_or_else(|| MountError::NotFound("canonical target".into()))?;
190 let names: Vec<&str> = relative.iter().map(String::as_str).collect();
191 let inner = target.walk(&names, caller).await?;
192 (Some(target), Some(inner))
193 } else {
194 (None, None)
195 };
196 Ok(Fid::new(CanonicalFid {
197 path: components.iter().map(|part| (*part).to_owned()).collect(),
198 canonical,
199 target,
200 inner,
201 }))
202 }
203
204 async fn open(&self, fid: &mut Fid, mode: u8, caller: &Subject) -> Result<(), MountError> {
205 if mode != 0 {
206 return Err(MountError::PermissionDenied(
207 "canonical export is read-only".into(),
208 ));
209 }
210 let state = fid
211 .downcast_mut::<CanonicalFid>()
212 .ok_or_else(|| MountError::InvalidArgument("foreign canonical fid".into()))?;
213 self.authorize(&state.canonical, caller).await?;
214 if let (Some(target), Some(inner)) = (&state.target, &mut state.inner) {
215 target.open(inner, mode, caller).await?;
216 }
217 Ok(())
218 }
219
220 async fn read(
221 &self,
222 fid: &Fid,
223 offset: u64,
224 count: u32,
225 caller: &Subject,
226 ) -> Result<Vec<u8>, MountError> {
227 let state = self.state(fid)?;
228 self.authorize(&state.canonical, caller).await?;
229 match (&state.target, &state.inner) {
230 (Some(target), Some(inner)) => target.read(inner, offset, count, caller).await,
231 _ => Err(MountError::IsDirectory("canonical prefix".into())),
232 }
233 }
234
235 async fn write(
236 &self,
237 _fid: &Fid,
238 _offset: u64,
239 _data: &[u8],
240 _caller: &Subject,
241 ) -> Result<u32, MountError> {
242 Err(MountError::PermissionDenied(
243 "canonical export is read-only".into(),
244 ))
245 }
246
247 async fn readdir(&self, fid: &Fid, caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
248 let state = self.state(fid)?;
249 self.authorize(&state.canonical, caller).await?;
250 match (&state.target, &state.inner) {
251 (Some(target), Some(inner)) => target.readdir(inner, caller).await,
252 _ => {
253 let mut entries = vec![Self::directory_entry(
254 self.synthetic_child(&state.canonical)
255 .ok_or_else(|| MountError::NotDirectory("canonical prefix".into()))?,
256 )];
257 if state.path.is_empty() {
258 entries.push(Self::directory_entry("worktree"));
259 }
260 Ok(entries)
261 }
262 }
263 }
264
265 async fn stat(&self, fid: &Fid, caller: &Subject) -> Result<Stat, MountError> {
266 let state = self.state(fid)?;
267 self.authorize(&state.canonical, caller).await?;
268 match (&state.target, &state.inner) {
269 (Some(target), Some(inner)) => target.stat(inner, caller).await,
270 _ => Ok(Stat::unknown_qid(
271 QTDIR,
272 0,
273 state.path.last().cloned().unwrap_or_else(|| "/".into()),
274 0,
275 )),
276 }
277 }
278
279 async fn clunk(&self, fid: Fid, caller: &Subject) {
280 if let Ok(mut state) = fid.downcast_into::<CanonicalFid>() {
281 if let (Some(target), Some(inner)) = (state.target.take(), state.inner.take()) {
282 target.clunk(inner, caller).await;
283 }
284 }
285 }
286}
287
288#[cfg(test)]
289#[allow(clippy::unwrap_used)]
290mod tests {
291 use super::{canonicalize_path, CanonicalReadMount};
292 use hyprstream_rpc::Subject;
293 use hyprstream_vfs::{Mount, MountError, SyntheticMount, SyntheticNode};
294 use std::sync::Arc;
295
296 #[test]
297 fn canonical_path_only_exports_one_repository_and_read_alias() {
298 let repo = "selected";
299 let worktree = "main";
300 assert_eq!(
301 canonicalize_path(repo, worktree, &[]).unwrap(),
302 Vec::<String>::new()
303 );
304 assert_eq!(
305 canonicalize_path(repo, worktree, &["worktree", "README"]).unwrap(),
306 ["srv", "registry", "selected", "main", "README"]
307 );
308 assert_eq!(
309 canonicalize_path(
310 repo,
311 worktree,
312 &["srv", "registry", "selected", "main", "README"]
313 )
314 .unwrap(),
315 ["srv", "registry", "selected", "main", "README"]
316 );
317 for denied in [
318 vec!["srv", "model"],
319 vec!["srv", "registry", "other", "main"],
320 vec!["srv", "registry", "selected", "other"],
321 vec!["worktree", "..", "private"],
322 vec!["srv", "registry", "selected", "main", ".."],
323 vec!["worktree", "a/b"],
324 vec!["private"],
325 ] {
326 assert!(
327 canonicalize_path(repo, worktree, &denied).is_err(),
328 "{denied:?}"
329 );
330 }
331 }
332
333 #[tokio::test]
334 async fn canonical_mount_rejects_a_different_holder_before_any_backing_walk() {
335 let backing: Arc<dyn Mount> = Arc::new(SyntheticMount::new(SyntheticNode::dir()));
336 let mount =
337 CanonicalReadMount::test_new(Subject::new("holder-a"), "selected", "main", backing);
338 assert!(matches!(
339 mount.walk(&[], &Subject::new("holder-b")).await,
340 Err(MountError::PermissionDenied(_))
341 ));
342 }
343}