atlas-cli 0.2.0

Machine Learning Lifecycle & Transparency Manager - Create and verify manifests for ML models and datasets
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
use crate::error::{Error, Result};
use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};

/// Ensures a file path is safe to use (not a symlink or hard link unless allowed)
///
/// # Examples
///
/// ```no_run
/// use atlas_cli::utils::safe_file_path;
/// use std::path::Path;
///
/// let path = Path::new("/tmp/safe_file.txt");
///
/// // Check path without allowing symlinks
/// match safe_file_path(&path, false) {
///     Ok(safe_path) => println!("Path is safe: {:?}", safe_path),
///     Err(e) => println!("Path is not safe: {}", e),
/// }
///
/// // Allow symlinks
/// let _ = safe_file_path(&path, true);
/// ```
pub fn safe_file_path(path: &Path, allow_symlinks: bool) -> Result<PathBuf> {
    // Check if the file exists
    if path.exists() {
        // Check if it's a symlink
        if path.is_symlink() {
            if !allow_symlinks {
                return Err(Error::Validation(format!(
                    "Security error: Path {} is a symlink, which is not allowed",
                    path.display()
                )));
            }

            // If symlinks are allowed, check the target is valid
            let target = fs::read_link(path)?;

            // Validate the target path (customize this logic based on your requirements)
            // For example, ensure it's within a specific directory
            if !is_safe_symlink_target(&target) {
                return Err(Error::Validation(format!(
                    "Security error: Symlink target {} is not in an allowed location",
                    target.display()
                )));
            }

            return Ok(target);
        }

        // Check for hard links (files with multiple links)
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            let metadata = fs::metadata(path)?;
            if metadata.nlink() > 1 {
                return Err(Error::Validation(format!(
                    "Security error: Path {} has multiple hard links ({})",
                    path.display(),
                    metadata.nlink()
                )));
            }
        }
    }

    // Path is safe or doesn't exist yet !
    Ok(path.to_path_buf())
}

/// Checks if a symlink target is in an allowed location
fn is_safe_symlink_target(target: &Path) -> bool {
    if let Ok(canonical) = target.canonicalize() {
        // Only allow /tmp or /var/app/data for now
        canonical.starts_with("/tmp") || canonical.starts_with("/var/app/data")
    } else {
        false
    }
}

/// Safely opens a file for reading
///
/// # Examples
///
/// ```no_run
/// use atlas_cli::utils::safe_open_file;
/// use std::path::Path;
/// use std::io::Read;
///
/// let path = Path::new("example.txt");
///
/// match safe_open_file(&path, false) {
///     Ok(mut file) => {
///         let mut contents = String::new();
///         file.read_to_string(&mut contents).unwrap();
///         println!("File contents: {}", contents);
///     }
///     Err(e) => eprintln!("Error opening file: {}", e),
/// }
/// ```
pub fn safe_open_file(path: &Path, allow_symlinks: bool) -> Result<File> {
    let safe_path = safe_file_path(path, allow_symlinks)?;
    File::open(&safe_path).map_err(Error::from)
}

/// Safely creates a file for writing
///
/// # Examples
///
/// ```no_run
/// use atlas_cli::utils::safe_create_file;
/// use std::path::Path;
/// use std::io::Write;
///
/// let path = Path::new("/tmp/new_file.txt");
///
/// match safe_create_file(&path, false) {
///     Ok(mut file) => {
///         file.write_all(b"Hello, World!").unwrap();
///         println!("File created successfully");
///     }
///     Err(e) => eprintln!("Error creating file: {}", e),
/// }
/// ```
pub fn safe_create_file(path: &Path, allow_symlinks: bool) -> Result<File> {
    let safe_path = safe_file_path(path, allow_symlinks)?;
    File::create(&safe_path).map_err(Error::from)
}

