gobblytes-core 0.0.1

Filesystem traits, OSTree path wrapper, and shared test helpers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#![no_std]
#![allow(async_fn_in_trait)]

extern crate alloc;

use alloc::{
    collections::{BTreeMap, VecDeque},
    format,
    string::{String, ToString},
    vec::Vec,
};
use core::fmt;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FilesystemEntryType {
    File,
    Directory,
    Symlink,
    Other,
}

/// Minimal VFS-like access to a filesystem tree.
pub trait Filesystem {
    type Error;

    /// Read the full contents of a file at `path` (absolute or relative to root).
    async fn read_all(&self, path: &str) -> Result<Vec<u8>, Self::Error>;

    /// Read a range of bytes from a file at `path`.
    async fn read_range(&self, path: &str, offset: u64, len: usize)
    -> Result<Vec<u8>, Self::Error>;

    /// List entries (file/dir names) in a directory at `path`.
    async fn read_dir(&self, path: &str) -> Result<Vec<String>, Self::Error>;

    /// Return entry type for a path without following symlinks.
    ///
    /// Returns `Ok(None)` when the path does not exist.
    async fn entry_type(&self, path: &str) -> Result<Option<FilesystemEntryType>, Self::Error>;

    /// Read symlink target bytes as UTF-8 text.
    ///
    /// Implementations should return an error when `path` is not a symlink.
    async fn read_link(&self, path: &str) -> Result<String, Self::Error>;

    /// Check if a path exists.
    async fn exists(&self, path: &str) -> Result<bool, Self::Error>;
}

const MAX_SYMLINK_HOPS: usize = 32;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OstreeError {
    message: String,
}

impl OstreeError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for OstreeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

#[derive(Clone)]
pub struct OstreeFs<P> {
    inner: P,
    deployment_root: String,
}

pub fn normalize_ostree_deployment_path(path: &str) -> Result<String, OstreeError> {
    let trimmed = path.trim();
    if trimmed.is_empty() {
        return Err(OstreeError::new("ostree path is empty"));
    }

    let mut components = Vec::new();
    for component in trimmed.split('/') {
        match component {
            "" | "." => {}
            ".." => {
                return Err(OstreeError::new(format!(
                    "ostree path must not contain '..': {trimmed}"
                )));
            }
            _ => components.push(component.to_string()),
        }
    }

    if components.is_empty() {
        return Err(OstreeError::new("ostree path resolves to root or empty"));
    }

    Ok(components.join("/"))
}

fn split_non_parent_components(path: &str) -> Result<Vec<String>, OstreeError> {
    let trimmed = path.trim();
    if trimmed.is_empty() {
        return Err(OstreeError::new("path is empty"));
    }

    let mut components = Vec::new();
    for component in trimmed.split('/') {
        match component {
            "" | "." => {}
            ".." => {
                return Err(OstreeError::new(format!(
                    "path must not contain '..': {trimmed}"
                )));
            }
            _ => components.push(component.to_string()),
        }
    }
    Ok(components)
}

fn apply_path_target(base: &mut Vec<String>, target: &str) -> Result<(), OstreeError> {
    let trimmed = target.trim();
    if trimmed.is_empty() {
        return Err(OstreeError::new("symlink target is empty"));
    }

    if trimmed.starts_with('/') {
        base.clear();
    }

    for component in trimmed.split('/') {
        match component {
            "" | "." => {}
            ".." => {
                base.pop();
            }
            _ => base.push(component.to_string()),
        }
    }

    Ok(())
}

impl<P> OstreeFs<P> {
    pub fn new(inner: P, deployment_path: &str) -> Result<Self, OstreeError> {
        let deployment_root = normalize_ostree_deployment_path(deployment_path)?;
        Ok(Self {
            inner,
            deployment_root,
        })
    }

    fn map_path(&self, path: &str) -> String {
        let suffix = path.trim().trim_start_matches('/');
        if suffix.is_empty() {
            format!("/{}", self.deployment_root)
        } else {
            format!("/{}/{}", self.deployment_root, suffix)
        }
    }
}

