cedarling 0.0.58

The Cedarling: a high-performance local authorization service powered by the Rust Cedar Engine.
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

//! Archive VFS implementation for .cjar policy store archives.
//!
//! This module provides a VFS implementation backed by ZIP archives, enabling
//! policy stores to be distributed as single `.cjar` files. The implementation:
//!
//! - **Fully WASM-compatible** - `from_buffer()` works in both native and WASM
//! - Reads files on-demand from the archive (no extraction needed)
//! - Validates archive format and structure during construction
//! - Prevents path traversal attacks
//! - Provides full [`VfsFileSystem`] trait implementation
//!
//! # WASM Support
//!
//! Archives are **fully supported in WASM**:
//! - Use `ArchiveVfs::from_buffer()` with bytes you fetch (works now)
//! - Use `ArchiveSource::Url` with `load_policy_store()` (once URL fetching is implemented)
//! - Only `from_file()` is native-only (requires file system access)
use super::errors::ArchiveError;
use super::vfs_adapter::{DirEntry, VfsFileSystem};
use std::io::{Cursor, Read, Seek};
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::sync::Mutex;
use zip::ZipArchive;

/// VFS implementation backed by a ZIP archive.
///
/// This implementation reads files on-demand from a ZIP archive without extraction,
/// making it efficient and WASM-compatible. The archive is validated during construction
/// to ensure it's a valid .cjar file with no path traversal attempts.
///
/// # Thread Safety
///
/// This type is `Send + Sync` despite using `Mutex` because the `ZipArchive` is protected
/// by a mutex. Concurrent access is prevented by the Mutex locking mechanism.
///
/// # Generic Type Parameter
///
/// The generic type `T` must implement `Read + Seek` and represents the underlying
/// reader for the ZIP archive. Common types:
/// - `Cursor<Vec<u8>>` - For in-memory archives (WASM-compatible)
/// - `std::fs::File` - For file-based archives (native only)
#[derive(Debug)]
pub(super) struct ArchiveVfs<T> {
    /// The ZIP archive reader (wrapped in Mutex for thread safety)
    archive: Mutex<ZipArchive<T>>,
}

impl<T> ArchiveVfs<T>
where
    T: Read + Seek,
{
    /// Create an [`ArchiveVfs`] from a reader.
    ///
    /// This method:
    /// 1. Validates the reader contains a valid ZIP archive
    /// 2. Checks for path traversal attempts
    /// 3. Validates archive structure
    ///
    /// # Errors
    ///
    /// Returns `ArchiveError` if:
    /// - Reader does not contain a valid ZIP archive
    /// - Archive contains path traversal attempts
    /// - Archive is corrupted
    pub(super) fn from_reader(reader: T) -> Result<Self, ArchiveError> {
        let mut archive = ZipArchive::new(reader).map_err(|e| ArchiveError::InvalidZipFormat {
            details: e.to_string(),
        })?;

        // Validate all file names for security
        for i in 0..archive.len() {
            let file = archive
                .by_index(i)
                .map_err(|e| ArchiveError::CorruptedEntry {
                    index: i,
                    details: e.to_string(),
                })?;

            let file_name = file.name();

            // Explicitly reject absolute paths (Unix-style or Windows-style)
            // Note: enclosed_name() behavior is inconsistent across environments -
            // it may return Some("etc/passwd") on some systems and None on others.
            // We explicitly check for absolute paths to ensure consistent behavior.
            if file_name.starts_with('/') || file_name.starts_with('\\') {
                return Err(ArchiveError::PathTraversal {
                    path: file_name.to_string(),
                });
            }

            // Check for Windows-style absolute paths (e.g., "C:\", "D:/")
            if file_name.len() >= 2 {
                let mut chars = file_name.chars();
                if let (Some(first), Some(second)) = (chars.next(), chars.next())
                    && first.is_ascii_alphabetic()
                    && second == ':'
                {
                    return Err(ArchiveError::PathTraversal {
                        path: file_name.to_string(),
                    });
                }
            }

            // Use enclosed_name() to validate and normalize the path
            // This handles path traversal patterns like "../"
            let normalized = file.enclosed_name();
            if let Some(normalized_path) = normalized {
                // Additional check: ensure normalized path doesn't contain .. sequences
                let path_str = normalized_path.to_string_lossy();
                if path_str.contains("..") {
                    return Err(ArchiveError::PathTraversal {
                        path: file_name.to_string(),
                    });
                }
            } else {
                return Err(ArchiveError::PathTraversal {
                    path: file_name.to_string(),
                });
            }
        }

        Ok(Self {
            archive: Mutex::new(archive),
        })
    }
}

