socket-patch-core 3.1.0

Core library for socket-patch: manifest, hash, crawlers, patch engine, API client
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
use std::collections::HashMap;
use std::path::Path;

use crate::manifest::schema::PatchFileInfo;
use crate::patch::file_hash::compute_file_git_sha256;

/// Status of a file rollback verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifyRollbackStatus {
    /// File is ready to be rolled back (current hash matches afterHash).
    Ready,
    /// File is already in the original state (current hash matches beforeHash).
    AlreadyOriginal,
    /// File hash does not match the expected afterHash.
    HashMismatch,
    /// File was not found on disk.
    NotFound,
    /// The before-hash blob needed for rollback is missing from the blobs directory.
    MissingBlob,
}

/// Result of verifying whether a single file can be rolled back.
#[derive(Debug, Clone)]
pub struct VerifyRollbackResult {
    pub file: String,
    pub status: VerifyRollbackStatus,
    pub message: Option<String>,
    pub current_hash: Option<String>,
    pub expected_hash: Option<String>,
    pub target_hash: Option<String>,
}

/// Result of rolling back patches for a single package.
#[derive(Debug, Clone)]
pub struct RollbackResult {
    pub package_key: String,
    pub package_path: String,
    pub success: bool,
    pub files_verified: Vec<VerifyRollbackResult>,
    pub files_rolled_back: Vec<String>,
    pub error: Option<String>,
}

/// Normalize file path by removing the "package/" prefix if present.
fn normalize_file_path(file_name: &str) -> &str {
    const PACKAGE_PREFIX: &str = "package/";
    if let Some(stripped) = file_name.strip_prefix(PACKAGE_PREFIX) {
        stripped
    } else {
        file_name
    }
}

/// Verify a single file can be rolled back.
///
/// A file is ready for rollback if:
/// 1. The file exists on disk.
/// 2. The before-hash blob exists in the blobs directory.
/// 3. Its current hash matches the afterHash (patched state).
pub async fn verify_file_rollback(
    pkg_path: &Path,
    file_name: &str,
    file_info: &PatchFileInfo,
    blobs_path: &Path,
) -> VerifyRollbackResult {
    let normalized = normalize_file_path(file_name);
    let filepath = pkg_path.join(normalized);

    let is_new_file = file_info.before_hash.is_empty();

    // For new files (empty beforeHash), rollback means deleting the file.
    if is_new_file {
        if tokio::fs::metadata(&filepath).await.is_err() {
            // File already doesn't exist — already rolled back.
            return VerifyRollbackResult {
                file: file_name.to_string(),
                status: VerifyRollbackStatus::AlreadyOriginal,
                message: None,
                current_hash: None,
                expected_hash: None,
                target_hash: None,
            };
        }
        let current_hash = compute_file_git_sha256(&filepath).await.unwrap_or_default();
        if current_hash == file_info.after_hash {
            return VerifyRollbackResult {
                file: file_name.to_string(),
                status: VerifyRollbackStatus::Ready,
                message: None,
                current_hash: Some(current_hash),
                expected_hash: None,
                target_hash: None,
            };
        }
        return VerifyRollbackResult {
            file: file_name.to_string(),
            status: VerifyRollbackStatus::HashMismatch,
            message: Some(
                "File has been modified after patching. Cannot safely rollback.".to_string(),
            ),
            current_hash: Some(current_hash),
            expected_hash: Some(file_info.after_hash.clone()),
            target_hash: None,
        };
    }

    // Check if file exists
    if tokio::fs::metadata(&filepath).await.is_err() {
        return VerifyRollbackResult {
            file: file_name.to_string(),
            status: VerifyRollbackStatus::NotFound,
            message: Some("File not found".to_string()),
            current_hash: None,
            expected_hash: None,
            target_hash: None,
        };
    }

    // Check if before blob exists (required for rollback)
    let before_blob_path = blobs_path.join(&file_info.before_hash);
    if tokio::fs::metadata(&before_blob_path).await.is_err() {
        return VerifyRollbackResult {
            file: file_name.to_string(),
            status: VerifyRollbackStatus::MissingBlob,
            message: Some(format!(
                "Before blob not found: {}. Re-download the patch to enable rollback.",
                file_info.before_hash
            )),
            current_hash: None,
            expected_hash: None,
            target_hash: Some(file_info.before_hash.clone()),
        };
    }

    // Compute current hash
    let current_hash = match compute_file_git_sha256(&filepath).await {
        Ok(h) => h,
        Err(e) => {
            return VerifyRollbackResult {
                file: file_name.to_string(),
                status: VerifyRollbackStatus::NotFound,
                message: Some(format!("Failed to hash file: {}", e)),
                current_hash: None,
                expected_hash: None,
                target_hash: None,
            };
        }
    };

    // Check if already in original state
    if current_hash == file_info.before_hash {
        return VerifyRollbackResult {
            file: file_name.to_string(),
            status: VerifyRollbackStatus::AlreadyOriginal,
            message: None,
            current_hash: Some(current_hash),
            expected_hash: None,
            target_hash: None,
        };
    }

    // Check if matches expected patched hash (afterHash)
    if current_hash != file_info.after_hash {
        return VerifyRollbackResult {
            file: file_name.to_string(),
            status: VerifyRollbackStatus::HashMismatch,
            message: Some(
                "File has been modified after patching. Cannot safely rollback.".to_string(),
            ),
            current_hash: Some(current_hash),
            expected_hash: Some(file_info.after_hash.clone()),
            target_hash: Some(file_info.before_hash.clone()),
        };
    }

    VerifyRollbackResult {
        file: file_name.to_string(),
        status: VerifyRollbackStatus::Ready,
        message: None,
        current_hash: Some(current_hash),
        expected_hash: None,
        target_hash: Some(file_info.before_hash.clone()),
    }
}