impl<P> OstreeFs<P>
where
    P: Filesystem,
    P::Error: fmt::Display,
{
    pub async fn resolve_deployment_path(
        inner: &P,
        deployment_path: &str,
    ) -> Result<String, OstreeError> {
        let normalized = normalize_ostree_deployment_path(deployment_path)?;
        let normalized_abs = format!("/{normalized}");
        let mut remaining = split_non_parent_components(&normalized_abs)?
            .into_iter()
            .collect::<VecDeque<_>>();
        let mut resolved = Vec::new();
        let mut symlink_hops = 0usize;

        while let Some(component) = remaining.pop_front() {
            resolved.push(component);
            let current_path = format!("/{}", resolved.join("/"));
            let entry_type = inner
                .entry_type(&current_path)
                .await
                .map_err(|err| OstreeError::new(format!("read entry type {current_path}: {err}")))?
                .ok_or_else(|| OstreeError::new(format!("missing path {current_path}")))?;

            if entry_type != FilesystemEntryType::Symlink {
                continue;
            }

            symlink_hops += 1;
            if symlink_hops > MAX_SYMLINK_HOPS {
                return Err(OstreeError::new(format!(
                    "symlink resolution exceeded {MAX_SYMLINK_HOPS} hops for {deployment_path}"
                )));
            }

            let link_target = inner.read_link(&current_path).await.map_err(|err| {
                OstreeError::new(format!("read symlink target {current_path}: {err}"))
            })?;
            resolved.pop();
            apply_path_target(&mut resolved, &link_target)?;

            let mut rewritten = resolved.into_iter().collect::<VecDeque<_>>();
            rewritten.extend(remaining.into_iter());
            remaining = rewritten;
            resolved = Vec::new();
        }

        let resolved_path = if resolved.is_empty() {
            "/".to_string()
        } else {
            format!("/{}", resolved.join("/"))
        };
        let resolved_type = inner
            .entry_type(&resolved_path)
            .await
            .map_err(|err| OstreeError::new(format!("read entry type {resolved_path}: {err}")))?
            .ok_or_else(|| {
                OstreeError::new(format!(
                    "resolved ostree path does not exist: {resolved_path}"
                ))
            })?;
        if resolved_type != FilesystemEntryType::Directory {
            return Err(OstreeError::new(format!(
                "resolved ostree path is not a directory: {resolved_path}"
            )));
        }
        normalize_ostree_deployment_path(&resolved_path)
    }
}

impl<P> Filesystem for OstreeFs<P>
where
    P: Filesystem,
{
    type Error = P::Error;

    async fn read_all(&self, path: &str) -> Result<Vec<u8>, Self::Error> {
        let mapped = self.map_path(path);
        self.inner.read_all(&mapped).await
    }

    async fn read_range(
        &self,
        path: &str,
        offset: u64,
        len: usize,
    ) -> Result<Vec<u8>, Self::Error> {
        let mapped = self.map_path(path);
        self.inner.read_range(&mapped, offset, len).await
    }

    async fn read_dir(&self, path: &str) -> Result<Vec<String>, Self::Error> {
        let mapped = self.map_path(path);
        self.inner.read_dir(&mapped).await
    }

    async fn entry_type(&self, path: &str) -> Result<Option<FilesystemEntryType>, Self::Error> {
        let mapped = self.map_path(path);
        self.inner.entry_type(&mapped).await
    }

    async fn read_link(&self, path: &str) -> Result<String, Self::Error> {
        let mapped = self.map_path(path);
        self.inner.read_link(&mapped).await
    }

    async fn exists(&self, path: &str) -> Result<bool, Self::Error> {
        let mapped = self.map_path(path);
        self.inner.exists(&mapped).await
    }
}

#[derive(Clone, Debug, Default)]
pub struct MockFilesystem {
    entry_types: BTreeMap<String, FilesystemEntryType>,
    directories: BTreeMap<String, Vec<String>>,
    files: BTreeMap<String, Vec<u8>>,
    symlinks: BTreeMap<String, String>,
}

impl MockFilesystem {
    pub fn add_dir(&mut self, path: &str, entries: &[&str]) {
        self.entry_types
            .insert(path.to_string(), FilesystemEntryType::Directory);
        self.directories.insert(
            path.to_string(),
            entries.iter().map(|entry| (*entry).to_string()).collect(),
        );
    }

    pub fn add_file(&mut self, path: &str, data: &[u8]) {
        self.entry_types
            .insert(path.to_string(), FilesystemEntryType::File);
        self.files.insert(path.to_string(), data.to_vec());
    }

    pub fn add_symlink(&mut self, path: &str) {
        self.add_symlink_target(path, ".");
    }

    pub fn add_symlink_target(&mut self, path: &str, target: &str) {
        self.entry_types
            .insert(path.to_string(), FilesystemEntryType::Symlink);
        self.symlinks.insert(path.to_string(), target.to_string());
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MockFilesystemError {
    MissingPath(String),
    MissingDirectory(String),
    NotASymlink(String),
    OffsetOverflow(String),
}

impl fmt::Display for MockFilesystemError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingPath(path) => write!(f, "missing path {path}"),
            Self::MissingDirectory(path) => write!(f, "missing directory {path}"),
            Self::NotASymlink(path) => write!(f, "path is not a symlink: {path}"),
            Self::OffsetOverflow(path) => write!(f, "range offset exceeds usize for {path}"),
        }
    }
}

impl Filesystem for MockFilesystem {
    type Error = MockFilesystemError;

    async fn read_all(&self, path: &str) -> Result<Vec<u8>, Self::Error> {
        self.files
            .get(path)
            .cloned()
            .ok_or_else(|| MockFilesystemError::MissingPath(path.to_string()))
    }