impl ArchiveVfs<std::fs::File> {
    /// Create an [`ArchiveVfs`] from a file path (native only).
    ///
    /// This method:
    /// 1. Validates the file has .cjar extension
    /// 2. Opens the file
    /// 3. Validates it's a valid ZIP archive
    /// 4. Checks for path traversal attempts
    ///
    /// # Errors
    ///
    /// Returns `ArchiveError` if:
    /// - File extension is not .cjar
    /// - File cannot be read
    /// - Archive is not a valid ZIP
    /// - Archive contains path traversal attempts
    /// - Archive is corrupted
    #[cfg(not(target_arch = "wasm32"))]
    pub(super) fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, ArchiveError> {
        let path = path.as_ref();

        // Validate extension
        if path.extension().and_then(|s| s.to_str()) != Some("cjar") {
            return Err(ArchiveError::InvalidExtension {
                expected: "cjar".to_string(),
                found: path
                    .extension()
                    .and_then(|s| s.to_str())
                    .unwrap_or("(none)")
                    .to_string(),
            });
        }

        let file = std::fs::File::open(path).map_err(|e| ArchiveError::CannotReadFile {
            path: path.display().to_string(),
            source: e,
        })?;

        Self::from_reader(file)
    }
}

impl ArchiveVfs<Cursor<Vec<u8>>> {
    /// Create an [`ArchiveVfs`] from bytes (works in WASM and native).
    ///
    /// This method:
    /// 1. Validates the bytes form a valid ZIP archive
    /// 2. Checks for path traversal attempts
    /// 3. Validates archive structure
    ///
    /// # Errors
    ///
    /// Returns `ArchiveError` if:
    /// - Bytes are not a valid ZIP archive
    /// - Archive contains path traversal attempts
    /// - Archive is corrupted
    pub(super) fn from_buffer(buffer: Vec<u8>) -> Result<Self, ArchiveError> {
        let cursor = Cursor::new(buffer);
        Self::from_reader(cursor)
    }
}

