datasynth-fingerprint 5.36.0

Privacy-preserving synthetic data fingerprinting for DataSynth
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
//! Writer for .dsf fingerprint files.

use std::io::{Seek, Write};
use std::path::Path;

use sha2::{Digest, Sha256};
use zip::write::SimpleFileOptions;
use zip::ZipWriter;

use crate::error::FingerprintResult;
use crate::models::Fingerprint;

use super::file_names;
use super::signing::DsfSigner;

/// Options for writing fingerprint files.
#[derive(Debug, Clone)]
pub struct WriteOptions {
    /// Compression level (0-9, 0 = no compression).
    pub compression_level: u32,
    /// Whether to pretty-print JSON/YAML.
    pub pretty: bool,
}

impl Default for WriteOptions {
    fn default() -> Self {
        Self {
            compression_level: 6,
            pretty: true,
        }
    }
}

/// Writer for .dsf fingerprint files.
pub struct FingerprintWriter {
    options: WriteOptions,
}

impl FingerprintWriter {
    /// Create a new fingerprint writer with default options.
    pub fn new() -> Self {
        Self {
            options: WriteOptions::default(),
        }
    }

    /// Create a new fingerprint writer with custom options.
    pub fn with_options(options: WriteOptions) -> Self {
        Self { options }
    }

    /// Write a fingerprint to a file.
    pub fn write_to_file(&self, fingerprint: &Fingerprint, path: &Path) -> FingerprintResult<()> {
        let file = std::fs::File::create(path)?;
        self.write(fingerprint, file)
    }

    /// Write a fingerprint to a file with digital signature.
    ///
    /// The signature is computed over the manifest content (excluding the signature field)
    /// and included in the manifest.
    pub fn write_to_file_signed(
        &self,
        fingerprint: &Fingerprint,
        path: &Path,
        signer: &DsfSigner,
    ) -> FingerprintResult<()> {
        let file = std::fs::File::create(path)?;
        self.write_signed(fingerprint, file, signer)
    }