    async fn read_range(
        &self,
        path: &str,
        offset: u64,
        len: usize,
    ) -> Result<Vec<u8>, Self::Error> {
        let data = self
            .files
            .get(path)
            .ok_or_else(|| MockFilesystemError::MissingPath(path.to_string()))?;
        let offset = usize::try_from(offset)
            .map_err(|_| MockFilesystemError::OffsetOverflow(path.to_string()))?;
        if offset >= data.len() {
            return Ok(Vec::new());
        }
        let end = (offset.saturating_add(len)).min(data.len());
        Ok(data[offset..end].to_vec())
    }

    async fn read_dir(&self, path: &str) -> Result<Vec<String>, Self::Error> {
        self.directories
            .get(path)
            .cloned()
            .ok_or_else(|| MockFilesystemError::MissingDirectory(path.to_string()))
    }

    async fn entry_type(&self, path: &str) -> Result<Option<FilesystemEntryType>, Self::Error> {
        Ok(self.entry_types.get(path).copied())
    }

    async fn read_link(&self, path: &str) -> Result<String, Self::Error> {
        self.symlinks
            .get(path)
            .cloned()
            .ok_or_else(|| MockFilesystemError::NotASymlink(path.to_string()))
    }

    async fn exists(&self, path: &str) -> Result<bool, Self::Error> {
        Ok(self.entry_types.contains_key(path) || self.directories.contains_key(path))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use futures::executor::block_on;

    #[test]
    fn normalize_ostree_path_removes_root_prefix_and_dots() {
        let path = normalize_ostree_deployment_path(" /ostree//boot.1/./fedora/123/0/ ").unwrap();
        assert_eq!(path, "ostree/boot.1/fedora/123/0");
    }

    #[test]
    fn normalize_ostree_path_rejects_parent_components() {
        let err = normalize_ostree_deployment_path("/ostree/../etc").unwrap_err();
        assert!(err.to_string().contains("must not contain '..'"));
    }

    #[test]
    fn apply_path_target_handles_relative_parent_segments() {
        let mut base = vec![
            "ostree".to_string(),
            "boot.1.1".to_string(),
            "live-pocket-fedora".to_string(),
            "bootcsum".to_string(),
        ];
        apply_path_target(
            &mut base,
            "../../../deploy/live-pocket-fedora/deploy/deadbeef.0",
        )
        .unwrap();
        assert_eq!(
            base,
            vec![
                "ostree".to_string(),
                "deploy".to_string(),
                "live-pocket-fedora".to_string(),
                "deploy".to_string(),
                "deadbeef.0".to_string()
            ]
        );
    }

    #[test]
    fn apply_path_target_replaces_base_on_absolute_targets() {
        let mut base = vec!["ostree".to_string(), "boot.1".to_string()];
        apply_path_target(&mut base, "/ostree/deploy/live-pocket-fedora").unwrap();
        assert_eq!(
            base,
            vec![
                "ostree".to_string(),
                "deploy".to_string(),
                "live-pocket-fedora".to_string()
            ]
        );
    }

    #[test]
    fn ostree_decorator_maps_paths_into_deployment_root() {
        let rootfs =
            OstreeFs::new(MockFilesystem::default(), "/ostree/boot.1/fedora/abc123/0").unwrap();
        assert_eq!(
            rootfs.map_path("/lib/modules"),
            "/ostree/boot.1/fedora/abc123/0/lib/modules"
        );
        assert_eq!(
            rootfs.map_path("usr/lib/modules"),
            "/ostree/boot.1/fedora/abc123/0/usr/lib/modules"
        );
        assert_eq!(rootfs.map_path("/"), "/ostree/boot.1/fedora/abc123/0");
    }

    #[test]
    fn resolve_deployment_path_follows_relative_symlink() {
        let mut fs = MockFilesystem::default();
        fs.add_dir("/ostree", &["boot.1", "deploy"]);
        fs.add_dir("/ostree/boot.1", &["fedora"]);
        fs.add_dir("/ostree/boot.1/fedora", &["abc"]);
        fs.add_dir("/ostree/boot.1/fedora/abc", &["0"]);
        fs.add_symlink_target(
            "/ostree/boot.1/fedora/abc/0",
            "../../../deploy/fedora/deploy/deadbeef.0",
        );
        fs.add_dir("/ostree/deploy", &["fedora"]);
        fs.add_dir("/ostree/deploy/fedora", &["deploy"]);
        fs.add_dir("/ostree/deploy/fedora/deploy", &["deadbeef.0"]);
        fs.add_dir("/ostree/deploy/fedora/deploy/deadbeef.0", &[]);

        let resolved = block_on(OstreeFs::resolve_deployment_path(
            &fs,
            "/ostree/boot.1/fedora/abc/0",
        ))
        .unwrap();
        assert_eq!(resolved, "ostree/deploy/fedora/deploy/deadbeef.0");
    }
}