-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobliteration.rs
More file actions
552 lines (468 loc) · 17.7 KB
/
Copy pathobliteration.rs
File metadata and controls
552 lines (468 loc) · 17.7 KB
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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
// SPDX-FileCopyrightText: 2025 Jonathan D.A. Jewell
//
// RMO: Obliterative Wipe Primitive
// Implements GDPR Article 17 "Right to Erasure" with formal obliteration proofs
//
// The RMO primitive guarantees:
// 1. Content is cryptographically unrecoverable after obliteration
// 2. A proof of non-existence is generated
// 3. The fact of obliteration is logged (without content)
use crate::content_store::{ContentHash, ContentStore};
use crate::error::{JanusError, Result};
use chrono::{DateTime, Utc};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use uuid::Uuid;
/// Number of overwrite passes for secure deletion
/// Based on DoD 5220.22-M standard (3 passes minimum)
const OVERWRITE_PASSES: usize = 3;
/// Obliteration patterns for each pass
const PATTERNS: [u8; 3] = [0x00, 0xFF, 0x00]; // zeros, ones, zeros
/// Cryptographic proof that content has been obliterated
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObliterationProof {
/// Unique proof identifier
pub id: String,
/// Hash of the obliterated content (proves what was deleted)
pub content_hash: ContentHash,
/// Timestamp of obliteration
pub timestamp: DateTime<Utc>,
/// User who performed obliteration
pub user: String,
/// Nonce used in proof generation
pub nonce: String,
/// Cryptographic commitment: H(content_hash || nonce || timestamp)
pub commitment: String,
/// Number of overwrite passes performed
pub overwrite_passes: usize,
/// Verification that storage location no longer contains original
pub storage_cleared: bool,
}
impl ObliterationProof {
/// Generate a new obliteration proof
pub fn generate(content_hash: &ContentHash, passes: usize) -> Self {
let id = Uuid::new_v4().to_string();
let timestamp = Utc::now();
let user = whoami::username();
// Generate random nonce
let mut nonce_bytes = [0u8; 32];
rand::thread_rng().fill_bytes(&mut nonce_bytes);
let nonce = hex::encode(nonce_bytes);
// Generate commitment: H(content_hash || nonce || timestamp)
let mut hasher = Sha256::new();
hasher.update(content_hash.raw_hash().as_bytes());
hasher.update(&nonce_bytes);
hasher.update(timestamp.to_rfc3339().as_bytes());
let commitment = hex::encode(hasher.finalize());
Self {
id,
content_hash: content_hash.clone(),
timestamp,
user,
nonce,
commitment,
overwrite_passes: passes,
storage_cleared: true,
}
}
/// Verify the proof's cryptographic commitment
pub fn verify_commitment(&self) -> bool {
let nonce_bytes = match hex::decode(&self.nonce) {
Ok(bytes) => bytes,
Err(_) => return false,
};
let mut hasher = Sha256::new();
hasher.update(self.content_hash.raw_hash().as_bytes());
hasher.update(&nonce_bytes);
hasher.update(self.timestamp.to_rfc3339().as_bytes());
let expected = hex::encode(hasher.finalize());
self.commitment == expected
}
}
/// Record of an obliteration event (stored in audit log)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObliterationRecord {
/// Unique record identifier
pub id: String,
/// When obliteration occurred
pub timestamp: DateTime<Utc>,
/// User who performed obliteration
pub user: String,
/// Hash of obliterated content (not the content itself)
pub content_hash: ContentHash,
/// Reason for obliteration (optional, for compliance)
pub reason: Option<String>,
/// Reference to legal basis (e.g., "GDPR Article 17")
pub legal_basis: Option<String>,
/// The obliteration proof
pub proof: ObliterationProof,
/// Related operation IDs that were cleaned up
pub cleaned_operation_ids: Vec<String>,
}
/// Obliteration log for audit trail
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ObliterationLog {
pub version: String,
pub records: Vec<ObliterationRecord>,
}
impl ObliterationLog {
pub fn new() -> Self {
Self {
version: "1.0".to_string(),
records: Vec::new(),
}
}
}
/// Manager for obliterative wipe operations
pub struct ObliterationManager {
/// Path to obliteration log
log_path: PathBuf,
/// Obliteration log
log: ObliterationLog,
}
impl ObliterationManager {
/// Create or open an obliteration manager
pub fn new(log_path: PathBuf) -> Result<Self> {
let log = if log_path.exists() {
let content = ({ use std::io::Read; std::fs::File::open(&log_path).and_then(|mut f| { let mut buf = String::new(); f.take(10 * 1024 * 1024).read_to_string(&mut buf)?; Ok(buf) }) })?;
serde_json::from_str(&content)
.map_err(|e| JanusError::MetadataCorrupted(e.to_string()))?
} else {
ObliterationLog::new()
};
Ok(Self { log_path, log })
}
/// Save log to disk
fn save(&self) -> Result<()> {
if let Some(parent) = self.log_path.parent() {
fs::create_dir_all(parent)?;
}
let content = serde_json::to_string_pretty(&self.log)?;
fs::write(&self.log_path, content)?;
Ok(())
}
/// Obliterate content from the content store
/// This is the main RMO primitive implementation
pub fn obliterate(
&mut self,
content_store: &ContentStore,
content_hash: &ContentHash,
reason: Option<String>,
legal_basis: Option<String>,
) -> Result<ObliterationRecord> {
// Get the content path
let content_path = content_store.content_path(content_hash);
if !content_path.exists() {
return Err(JanusError::FileNotFound(format!(
"Content {} not found in store",
content_hash
)));
}
// Perform secure overwrite
let passes = secure_overwrite(&content_path)?;
// Remove the file
fs::remove_file(&content_path)?;
// Generate obliteration proof
let proof = ObliterationProof::generate(content_hash, passes);
// Create record
let record = ObliterationRecord {
id: Uuid::new_v4().to_string(),
timestamp: Utc::now(),
user: whoami::username(),
content_hash: content_hash.clone(),
reason,
legal_basis,
proof,
cleaned_operation_ids: Vec::new(),
};
// Log the obliteration
self.log.records.push(record.clone());
self.save()?;
Ok(record)
}
/// Obliterate content and clean up related metadata references
pub fn obliterate_with_cleanup(
&mut self,
content_store: &ContentStore,
content_hash: &ContentHash,
operation_ids: Vec<String>,
reason: Option<String>,
legal_basis: Option<String>,
) -> Result<ObliterationRecord> {
// Perform obliteration
let mut record = self.obliterate(content_store, content_hash, reason, legal_basis)?;
// Record which operations were affected
record.cleaned_operation_ids = operation_ids;
// Update the log
if let Some(last) = self.log.records.last_mut() {
last.cleaned_operation_ids = record.cleaned_operation_ids.clone();
}
self.save()?;
Ok(record)
}
/// Get all obliteration records
pub fn records(&self) -> &[ObliterationRecord] {
&self.log.records
}
/// Get record by ID
pub fn get(&self, id: &str) -> Option<&ObliterationRecord> {
self.log.records.iter().find(|r| r.id == id)
}
/// Get records for a specific content hash
pub fn get_by_hash(&self, hash: &ContentHash) -> Vec<&ObliterationRecord> {
self.log
.records
.iter()
.filter(|r| r.content_hash == *hash)
.collect()
}
/// Verify an obliteration proof
pub fn verify_proof(&self, proof_id: &str) -> Result<bool> {
let record = self
.log
.records
.iter()
.find(|r| r.proof.id == proof_id)
.ok_or_else(|| JanusError::InvalidOperationId(proof_id.to_string()))?;
Ok(record.proof.verify_commitment())
}
/// Count total obliterations
pub fn count(&self) -> usize {
self.log.records.len()
}
}
/// Perform secure overwrite of a file
/// Uses multiple passes with different patterns to ensure data is unrecoverable
fn secure_overwrite(path: &Path) -> Result<usize> {
let metadata = fs::metadata(path)?;
let file_size = metadata.len() as usize;
if file_size == 0 {
return Ok(OVERWRITE_PASSES);
}
// Open file for writing
let mut file = OpenOptions::new().write(true).open(path)?;
// Perform overwrite passes
for (pass, &pattern) in PATTERNS.iter().enumerate() {
// Seek to beginning
file.seek(SeekFrom::Start(0))?;
// Create pattern buffer
let buffer = if pass == OVERWRITE_PASSES - 1 {
// Final pass: random data
let mut random_buffer = vec![0u8; file_size.min(8192)];
rand::thread_rng().fill_bytes(&mut random_buffer);
random_buffer
} else {
// Fixed pattern
vec![pattern; file_size.min(8192)]
};
// Write in chunks
let mut written = 0;
while written < file_size {
let to_write = (file_size - written).min(buffer.len());
file.write_all(&buffer[..to_write])?;
written += to_write;
}
// Flush to disk
file.sync_all()?;
}
Ok(OVERWRITE_PASSES)
}
/// Obliterate an arbitrary file on disk (not necessarily in the content
/// store): hash its current content, securely overwrite it with
/// [`OVERWRITE_PASSES`] passes, remove it, and return a proof of erasure.
///
/// This is the GDPR Article 17 "right to erasure" primitive applied to a
/// concrete filesystem path, used by the `jk obliterate <path>` command.
/// Unlike [`ObliterationManager::obliterate`] it does not consult the content
/// store, so it works on files the repository never ingested.
///
/// TODO(product): also scrub any content-store copies and prune the
/// associated operation-log entries so no recoverable trace remains, and
/// thread the resulting proof into the obliteration audit log.
pub fn obliterate_file(path: &Path) -> Result<ObliterationProof> {
if !path.exists() {
return Err(JanusError::FileNotFound(format!(
"{} not found",
path.display()
)));
}
// Record what we are about to destroy (content hash, for the proof).
let content = fs::read(path)?;
let content_hash = ContentHash::from_bytes(&content);
// DoD 5220.22-M style multi-pass overwrite, then unlink.
let passes = secure_overwrite(path)?;
fs::remove_file(path)?;
Ok(ObliterationProof::generate(&content_hash, passes))
}
/// Verify that content no longer exists at a path
pub fn verify_obliteration(path: &Path, original_hash: &ContentHash) -> Result<bool> {
if !path.exists() {
return Ok(true);
}
// Read remaining content
let mut file = File::open(path)?;
let mut content = Vec::new();
file.read_to_end(&mut content)?;
// Verify it doesn't match original
let current_hash = ContentHash::from_bytes(&content);
Ok(current_hash != *original_hash)
}
/// Batch obliteration request
#[derive(Debug, Clone)]
pub struct BatchObliterationRequest {
pub content_hashes: Vec<ContentHash>,
pub reason: Option<String>,
pub legal_basis: Option<String>,
}
/// Batch obliteration result
#[derive(Debug)]
pub struct BatchObliterationResult {
pub successful: Vec<ObliterationRecord>,
pub failed: Vec<(ContentHash, JanusError)>,
}
impl ObliterationManager {
/// Obliterate multiple content items
pub fn obliterate_batch(
&mut self,
content_store: &ContentStore,
request: BatchObliterationRequest,
) -> BatchObliterationResult {
let mut successful = Vec::new();
let mut failed = Vec::new();
for hash in request.content_hashes {
match self.obliterate(
content_store,
&hash,
request.reason.clone(),
request.legal_basis.clone(),
) {
Ok(record) => successful.push(record),
Err(e) => failed.push((hash, e)),
}
}
BatchObliterationResult { successful, failed }
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn setup() -> (TempDir, ContentStore, ObliterationManager) {
let tmp = TempDir::new().expect("failed to create temp dir");
let content_store = ContentStore::new(tmp.path().join("content"), false)
.expect("failed to create content store");
let obliteration_manager =
ObliterationManager::new(tmp.path().join("obliterations.json"))
.expect("failed to create obliteration manager");
(tmp, content_store, obliteration_manager)
}
#[test]
fn test_obliteration_proof_generation() {
let hash = ContentHash::from_bytes(b"test content");
let proof = ObliterationProof::generate(&hash, 3);
assert!(!proof.id.is_empty());
assert_eq!(proof.content_hash, hash);
assert_eq!(proof.overwrite_passes, 3);
assert!(proof.storage_cleared);
}
#[test]
fn test_proof_verification() {
let hash = ContentHash::from_bytes(b"test content");
let proof = ObliterationProof::generate(&hash, 3);
assert!(proof.verify_commitment());
}
#[test]
fn test_obliterate_content() {
let (_tmp, content_store, mut obliteration_manager) = setup();
// Store some content
let content = b"sensitive data to be obliterated";
let hash = content_store.store(content).expect("failed to store content");
// Verify it exists
assert!(content_store.exists(&hash));
// Obliterate it
let record = obliteration_manager
.obliterate(
&content_store,
&hash,
Some("User request".to_string()),
Some("GDPR Article 17".to_string()),
)
.expect("failed to obliterate content");
// Verify obliteration
assert!(!content_store.exists(&hash));
assert_eq!(record.content_hash, hash);
assert_eq!(record.reason, Some("User request".to_string()));
assert_eq!(record.legal_basis, Some("GDPR Article 17".to_string()));
assert!(record.proof.verify_commitment());
}
#[test]
fn test_obliteration_log_persistence() {
let (tmp, content_store, mut obliteration_manager) = setup();
// Store and obliterate content
let content = b"data to obliterate";
let hash = content_store.store(content).expect("failed to store content");
let record = obliteration_manager
.obliterate(&content_store, &hash, None, None)
.expect("failed to obliterate content");
// Reopen manager and verify log
let obliteration_manager2 =
ObliterationManager::new(tmp.path().join("obliterations.json"))
.expect("failed to reopen obliteration manager");
assert_eq!(obliteration_manager2.count(), 1);
let retrieved = obliteration_manager2.get(&record.id)
.expect("failed to retrieve obliteration record");
assert_eq!(retrieved.content_hash, hash);
}
#[test]
fn test_secure_overwrite() {
let tmp = TempDir::new().expect("failed to create temp dir");
let test_file = tmp.path().join("test.txt");
// Create file with known content
let original = b"sensitive information that must be destroyed";
fs::write(&test_file, original).expect("failed to write test file");
// Perform secure overwrite
let passes = secure_overwrite(&test_file).expect("failed to perform secure overwrite");
assert_eq!(passes, OVERWRITE_PASSES);
// Read back and verify content changed
let remaining = fs::read(&test_file).expect("failed to read overwritten file");
assert_ne!(remaining, original.to_vec());
}
#[test]
fn test_batch_obliteration() {
let (_tmp, content_store, mut obliteration_manager) = setup();
// Store multiple contents
let hashes: Vec<ContentHash> = (0..5)
.map(|i| {
let content = format!("content {}", i);
content_store.store(content.as_bytes())
.expect("failed to store batch content")
})
.collect();
// Batch obliterate
let request = BatchObliterationRequest {
content_hashes: hashes.clone(),
reason: Some("Batch cleanup".to_string()),
legal_basis: Some("GDPR Article 17".to_string()),
};
let result = obliteration_manager.obliterate_batch(&content_store, request);
assert_eq!(result.successful.len(), 5);
assert!(result.failed.is_empty());
// Verify all obliterated
for hash in hashes {
assert!(!content_store.exists(&hash));
}
}
#[test]
fn test_obliterate_nonexistent() {
let (_tmp, content_store, mut obliteration_manager) = setup();
let fake_hash = ContentHash::from_bytes(b"nonexistent");
let result = obliteration_manager.obliterate(&content_store, &fake_hash, None, None);
assert!(result.is_err());
}
}