impl<T> ArchiveVfs<T>
where
    T: Read + Seek,
{
    /// Normalize a path for archive lookup.
    ///
    /// Handles:
    /// - Converting absolute paths to relative
    /// - Removing leading slashes
    /// - Removing leading "./" prefix
    /// - Converting "." to ""
    /// - Normalizing path separators
    fn normalize_path(path: &str) -> String {
        let path = path.trim_start_matches('/');
        let path = path.strip_prefix("./").unwrap_or(path);
        if path == "." || path.is_empty() {
            String::new()
        } else {
            path.to_string()
        }
    }

    /// Check if a path exists in the archive (file or directory).
    fn path_exists(&self, path: &str) -> Result<bool, std::io::Error> {
        let normalized = Self::normalize_path(path);

        let mut archive = self
            .archive
            .lock()
            .map_err(|e| std::io::Error::other(format!("archive mutex poisoned: {e}")))?;

        // Check if it's a file
        if archive.by_name(&normalized).is_ok() {
            return Ok(true);
        }

        // Check if it's a directory by looking for entries that start with this prefix
        let dir_prefix = if normalized.is_empty() {
            String::new()
        } else {
            format!("{normalized}/")
        };

        for i in 0..archive.len() {
            if let Ok(file) = archive.by_index(i) {
                let file_name = file.name();
                if file_name == normalized || file_name.starts_with(&dir_prefix) {
                    return Ok(true);
                }
            }
        }

        Ok(false)
    }

    /// Check if a path is a file in the archive.
    #[cfg(test)]
    pub(super) fn is_file(&self, path: &str) -> bool {
        let normalized = Self::normalize_path(path);
        let Ok(mut archive) = self.archive.lock() else {
            return false;
        };

        if let Ok(file) = archive.by_name(&normalized) {
            return file.is_file();
        }

        false
    }

    /// Check if a path is a directory in the archive.
    fn is_directory(&self, path: &str) -> Result<bool, std::io::Error> {
        let normalized = Self::normalize_path(path);
        let mut archive = self
            .archive
            .lock()
            .map_err(|e| std::io::Error::other(format!("archive mutex poisoned: {e}")))?;
        Ok(Self::is_directory_locked(&mut archive, &normalized))
    }

    /// Check if a path is a directory (with already-locked archive).
    /// This is a helper to avoid deadlocks when called from methods that already hold the lock.
    fn is_directory_locked(archive: &mut ZipArchive<T>, normalized: &str) -> bool {
        // Root is always a directory
        if normalized.is_empty() {
            return true;
        }

        // Check if there's an explicit directory entry
        let dir_path_with_slash = format!("{normalized}/");
        if let Ok(file) = archive.by_name(&dir_path_with_slash) {
            return file.is_dir();
        }

        // Check if any files have this as a prefix (implicit directory)
        for i in 0..archive.len() {
            if let Ok(file) = archive.by_index(i) {
                let file_name = file.name();
                if file_name.starts_with(&format!("{normalized}/")) {
                    return true;
                }
            }
        }

        false
    }
}