/// Safely opens a file with custom options
pub fn safe_open_options(path: &Path, allow_symlinks: bool) -> Result<OpenOptions> {
    let _safe_path = safe_file_path(path, allow_symlinks)?;
    Ok(OpenOptions::new())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Result;
    use std::fs::{self, File};
    use std::io::{Read, Write};
    use std::path::PathBuf;
    use tempfile::tempdir;

    #[test]
    fn test_safe_file_path_normal() -> Result<()> {
        // Test with a normal path
        let dir = tempdir()?;
        let normal_path = dir.path().join("test_file.txt");

        // Should return the same path
        let result = safe_file_path(&normal_path, false)?;
        assert_eq!(result, normal_path);

        Ok(())
    }

    #[test]
    fn test_safe_file_path_nonexistent() -> Result<()> {
        // Test with a nonexistent path
        let dir = tempdir()?;
        let nonexistent_path = dir.path().join("nonexistent_file.txt");

        // Should still return the path if it doesn't exist
        let result = safe_file_path(&nonexistent_path, false)?;
        assert_eq!(result, nonexistent_path);

        Ok(())
    }

    #[test]
    #[cfg(unix)] // This test is Unix-specific
    fn test_safe_file_path_symlink() -> Result<()> {
        // Create a temporary directory and files
        let dir = tempdir()?;
        let target_path = dir.path().join("target_file.txt");
        let symlink_path = dir.path().join("symlink_file.txt");

        // Create the target file
        let mut file = File::create(&target_path)?;
        file.write_all(b"target file content")?;

        // Create a symlink to the target
        std::os::unix::fs::symlink(&target_path, &symlink_path)?;

        // Test with symlinks not allowed (default)
        let result = safe_file_path(&symlink_path, false);
        assert!(result.is_err(), "Should reject symlinks when not allowed");

        // Test with symlinks allowed
        let result = safe_file_path(&symlink_path, true)?;

        // Should return the target path when symlinks are allowed
        assert_eq!(result, target_path);

        Ok(())
    }

    #[test]
    #[cfg(unix)] // This wnt work on Windows
    fn test_safe_file_path_unsafe_symlink() {
        // Test with a symlink to a potentially unsafe location
        let dir = tempdir().unwrap();
        let unsafe_target = PathBuf::from("/etc/passwd");
        let unsafe_symlink = dir.path().join("unsafe_symlink.txt");

        // Create a symlink to the unsafe target
        std::os::unix::fs::symlink(&unsafe_target, &unsafe_symlink).unwrap();

        // Even with symlinks allowed, should reject unsafe targets
        let result = safe_file_path(&unsafe_symlink, true);
        assert!(
            result.is_err(),
            "Should reject symlinks to unsafe locations"
        );
    }

    #[test]
    #[cfg(unix)] // This test is Unix-specific
    fn test_safe_file_path_hardlink() -> Result<()> {
        // Create a temporary directory and files
        let dir = tempdir()?;
        let target_path = dir.path().join("target_file.txt");
        let hardlink_path = dir.path().join("hardlink_file.txt");

        // Create the target file
        let mut file = File::create(&target_path)?;
        file.write_all(b"target file content")?;

        // Create a hard link to the target
        std::fs::hard_link(&target_path, &hardlink_path)?;

        // Hard links should be detected and rejected
        let result = safe_file_path(&hardlink_path, false);
        assert!(
            result.is_err(),
            "Should reject files with multiple hard links"
        );

        Ok(())
    }

    #[test]
    fn test_safe_open_file() -> Result<()> {
        // Create a temporary directory and file
        let dir = tempdir()?;
        let file_path = dir.path().join("test_open.txt");

        // Create and write to the file
        {
            let mut file = File::create(&file_path)?;
            file.write_all(b"test content")?;
        }

        // Test opening the file
        let mut file = safe_open_file(&file_path, false)?;
        let mut content = String::new();
        file.read_to_string(&mut content)?;

        // Should be able to read the content
        assert_eq!(content, "test content");

        Ok(())
    }

    #[test]
    fn test_safe_create_file() -> Result<()> {
        // Create a temporary directory
        let dir = tempdir()?;
        let file_path = dir.path().join("test_create.txt");

        // Test creating a file
        {
            let mut file = safe_create_file(&file_path, false)?;
            file.write_all(b"created content")?;
        }

        // Verify the file was created with the content
        let mut content = String::new();
        let mut file = File::open(&file_path)?;
        file.read_to_string(&mut content)?;

        assert_eq!(content, "created content");

        Ok(())
    }

    #[test]
    fn test_safe_open_options() -> Result<()> {
        // Create a temporary directory and file
        let dir = tempdir()?;
        let file_path = dir.path().join("test_options.txt");

        // Test creating with OpenOptions
        {
            let mut options = safe_open_options(&file_path, false)?;
            let mut file = options.write(true).create(true).open(&file_path)?;
            file.write_all(b"options content")?;
        }

        // Verify the file was created with the content
        let mut content = String::new();
        let mut file = File::open(&file_path)?;
        file.read_to_string(&mut content)?;

        assert_eq!(content, "options content");

        Ok(())
    }

    #[test]
    fn test_safe_open_file_nonexistent() {
        // Test opening a nonexistent file
        let nonexistent_path = PathBuf::from("/tmp/this_file_should_not_exist.txt");

        // Make sure the file doesn't exist
        if nonexistent_path.exists() {
            fs::remove_file(&nonexistent_path).unwrap();
        }

        let result = safe_open_file(&nonexistent_path, false);

        // Should return an error
        assert!(result.is_err());

        // The error should be an IO error
        if let Err(e) = result {
            match e {
                crate::error::Error::Io(_) => {} // Expected error type
                _ => panic!("Unexpected error type: {e:?}"),
            }
        }
    }

    #[test]
    fn test_is_safe_symlink_target() {
        let check_path = |path: &str| -> bool {
            let path = Path::new(path);
            if let Ok(canonical) = path.canonicalize() {
                canonical.starts_with("/tmp") || canonical.starts_with("/var/app/data")
            } else {
                // Simulate behavior for paths that can't be canonicalized
                false
            }
        };

        // Test a path that exists and should be allowed (tmpdir)
        let tmp_dir = tempdir().unwrap();
        assert!(
            check_path(tmp_dir.path().to_str().unwrap()),
            "Temporary directory should be considered safe"
        );

        // Test paths that should not be allowed
        assert!(
            !check_path("/etc/passwd"),
            "/etc/passwd should not be considered safe"
        );
        assert!(
            !check_path("/home/user/file.txt"),
            "/home/user/file.txt should not be considered safe"
        );
    }

    #[test]
    fn test_safe_open_file_comprehensive() -> Result<()> {
        // Create a temporary directory and file
        let dir = tempdir()?;
        let file_path = dir.path().join("comprehensive_test.txt");

        // Test with non-existent file (should fail)
        let result = safe_open_file(&file_path, false);
        assert!(result.is_err(), "Opening non-existent file should fail");

        // Create the file
        {
            let mut file = File::create(&file_path)?;
            file.write_all(b"comprehensive test")?;
        }

        // Test opening existing file (should succeed)
        let mut file = safe_open_file(&file_path, false)?;
        let mut content = String::new();
        file.read_to_string(&mut content)?;
        assert_eq!(content, "comprehensive test");

        // Test with invalid path
        let invalid_path = PathBuf::from("\0invalid");
        let result = safe_open_file(&invalid_path, false);
        assert!(
            result.is_err(),
            "Opening file with invalid path should fail"
        );

        Ok(())
    }

    #[test]
    fn test_safe_create_file_existing() -> Result<()> {
        // Create a temporary directory and file
        let dir = tempdir()?;
        let file_path = dir.path().join("existing.txt");

        // Create the file with initial content
        {
            let mut file = File::create(&file_path)?;
            file.write_all(b"initial content")?;
        }

        // Use safe_create_file to overwrite the file
        {
            let mut file = safe_create_file(&file_path, false)?;
            file.write_all(b"overwritten content")?;
        }

        // Verify the content was overwritten
        let mut content = String::new();
        let mut file = File::open(&file_path)?;
        file.read_to_string(&mut content)?;

        assert_eq!(content, "overwritten content");

        Ok(())
    }
}