Skip to main content

qualia_solid_bridge/
pod_store.rs

1//! Filesystem-backed Solid LDP resource store for a personal pod.
2//!
3//! Layout under `root`:
4//! ```text
5//! profile/card          WebID profile (Turtle)
6//! public/               Public container
7//! private/              Private container
8//! inbox/                LDN inbox container
9//! ```
10//!
11//! Paths are URL-decoded relative paths with `..` rejected (fail-closed).
12
13use std::fs;
14use std::io::{self, Write};
15use std::path::{Component, Path, PathBuf};
16
17/// Safe personal-pod root on disk.
18#[derive(Debug, Clone)]
19pub struct PodStore {
20    root: PathBuf,
21}
22
23impl PodStore {
24    /// Creates a new instance.
25    pub fn new(root: impl Into<PathBuf>) -> Self {
26        Self { root: root.into() }
27    }
28
29    /// Root.
30    pub fn root(&self) -> &Path {
31        &self.root
32    }
33
34    /// Create root + default containers, WebID profile, and seed Solid stack ontologies.
35    pub fn ensure_defaults(&self, public_base: &str) -> io::Result<()> {
36        fs::create_dir_all(self.root.join("profile"))?;
37        fs::create_dir_all(self.root.join("public"))?;
38        fs::create_dir_all(self.root.join("private"))?;
39        fs::create_dir_all(self.root.join("inbox"))?;
40        fs::create_dir_all(self.root.join("public").join("ontologies"))?;
41
42        let card = self.root.join("profile").join("card");
43        if !card.exists() {
44            let webid = format!("{}/profile/card#me", public_base.trim_end_matches('/'));
45            let issuer = public_base.trim_end_matches('/');
46            // IRIs from bundled W3C ns archives (ldp, solid/terms, pim/space, foaf).
47            let body = format!(
48                r#"@prefix foaf: <{foaf}> .
49@prefix solid: <{solid}> .
50@prefix pim: <{pim}> .
51@prefix ldp: <{ldp}> .
52
53<#me> a foaf:Person ;
54    foaf:name "Local Webizen" ;
55    solid:oidcIssuer <{issuer}> ;
56    pim:storage <{base}/> ;
57    ldp:inbox <{base}/inbox/> .
58
59<{webid}> a foaf:Person .
60"#,
61                foaf = crate::vocab::NS_FOAF,
62                solid = crate::vocab::NS_SOLID,
63                pim = crate::vocab::NS_PIM_SPACE,
64                ldp = crate::vocab::NS_LDP,
65                issuer = issuer,
66                base = issuer,
67                webid = webid,
68            );
69            let mut f = fs::File::create(&card)?;
70            f.write_all(body.as_bytes())?;
71        }
72
73        // Empty container markers so clients can discover trees.
74        for dir in ["public", "private", "inbox"] {
75            let marker = self.root.join(dir).join(".meta");
76            if !marker.exists() {
77                let mut f = fs::File::create(marker)?;
78                writeln!(
79                    f,
80                    "@prefix ldp: <{}> .\n<> a ldp:BasicContainer .",
81                    crate::vocab::NS_LDP
82                )?;
83            }
84        }
85
86        self.seed_bundled_ontologies()?;
87        Ok(())
88    }
89
90    /// Copy LDP / Solid / WAC / PIM / FOAF ontology files into the pod so clients
91    /// can fetch them offline from `/public/ontologies/`.
92    pub fn seed_bundled_ontologies(&self) -> io::Result<()> {
93        let ont_dir = self.root.join("public").join("ontologies");
94        fs::create_dir_all(&ont_dir)?;
95        let mut index = String::from(
96            "@prefix ldp: <http://www.w3.org/ns/ldp#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n<> a ldp:BasicContainer .\n",
97        );
98        for (file, label) in crate::vocab::POD_ONTOLOGY_FILES {
99            let dest = ont_dir.join(file);
100            if !dest.exists() {
101                if let Some(src) = crate::vocab::resolve_ontology_source(file) {
102                    if let Err(e) = fs::copy(&src, &dest) {
103                        eprintln!(
104                            "solid-bridge: could not seed ontology {file} from {}: {e}",
105                            src.display()
106                        );
107                        continue;
108                    }
109                } else {
110                    eprintln!("solid-bridge: ontology source not found: {file}");
111                    continue;
112                }
113            }
114            if dest.exists() {
115                index.push_str(&format!(
116                    "<> ldp:contains <{file}> .\n<{file}> rdfs:label \"{label}\" .\n"
117                ));
118            }
119        }
120        let idx_path = ont_dir.join(".meta");
121        fs::write(idx_path, index)?;
122        Ok(())
123    }
124
125    /// Resolve a URL path (`/public/foo.ttl`) to an absolute filesystem path.
126    pub fn resolve(&self, url_path: &str) -> io::Result<PathBuf> {
127        let trimmed = url_path.trim_start_matches('/');
128        if trimmed.is_empty() {
129            return Ok(self.root.clone());
130        }
131        let mut out = self.root.clone();
132        for comp in Path::new(trimmed).components() {
133            match comp {
134                Component::Normal(s) => out.push(s),
135                Component::CurDir => {}
136                Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
137                    return Err(io::Error::new(
138                        io::ErrorKind::PermissionDenied,
139                        "path traversal rejected",
140                    ));
141                }
142            }
143        }
144        // Must stay under root
145        let canon_root = self
146            .root
147            .canonicalize()
148            .unwrap_or_else(|_| self.root.clone());
149        if let Ok(canon) = out.canonicalize() {
150            if !canon.starts_with(&canon_root) {
151                return Err(io::Error::new(
152                    io::ErrorKind::PermissionDenied,
153                    "path escapes pod root",
154                ));
155            }
156        } else {
157            // Parent must be under root for create
158            if let Some(parent) = out.parent() {
159                if parent.exists() {
160                    let cp = parent.canonicalize()?;
161                    if !cp.starts_with(&canon_root) {
162                        return Err(io::Error::new(
163                            io::ErrorKind::PermissionDenied,
164                            "path escapes pod root",
165                        ));
166                    }
167                }
168            }
169        }
170        Ok(out)
171    }
172
173    /// Reads bytes.
174    pub fn read_bytes(&self, url_path: &str) -> io::Result<Vec<u8>> {
175        let path = self.resolve(url_path)?;
176        if path.is_dir() {
177            return Ok(self.container_listing_turtle(url_path)?.into_bytes());
178        }
179        fs::read(path)
180    }
181
182    /// Writes bytes.
183    pub fn write_bytes(&self, url_path: &str, body: &[u8]) -> io::Result<()> {
184        let path = self.resolve(url_path)?;
185        if let Some(parent) = path.parent() {
186            fs::create_dir_all(parent)?;
187        }
188        fs::write(path, body)
189    }
190
191    /// Deletes.
192    pub fn delete(&self, url_path: &str) -> io::Result<()> {
193        let path = self.resolve(url_path)?;
194        if path.is_dir() {
195            fs::remove_dir_all(path)
196        } else if path.exists() {
197            fs::remove_file(path)
198        } else {
199            Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
200        }
201    }
202
203    /// `true` when it exists.
204    pub fn exists(&self, url_path: &str) -> bool {
205        self.resolve(url_path).map(|p| p.exists()).unwrap_or(false)
206    }
207
208    /// `true` when container.
209    pub fn is_container(&self, url_path: &str) -> bool {
210        self.resolve(url_path)
211            .map(|p| p.is_dir() || url_path.ends_with('/'))
212            .unwrap_or(false)
213    }
214
215    /// Minimal LDP BasicContainer listing as Turtle.
216    pub fn container_listing_turtle(&self, url_path: &str) -> io::Result<String> {
217        let path = self.resolve(url_path)?;
218        let mut out = String::from(
219            "@prefix ldp: <http://www.w3.org/ns/ldp#> .\n@prefix dcterms: <http://purl.org/dc/terms/> .\n\n<> a ldp:BasicContainer, ldp:Container .\n",
220        );
221        if path.is_dir() {
222            for entry in fs::read_dir(&path)? {
223                let entry = entry?;
224                let name = entry.file_name().to_string_lossy().into_owned();
225                if name.starts_with('.') {
226                    continue;
227                }
228                let slash = if entry.path().is_dir() { "/" } else { "" };
229                out.push_str(&format!("<> ldp:contains <{}{}> .\n", name, slash));
230            }
231        }
232        Ok(out)
233    }
234
235    /// Guess content-type from path suffix.
236    pub fn content_type_for(url_path: &str) -> &'static str {
237        let lower = url_path.to_ascii_lowercase();
238        if lower.ends_with(".json") || lower.ends_with(".jsonld") {
239            "application/ld+json"
240        } else if lower.ends_with(".acl") || lower.ends_with(".ttl") || !lower.contains('.') {
241            "text/turtle"
242        } else if lower.ends_with(".html") {
243            "text/html"
244        } else {
245            "application/octet-stream"
246        }
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use std::env;
254
255    #[test]
256    fn rejects_traversal_and_round_trips() {
257        let dir = env::temp_dir().join(format!("qualia-pod-{}", std::process::id()));
258        let _ = fs::remove_dir_all(&dir);
259        let store = PodStore::new(&dir);
260        store.ensure_defaults("http://127.0.0.1:4243").unwrap();
261
262        store
263            .write_bytes("/public/hello.ttl", b"<a> <b> <c> .")
264            .unwrap();
265        let got = store.read_bytes("/public/hello.ttl").unwrap();
266        assert_eq!(got, b"<a> <b> <c> .");
267
268        assert!(
269            store.resolve("/public/../profile/card").is_err()
270                || store
271                    .resolve("/public/../profile/card")
272                    .map(|p| p.starts_with(&dir.join("profile")))
273                    .unwrap_or(false)
274        );
275
276        // Explicit parent components rejected
277        assert!(store.resolve("/../etc/passwd").is_err());
278
279        let listing = String::from_utf8(store.read_bytes("/public/").unwrap()).unwrap();
280        assert!(listing.contains("ldp:BasicContainer"));
281        assert!(listing.contains("hello.ttl"));
282
283        let _ = fs::remove_dir_all(&dir);
284    }
285}