impl<T> VfsFileSystem for ArchiveVfs<T>
where
    T: Read + Seek + Send + Sync + 'static,
{
    fn read_file(&self, path: &str) -> Result<Vec<u8>, std::io::Error> {
        let normalized = Self::normalize_path(path);

        let mut archive = self
            .archive
            .lock()
            .map_err(|e| std::io::Error::other(format!("archive mutex poisoned: {e}")))?;

        let mut file = archive.by_name(&normalized).map_err(|e| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("File not found in archive: {path}: {e}"),
            )
        })?;

        let mut contents = Vec::new();
        file.read_to_end(&mut contents)?;

        Ok(contents)
    }

    fn exists(&self, path: &str) -> bool {
        self.path_exists(path).unwrap_or(false)
    }

    fn is_dir(&self, path: &str) -> bool {
        self.is_directory(path).unwrap_or(false)
    }

    fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, std::io::Error> {
        let normalized = Self::normalize_path(path);
        let prefix = if normalized.is_empty() {
            String::new()
        } else {
            format!("{normalized}/")
        };

        let mut archive = self
            .archive
            .lock()
            .map_err(|e| std::io::Error::other(format!("archive mutex poisoned: {e}")))?;
        let mut seen = std::collections::HashSet::new();
        let mut entry_paths = Vec::new();

        // First pass: collect all unique entry paths
        for i in 0..archive.len() {
            let file = archive.by_index(i).map_err(|e| {
                std::io::Error::other(format!("Failed to read archive entry {i}: {e}"))
            })?;

            let file_name = file.name();

            // Check if this file is in the requested directory
            if file_name.starts_with(&prefix) || (prefix.is_empty() && !file_name.contains('/')) {
                let relative = if prefix.is_empty() {
                    file_name
                } else {
                    &file_name[prefix.len()..]
                };

                // Get the immediate child name (first component)
                let child_name = if let Some(slash_pos) = relative.find('/') {
                    &relative[..slash_pos]
                } else {
                    relative
                };

                // Skip empty names and deduplicate
                if child_name.is_empty() || !seen.insert(child_name.to_string()) {
                    continue;
                }

                // Determine the full path for this entry
                let entry_path = if prefix.is_empty() {
                    child_name.to_string()
                } else {
                    format!("{prefix}{child_name}")
                };

                entry_paths.push((child_name.to_string(), entry_path));
            }
        }

        // Second pass: check if each path is a directory
        let mut entries = Vec::new();
        for (name, entry_path) in entry_paths {
            let entry_path_normalized = Self::normalize_path(&entry_path);
            let is_directory = Self::is_directory_locked(&mut archive, &entry_path_normalized);

            entries.push(DirEntry {
                name,
                path: entry_path,
                is_dir: is_directory,
            });
        }

        Ok(entries)
    }

    fn open_file(&self, path: &str) -> Result<Box<dyn Read + Send>, std::io::Error> {
        let bytes = self.read_file(path)?;
        Ok(Box::new(Cursor::new(bytes)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use zip::CompressionMethod;
    use zip::write::{ExtendedFileOptions, FileOptions};

    /// Helper to create a test .cjar archive in memory
    fn create_test_archive(files: Vec<(&str, &str)>) -> Vec<u8> {
        let mut buffer = Vec::new();
        {
            let cursor = Cursor::new(&mut buffer);
            let mut zip = zip::ZipWriter::new(cursor);

            for (name, content) in files {
                let options = FileOptions::<ExtendedFileOptions>::default()
                    .compression_method(CompressionMethod::Deflated);
                zip.start_file(name, options).unwrap();
                zip.write_all(content.as_bytes()).unwrap();
            }

            zip.finish().unwrap();
        }
        buffer
    }

    #[test]
    fn test_from_buffer_valid_archive() {
        let bytes = create_test_archive(vec![("metadata.json", "{}")]);
        let _result = ArchiveVfs::from_buffer(bytes)
            .expect("expect ArchiveVfs initialized correctly from buffer");
    }

    #[test]
    fn test_from_buffer_invalid_zip() {
        let bytes = b"This is not a ZIP file".to_vec();
        let result = ArchiveVfs::from_buffer(bytes);
        let err = result.expect_err("Expected InvalidZipFormat error for non-ZIP data");
        assert!(
            matches!(err, ArchiveError::InvalidZipFormat { .. }),
            "Expected InvalidZipFormat error, got: {err:?}"
        );
    }

    #[test]
    fn test_from_buffer_path_traversal() {
        let bytes = create_test_archive(vec![("../../../etc/passwd", "malicious")]);
        let result = ArchiveVfs::from_buffer(bytes);
        let err = result.expect_err("Expected PathTraversal error for malicious path");
        assert!(
            matches!(err, ArchiveError::PathTraversal { .. }),
            "Expected PathTraversal error, got: {err:?}"
        );
    }

    #[test]
    fn test_read_file_success() {
        let bytes = create_test_archive(vec![
            ("metadata.json", r#"{"version":"1.0"}"#),
            ("schema.cedarschema", "namespace Test;"),
        ]);
        let vfs = ArchiveVfs::from_buffer(bytes).unwrap();

        let content = vfs.read_file("metadata.json").unwrap();
        assert_eq!(String::from_utf8(content).unwrap(), r#"{"version":"1.0"}"#);

        let content = vfs.read_file("schema.cedarschema").unwrap();
        assert_eq!(String::from_utf8(content).unwrap(), "namespace Test;");
    }

    #[test]
    fn test_read_file_not_found() {
        let bytes = create_test_archive(vec![("metadata.json", "{}")]);
        let vfs = ArchiveVfs::from_buffer(bytes).unwrap();

        let result = vfs.read_file("nonexistent.json");
        let err = result.expect_err("Expected error for nonexistent file");
        assert!(
            matches!(err, std::io::Error { .. }),
            "Expected IO error for file not found"
        );
    }

    #[test]
    fn test_exists() {
        let bytes = create_test_archive(vec![
            ("metadata.json", "{}"),
            ("policies/policy1.cedar", "permit();"),
        ]);
        let vfs = ArchiveVfs::from_buffer(bytes).unwrap();

        assert!(vfs.exists("metadata.json"));
        assert!(vfs.exists("policies/policy1.cedar"));
        assert!(vfs.exists("policies")); // directory
        assert!(!vfs.exists("nonexistent.json"));
    }

    #[test]
    fn test_is_file() {
        let bytes = create_test_archive(vec![
            ("metadata.json", "{}"),
            ("policies/policy1.cedar", "permit();"),
        ]);
        let vfs = ArchiveVfs::from_buffer(bytes).unwrap();

        assert!(vfs.is_file("metadata.json"));
        assert!(vfs.is_file("policies/policy1.cedar"));
        assert!(!vfs.is_file("policies"));
        assert!(!vfs.is_file("nonexistent.json"));
    }

    #[test]
    fn test_is_dir() {
        let bytes = create_test_archive(vec![
            ("metadata.json", "{}"),
            ("policies/policy1.cedar", "permit();"),
            ("policies/policy2.cedar", "forbid();"),
        ]);
        let vfs = ArchiveVfs::from_buffer(bytes).unwrap();

        assert!(vfs.is_dir("."));
        assert!(vfs.is_dir("policies"));
        assert!(!vfs.is_dir("metadata.json"));
        assert!(!vfs.is_dir("nonexistent"));
    }

    #[test]
    fn test_read_dir_root() {
        let bytes = create_test_archive(vec![
            ("metadata.json", "{}"),
            ("schema.cedarschema", "namespace Test;"),
            ("policies/policy1.cedar", "permit();"),
        ]);
        let vfs = ArchiveVfs::from_buffer(bytes).unwrap();

        let entries = vfs.read_dir(".").unwrap();
        assert_eq!(entries.len(), 3);

        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"metadata.json"));
        assert!(names.contains(&"schema.cedarschema"));
        assert!(names.contains(&"policies"));
    }

    #[test]
    fn test_read_dir_subdirectory() {
        let bytes = create_test_archive(vec![
            ("policies/policy1.cedar", "permit();"),
            ("policies/policy2.cedar", "forbid();"),
            ("policies/nested/policy3.cedar", "deny();"),
        ]);
        let vfs = ArchiveVfs::from_buffer(bytes).unwrap();

        let entries = vfs.read_dir("policies").unwrap();
        assert_eq!(entries.len(), 3);

        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"policy1.cedar"));
        assert!(names.contains(&"policy2.cedar"));
        assert!(names.contains(&"nested"));
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_from_file_path_invalid_extension() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let archive_path = temp_dir.path().join("test.zip");

        let bytes = create_test_archive(vec![("metadata.json", "{}")]);
        std::fs::write(&archive_path, bytes).unwrap();

        let result = ArchiveVfs::from_file(&archive_path);
        assert!(matches!(
            result.expect_err("should fail"),
            ArchiveError::InvalidExtension { .. }
        ));
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_from_file_path_success() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let archive_path = temp_dir.path().join("test.cjar");

        let bytes = create_test_archive(vec![("metadata.json", "{}")]);
        std::fs::write(&archive_path, bytes).unwrap();

        ArchiveVfs::from_file(&archive_path).expect("should load valid .cjar file");
    }

    #[test]
    fn test_complex_directory_structure() {
        let bytes = create_test_archive(vec![
            ("metadata.json", "{}"),
            ("policies/allow/policy1.cedar", "permit();"),
            ("policies/allow/policy2.cedar", "permit();"),
            ("policies/deny/policy3.cedar", "forbid();"),
            ("entities/users/admin.json", "{}"),
            ("entities/users/regular.json", "{}"),
            ("entities/groups/admins.json", "{}"),
        ]);
        let vfs = ArchiveVfs::from_buffer(bytes).unwrap();

        // Test root
        let root_entries = vfs.read_dir(".").unwrap();
        assert_eq!(root_entries.len(), 3); // metadata.json, policies, entities

        // Test policies directory
        let policies_entries = vfs.read_dir("policies").unwrap();
        assert_eq!(policies_entries.len(), 2); // allow, deny

        // Test nested allow directory
        let allow_entries = vfs.read_dir("policies/allow").unwrap();
        assert_eq!(allow_entries.len(), 2); // policy1.cedar, policy2.cedar
    }
}