/// Rollback a single file to its original state.
/// Writes the original content and verifies the resulting hash.
pub async fn rollback_file_patch(
    pkg_path: &Path,
    file_name: &str,
    original_content: &[u8],
    expected_hash: &str,
) -> Result<(), std::io::Error> {
    let normalized = normalize_file_path(file_name);
    let filepath = pkg_path.join(normalized);

    // Make file writable if it is read-only (e.g. Go module cache)
    #[cfg(unix)]
    if let Ok(meta) = tokio::fs::metadata(&filepath).await {
        use std::os::unix::fs::PermissionsExt;
        let perms = meta.permissions();
        if perms.readonly() {
            let mode = perms.mode();
            let mut new_perms = perms;
            new_perms.set_mode(mode | 0o200);
            tokio::fs::set_permissions(&filepath, new_perms).await?;
        }
    }

    // Write the original content
    tokio::fs::write(&filepath, original_content).await?;

    // Verify the hash after writing
    let verify_hash = compute_file_git_sha256(&filepath).await?;
    if verify_hash != expected_hash {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "Hash verification failed after rollback. Expected: {}, Got: {}",
                expected_hash, verify_hash
            ),
        ));
    }

    Ok(())
}

/// Verify and rollback patches for a single package.
///
/// For each file in `files`, this function:
/// 1. Verifies the file is ready to be rolled back (or already original).
/// 2. If not dry_run, reads the before-hash blob and writes it back.
/// 3. Returns a summary of what happened.
pub async fn rollback_package_patch(
    package_key: &str,
    pkg_path: &Path,
    files: &HashMap<String, PatchFileInfo>,
    blobs_path: &Path,
    dry_run: bool,
) -> RollbackResult {
    let mut result = RollbackResult {
        package_key: package_key.to_string(),
        package_path: pkg_path.display().to_string(),
        success: false,
        files_verified: Vec::new(),
        files_rolled_back: Vec::new(),
        error: None,
    };

    // First, verify all files
    for (file_name, file_info) in files {
        let verify_result =
            verify_file_rollback(pkg_path, file_name, file_info, blobs_path).await;

        // If any file has issues (not ready and not already original), we can't proceed
        if verify_result.status != VerifyRollbackStatus::Ready
            && verify_result.status != VerifyRollbackStatus::AlreadyOriginal
        {
            let msg = verify_result
                .message
                .clone()
                .unwrap_or_else(|| format!("{:?}", verify_result.status));
            result.error = Some(format!(
                "Cannot rollback: {} - {}",
                verify_result.file, msg
            ));
            result.files_verified.push(verify_result);
            return result;
        }

        result.files_verified.push(verify_result);
    }

    // Check if all files are already in original state
    let all_original = result
        .files_verified
        .iter()
        .all(|v| v.status == VerifyRollbackStatus::AlreadyOriginal);
    if all_original {
        result.success = true;
        return result;
    }

    // If dry run, stop here
    if dry_run {
        result.success = true;
        return result;
    }

    // Rollback files that need it
    for (file_name, file_info) in files {
        let verify_result = result
            .files_verified
            .iter()
            .find(|v| v.file == *file_name);
        if let Some(vr) = verify_result {
            if vr.status == VerifyRollbackStatus::AlreadyOriginal {
                continue;
            }
        }

        // New files (empty beforeHash): delete instead of restoring.
        if file_info.before_hash.is_empty() {
            let normalized = normalize_file_path(file_name);
            let filepath = pkg_path.join(normalized);
            if let Err(e) = tokio::fs::remove_file(&filepath).await {
                result.error = Some(format!("Failed to delete {}: {}", file_name, e));
                return result;
            }
            result.files_rolled_back.push(file_name.clone());
            continue;
        }

        // Read original content from blobs
        let blob_path = blobs_path.join(&file_info.before_hash);
        let original_content = match tokio::fs::read(&blob_path).await {
            Ok(content) => content,
            Err(e) => {
                result.error = Some(format!(
                    "Failed to read blob {}: {}",
                    file_info.before_hash, e
                ));
                return result;
            }
        };

        // Rollback the file
        if let Err(e) =
            rollback_file_patch(pkg_path, file_name, &original_content, &file_info.before_hash)
                .await
        {
            result.error = Some(e.to_string());
            return result;
        }

        result.files_rolled_back.push(file_name.clone());
    }

    result.success = true;
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hash::git_sha256::compute_git_sha256_from_bytes;

    #[tokio::test]
    async fn test_verify_file_rollback_not_found() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let file_info = PatchFileInfo {
            before_hash: "aaa".to_string(),
            after_hash: "bbb".to_string(),
        };

        let result =
            verify_file_rollback(pkg_dir.path(), "nonexistent.js", &file_info, blobs_dir.path())
                .await;
        assert_eq!(result.status, VerifyRollbackStatus::NotFound);
    }

    #[tokio::test]
    async fn test_verify_file_rollback_missing_blob() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let content = b"patched content";
        tokio::fs::write(pkg_dir.path().join("index.js"), content)
            .await
            .unwrap();

        let file_info = PatchFileInfo {
            before_hash: "missing_blob_hash".to_string(),
            after_hash: compute_git_sha256_from_bytes(content),
        };

        let result =
            verify_file_rollback(pkg_dir.path(), "index.js", &file_info, blobs_dir.path()).await;
        assert_eq!(result.status, VerifyRollbackStatus::MissingBlob);
        assert!(result.message.unwrap().contains("Before blob not found"));
    }

    #[tokio::test]
    async fn test_verify_file_rollback_ready() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let patched = b"patched content";
        let before_hash = compute_git_sha256_from_bytes(original);
        let after_hash = compute_git_sha256_from_bytes(patched);

        // File is in patched state
        tokio::fs::write(pkg_dir.path().join("index.js"), patched)
            .await
            .unwrap();

        // Before blob exists
        tokio::fs::write(blobs_dir.path().join(&before_hash), original)
            .await
            .unwrap();

        let file_info = PatchFileInfo {
            before_hash: before_hash.clone(),
            after_hash: after_hash.clone(),
        };

        let result =
            verify_file_rollback(pkg_dir.path(), "index.js", &file_info, blobs_dir.path()).await;
        assert_eq!(result.status, VerifyRollbackStatus::Ready);
        assert_eq!(result.current_hash.unwrap(), after_hash);
    }

    #[tokio::test]
    async fn test_verify_file_rollback_already_original() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let before_hash = compute_git_sha256_from_bytes(original);

        // File is already in original state
        tokio::fs::write(pkg_dir.path().join("index.js"), original)
            .await
            .unwrap();

        // Before blob exists
        tokio::fs::write(blobs_dir.path().join(&before_hash), original)
            .await
            .unwrap();

        let file_info = PatchFileInfo {
            before_hash: before_hash.clone(),
            after_hash: "bbbb".to_string(),
        };

        let result =
            verify_file_rollback(pkg_dir.path(), "index.js", &file_info, blobs_dir.path()).await;
        assert_eq!(result.status, VerifyRollbackStatus::AlreadyOriginal);
    }

    #[tokio::test]
    async fn test_verify_file_rollback_hash_mismatch() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let before_hash = compute_git_sha256_from_bytes(original);

        // File has been modified to something unexpected
        tokio::fs::write(pkg_dir.path().join("index.js"), b"something unexpected")
            .await
            .unwrap();

        // Before blob exists
        tokio::fs::write(blobs_dir.path().join(&before_hash), original)
            .await
            .unwrap();

        let file_info = PatchFileInfo {
            before_hash,
            after_hash: "expected_after_hash".to_string(),
        };

        let result =
            verify_file_rollback(pkg_dir.path(), "index.js", &file_info, blobs_dir.path()).await;
        assert_eq!(result.status, VerifyRollbackStatus::HashMismatch);
        assert!(result
            .message
            .unwrap()
            .contains("modified after patching"));
    }

    #[tokio::test]
    async fn test_rollback_file_patch_success() {
        let dir = tempfile::tempdir().unwrap();
        let original = b"original content";
        let original_hash = compute_git_sha256_from_bytes(original);

        // File currently has patched content
        tokio::fs::write(dir.path().join("index.js"), b"patched")
            .await
            .unwrap();

        rollback_file_patch(dir.path(), "index.js", original, &original_hash)
            .await
            .unwrap();

        let written = tokio::fs::read(dir.path().join("index.js")).await.unwrap();
        assert_eq!(written, original);
    }

    #[tokio::test]
    async fn test_rollback_file_patch_hash_mismatch() {
        let dir = tempfile::tempdir().unwrap();
        tokio::fs::write(dir.path().join("index.js"), b"patched")
            .await
            .unwrap();

        let result =
            rollback_file_patch(dir.path(), "index.js", b"original content", "wrong_hash").await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Hash verification failed"));
    }

    #[tokio::test]
    async fn test_rollback_package_patch_success() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let patched = b"patched content";
        let before_hash = compute_git_sha256_from_bytes(original);
        let after_hash = compute_git_sha256_from_bytes(patched);

        // File is in patched state
        tokio::fs::write(pkg_dir.path().join("index.js"), patched)
            .await
            .unwrap();

        // Before blob exists
        tokio::fs::write(blobs_dir.path().join(&before_hash), original)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash: before_hash.clone(),
                after_hash,
            },
        );

        let result = rollback_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            blobs_dir.path(),
            false,
        )
        .await;

        assert!(result.success);
        assert_eq!(result.files_rolled_back.len(), 1);
        assert!(result.error.is_none());

        // Verify file was restored
        let content = tokio::fs::read(pkg_dir.path().join("index.js")).await.unwrap();
        assert_eq!(content, original);
    }

    #[tokio::test]
    async fn test_rollback_package_patch_dry_run() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let patched = b"patched content";
        let before_hash = compute_git_sha256_from_bytes(original);
        let after_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(pkg_dir.path().join("index.js"), patched)
            .await
            .unwrap();
        tokio::fs::write(blobs_dir.path().join(&before_hash), original)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash,
                after_hash,
            },
        );

        let result = rollback_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            blobs_dir.path(),
            true, // dry run
        )
        .await;

        assert!(result.success);
        assert_eq!(result.files_rolled_back.len(), 0); // dry run

        // File should still be patched
        let content = tokio::fs::read(pkg_dir.path().join("index.js")).await.unwrap();
        assert_eq!(content, patched);
    }

    #[tokio::test]
    async fn test_rollback_package_patch_all_original() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let before_hash = compute_git_sha256_from_bytes(original);

        // File is already original
        tokio::fs::write(pkg_dir.path().join("index.js"), original)
            .await
            .unwrap();
        tokio::fs::write(blobs_dir.path().join(&before_hash), original)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash,
                after_hash: "bbbb".to_string(),
            },
        );

        let result = rollback_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            blobs_dir.path(),
            false,
        )
        .await;

        assert!(result.success);
        assert_eq!(result.files_rolled_back.len(), 0);
    }

    #[tokio::test]
    async fn test_rollback_package_patch_missing_blob_blocks() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        tokio::fs::write(pkg_dir.path().join("index.js"), b"patched content")
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash: "missing_hash".to_string(),
                after_hash: "bbbb".to_string(),
            },
        );

        let result = rollback_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            blobs_dir.path(),
            false,
        )
        .await;

        assert!(!result.success);
        assert!(result.error.is_some());
    }
}