checkpointkit 0.1.4

Crash-resume checkpoint persistence with atomic writes and progress tracking
Documentation
//! Oneshot adversarial tests for checkpointkit.
//! See TESTING.md for the Santh testing standard.

use checkpointkit::{load, save, CheckpointError, ProgressTracker};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tempfile::tempdir;

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
struct Payload {
    data: String,
}

#[test]
fn test_depth_save_path_traversal() {
    let path = std::path::Path::new("/tmp/../etc/passwd");
    let state = Payload { data: "pwned".to_string() };

    let result = save(path, &state);
    match result {
        Err(CheckpointError::PathTraversal(p)) => {
            assert_eq!(p, std::path::PathBuf::from("/tmp/../etc/passwd"));
        }
        _ => panic!("Expected PathTraversal error, got {result:?}"),
    }
}

#[test]
fn test_depth_load_path_traversal() {
    let path = std::path::Path::new("/tmp/../etc/passwd");

    let result: Result<Option<Payload>, _> = load(path);
    match result {
        Err(CheckpointError::PathTraversal(p)) => {
            assert_eq!(p, std::path::PathBuf::from("/tmp/../etc/passwd"));
        }
        _ => panic!("Expected PathTraversal error, got {result:?}"),
    }
}

#[test]
fn test_depth_save_null_bytes_in_path() {
    let path = std::path::Path::new("/tmp/some\0path.json");
    let state = Payload { data: "test".to_string() };
    
    // std::fs operations with null bytes usually fail with an IO error 
    // or invalid input error. Let's make sure it fails correctly.
    let result = save(path, &state);
    assert!(result.is_err(), "save with null bytes in path should fail");
}

#[test]
fn test_depth_load_null_bytes_in_path() {
    let path = std::path::Path::new("/tmp/some\0path.json");
    
    let result: Result<Option<Payload>, _> = load(path);
    assert!(result.is_err(), "load with null bytes in path should fail");
}

#[test]
fn test_depth_enormous_path() {
    let dir = tempdir().unwrap();
    let mut path = dir.path().to_path_buf();
    
    // Create an extremely long path > 4096 bytes (standard PATH_MAX)
    for _ in 0..1000 {
        path.push("very_long_directory_name_that_goes_on_and_on");
    }
    path.push("test.json");
    
    let state = Payload { data: "test".to_string() };
    let result = save(&path, &state);
    assert!(result.is_err(), "save with enormous path should fail with Io error");
}

#[test]
fn test_depth_load_garbage_bytes() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("garbage.json");
    
    // Write completely invalid UTF-8 and JSON
    std::fs::write(&path, [0xFF, 0xFE, 0xFD, 0x00, 0x01, 0x02]).unwrap();
    
    let result: Result<Option<Payload>, _> = load(&path);
    match result {
        Err(CheckpointError::Serialize(_)) => {}
        _ => panic!("Expected Serialize error for garbage bytes, got {result:?}"),
    }
}

#[test]
fn test_depth_load_empty_file() {
    // An existing 0-byte checkpoint is corruption, not absence: `save` writes
    // JSON via atomic rename and JSON is never 0 bytes, so a 0-byte final file
    // means the checkpoint was truncated or externally clobbered. `load` must
    // fail closed with CorruptCheckpoint rather than silently restarting from
    // scratch (which would discard the corrupt checkpoint with no signal).
    let dir = tempdir().unwrap();
    let path = dir.path().join("empty.json");

    std::fs::write(&path, []).unwrap(); // 0 bytes

    let result: Result<Option<Payload>, _> = load(&path);
    match &result {
        Err(CheckpointError::CorruptCheckpoint(p)) => {
            assert_eq!(p, &path, "error must name the corrupt checkpoint path");
        }
        _ => panic!("Expected CorruptCheckpoint for empty file, got {result:?}"),
    }
}

#[test]
fn test_depth_huge_state() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("huge.json");
    
    // Create >1MB string payload
    let state = Payload { data: "X".repeat(2 * 1024 * 1024) };
    
    assert!(save(&path, &state).is_ok(), "saving 2MB file should succeed");
    
    let loaded: Option<Payload> = load(&path).unwrap();
    assert_eq!(loaded.unwrap().data.len(), 2 * 1024 * 1024, "loaded string length should match");
}

#[test]
fn test_depth_progress_tracker_boundary_overflow() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("overflow.json");
    
    let mut tracker = ProgressTracker::new(u64::MAX, &path, Duration::from_secs(1)).unwrap();
    
    // Adding to u64::MAX should cap at total but not panic or overflow
    tracker.increment(10).unwrap();
    assert_eq!(tracker.current(), 10);
    
    // Huge increment
    tracker.increment(u64::MAX - 20).unwrap();
    assert_eq!(tracker.current(), u64::MAX - 10);
    
    // Overflow the add
    tracker.increment(20).unwrap();
    assert_eq!(tracker.current(), u64::MAX);
    
    // Further increment should stay at MAX
    tracker.increment(1).unwrap();
    assert_eq!(tracker.current(), u64::MAX);
}

#[test]
fn test_depth_invalid_utf8_path() {
    #[cfg(unix)]
    {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        let invalid_utf8 = [0x66, 0x6f, 0x80, 0x6f]; // "fo\x80o"
        let os_str = OsStr::from_bytes(&invalid_utf8);
        // Must stay under a tempdir: a CWD-relative non-UTF8 filename lands in
        // the crate root and makes `cargo package` fail (non-unicode path).
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join(os_str);

        let state = Payload { data: "test".to_string() };
        let result = save(path, &state);
        assert!(
            result.is_ok() || matches!(result, Err(CheckpointError::Io { .. })),
            "Invalid UTF-8 path must either succeed or return an Io error, got {result:?}"
        );
    }
}