    /// Write a fingerprint with digital signature to any writer.
    pub fn write_signed<W: Write + Seek>(
        &self,
        fingerprint: &Fingerprint,
        writer: W,
        signer: &DsfSigner,
    ) -> FingerprintResult<()> {
        let mut zip = ZipWriter::new(writer);
        let options = SimpleFileOptions::default().compression_method(
            if self.options.compression_level > 0 {
                zip::CompressionMethod::Deflated
            } else {
                zip::CompressionMethod::Stored
            },
        );

        // Track checksums
        let mut checksums = std::collections::HashMap::new();

        // Write all components and collect checksums (same as regular write)
        if !fingerprint.schema.is_empty() {
            let schema_yaml = serde_yaml::to_string(&fingerprint.schema)?;
            checksums.insert(
                file_names::SCHEMA.to_string(),
                compute_checksum(schema_yaml.as_bytes()),
            );
            zip.start_file(file_names::SCHEMA, options)?;
            zip.write_all(schema_yaml.as_bytes())?;
        }

        if !fingerprint.statistics.is_empty() {
            let stats_yaml = serde_yaml::to_string(&fingerprint.statistics)?;
            checksums.insert(
                file_names::STATISTICS.to_string(),
                compute_checksum(stats_yaml.as_bytes()),
            );
            zip.start_file(file_names::STATISTICS, options)?;
            zip.write_all(stats_yaml.as_bytes())?;
        }

        if let Some(ref correlations) = fingerprint.correlations {
            let yaml = serde_yaml::to_string(correlations)?;
            checksums.insert(
                file_names::CORRELATIONS.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::CORRELATIONS, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        if let Some(ref integrity) = fingerprint.integrity {
            let yaml = serde_yaml::to_string(integrity)?;
            checksums.insert(
                file_names::INTEGRITY.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::INTEGRITY, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        if let Some(ref rules) = fingerprint.rules {
            let yaml = serde_yaml::to_string(rules)?;
            checksums.insert(
                file_names::RULES.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::RULES, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        if let Some(ref anomalies) = fingerprint.anomalies {
            let yaml = serde_yaml::to_string(anomalies)?;
            checksums.insert(
                file_names::ANOMALIES.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::ANOMALIES, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        if let Some(ref behavioral) = fingerprint.behavioral {
            let yaml = serde_yaml::to_string(behavioral)?;
            checksums.insert(
                file_names::BEHAVIORAL.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::BEHAVIORAL, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        let audit_json = if self.options.pretty {
            serde_json::to_string_pretty(&fingerprint.privacy_audit)?
        } else {
            serde_json::to_string(&fingerprint.privacy_audit)?
        };
        checksums.insert(
            file_names::PRIVACY_AUDIT.to_string(),
            compute_checksum(audit_json.as_bytes()),
        );
        zip.start_file(file_names::PRIVACY_AUDIT, options)?;
        zip.write_all(audit_json.as_bytes())?;

        // Create manifest with checksums but WITHOUT signature
        let mut manifest = fingerprint.manifest.clone();
        manifest.checksums = checksums;
        manifest.signature = None;

        // Sign the manifest using canonical JSON
        let signature = signer.sign_manifest(&manifest);

        // Add signature to manifest
        manifest.signature = Some(signature);

        // Write final manifest with signature
        let manifest_json = if self.options.pretty {
            serde_json::to_string_pretty(&manifest)?
        } else {
            serde_json::to_string(&manifest)?
        };
        zip.start_file(file_names::MANIFEST, options)?;
        zip.write_all(manifest_json.as_bytes())?;

        zip.finish()?;
        Ok(())
    }

    /// Write a fingerprint to any writer.
    pub fn write<W: Write + Seek>(
        &self,
        fingerprint: &Fingerprint,
        writer: W,
    ) -> FingerprintResult<()> {
        let mut zip = ZipWriter::new(writer);
        let options = SimpleFileOptions::default().compression_method(
            if self.options.compression_level > 0 {
                zip::CompressionMethod::Deflated
            } else {
                zip::CompressionMethod::Stored
            },
        );

        // Track checksums
        let mut checksums = std::collections::HashMap::new();

        // Write manifest (we'll update it with checksums at the end)
        // For now, create a mutable copy
        let mut manifest = fingerprint.manifest.clone();

        // Write schema — skip when empty (parquet-bypass bundles have no schema)
        // Note: serde_yaml always produces human-readable output, so pretty option has no effect
        if !fingerprint.schema.is_empty() {
            let schema_yaml = serde_yaml::to_string(&fingerprint.schema)?;
            checksums.insert(
                file_names::SCHEMA.to_string(),
                compute_checksum(schema_yaml.as_bytes()),
            );
            zip.start_file(file_names::SCHEMA, options)?;
            zip.write_all(schema_yaml.as_bytes())?;
        }

        // Write statistics — skip when empty (parquet-bypass bundles have no statistics)
        if !fingerprint.statistics.is_empty() {
            let stats_yaml = serde_yaml::to_string(&fingerprint.statistics)?;
            checksums.insert(
                file_names::STATISTICS.to_string(),
                compute_checksum(stats_yaml.as_bytes()),
            );
            zip.start_file(file_names::STATISTICS, options)?;
            zip.write_all(stats_yaml.as_bytes())?;
        }

        // Write optional components
        if let Some(ref correlations) = fingerprint.correlations {
            let yaml = serde_yaml::to_string(correlations)?;
            checksums.insert(
                file_names::CORRELATIONS.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::CORRELATIONS, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        if let Some(ref integrity) = fingerprint.integrity {
            let yaml = serde_yaml::to_string(integrity)?;
            checksums.insert(
                file_names::INTEGRITY.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::INTEGRITY, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        if let Some(ref rules) = fingerprint.rules {
            let yaml = serde_yaml::to_string(rules)?;
            checksums.insert(
                file_names::RULES.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::RULES, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        if let Some(ref anomalies) = fingerprint.anomalies {
            let yaml = serde_yaml::to_string(anomalies)?;
            checksums.insert(
                file_names::ANOMALIES.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::ANOMALIES, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        if let Some(ref behavioral) = fingerprint.behavioral {
            let yaml = serde_yaml::to_string(behavioral)?;
            checksums.insert(
                file_names::BEHAVIORAL.to_string(),
                compute_checksum(yaml.as_bytes()),
            );
            zip.start_file(file_names::BEHAVIORAL, options)?;
            zip.write_all(yaml.as_bytes())?;
        }

        // Write privacy audit
        let audit_json = if self.options.pretty {
            serde_json::to_string_pretty(&fingerprint.privacy_audit)?
        } else {
            serde_json::to_string(&fingerprint.privacy_audit)?
        };
        checksums.insert(
            file_names::PRIVACY_AUDIT.to_string(),
            compute_checksum(audit_json.as_bytes()),
        );
        zip.start_file(file_names::PRIVACY_AUDIT, options)?;
        zip.write_all(audit_json.as_bytes())?;

        // Update manifest with checksums and write it
        manifest.checksums = checksums;
        let manifest_json = if self.options.pretty {
            serde_json::to_string_pretty(&manifest)?
        } else {
            serde_json::to_string(&manifest)?
        };
        zip.start_file(file_names::MANIFEST, options)?;
        zip.write_all(manifest_json.as_bytes())?;

        zip.finish()?;
        Ok(())
    }
}

impl Default for FingerprintWriter {
    fn default() -> Self {
        Self::new()
    }
}

/// Compute SHA-256 checksum of data.
fn compute_checksum(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    hex::encode(hasher.finalize())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::reader::FingerprintReader;
    use crate::models::{
        Manifest, PrivacyAudit, PrivacyLevel, PrivacyMetadata, SchemaFingerprint, SourceMetadata,
        StatisticsFingerprint,
    };
    use std::io::Cursor;
    use zip::ZipArchive;

    #[test]
    fn test_write_fingerprint() {
        let source = SourceMetadata::new("Test source", vec!["test_table".to_string()], 100);
        let privacy = PrivacyMetadata::from_level(PrivacyLevel::Standard);
        let manifest = Manifest::new(source, privacy);
        let schema = SchemaFingerprint::new();
        let statistics = StatisticsFingerprint::new();
        let privacy_audit = PrivacyAudit::new(1.0, 5);

        let fingerprint = Fingerprint::new(manifest, schema, statistics, privacy_audit);

        let mut buffer = Cursor::new(Vec::new());
        let writer = FingerprintWriter::new();
        writer.write(&fingerprint, &mut buffer).unwrap();

        // Verify the buffer is not empty and starts with ZIP magic bytes
        let data = buffer.into_inner();
        assert!(!data.is_empty());
        assert_eq!(&data[0..2], b"PK"); // ZIP magic bytes
    }

    #[test]
    fn round_trip_skips_empty_schema_and_statistics() {
        let source = SourceMetadata::new("test", vec![], 0);
        let privacy = PrivacyMetadata::from_level(PrivacyLevel::Standard);
        let manifest = Manifest::new(source, privacy);
        let fp = Fingerprint::new(
            manifest,
            SchemaFingerprint::new(),
            StatisticsFingerprint::new(),
            PrivacyAudit::new(1.0, 5),
        );

        let mut buffer = Cursor::new(Vec::new());
        let writer = FingerprintWriter::new();
        writer.write(&fp, &mut buffer).unwrap();

        // Inspect the ZIP — schema.yaml and statistics.yaml should be absent.
        let data = buffer.into_inner();
        let archive = ZipArchive::new(Cursor::new(data.clone())).unwrap();
        let names: Vec<&str> = archive.file_names().collect();
        assert!(
            !names.contains(&file_names::SCHEMA),
            "empty schema should NOT be in the ZIP, got names: {names:?}"
        );
        assert!(
            !names.contains(&file_names::STATISTICS),
            "empty statistics should NOT be in the ZIP, got names: {names:?}"
        );

        // Re-read — should produce equivalent empty defaults.
        let reader = FingerprintReader::new();
        let loaded = reader.read(Cursor::new(data)).unwrap();
        assert!(loaded.schema.is_empty(), "re-read schema should be empty");
        assert!(
            loaded.statistics.is_empty(),
            "re-read statistics should be empty"
        );
    }
}