opentdf 0.18.0

Rust implementation of OpenTDF (Trusted Data Format)
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
//! High-level TDF API for simplified encryption and decryption
//!
//! This module provides a clean, fluent API for common TDF operations.

use crate::archive::{TdfArchiveBuilder, TdfArchiveMemoryBuilder, TdfError};
use crate::manifest::{IntegrityInformationExt, KeyAccessExt, TdfManifest, TdfManifestExt};
use crate::policy::Policy;
use opentdf_crypto::TdfEncryption;
use std::path::Path;

#[cfg(feature = "kas-client")]
use crate::archive::{DEFAULT_MAX_PAYLOAD_SIZE, TdfArchive};

#[cfg(feature = "kas-client")]
use crate::kas::KasClient;

/// High-level TDF operations
///
/// # Examples
///
/// ```no_run
/// use opentdf::Tdf;
/// # use opentdf::Policy;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let policy = Policy::new("uuid".to_string(), vec![], vec![]);
///
/// // Encrypt data
/// Tdf::encrypt(b"Sensitive data")
///     .kas_url("https://kas.example.com")
///     .policy(policy)
///     .to_file("output.tdf")?;
/// # Ok(())
/// # }
/// ```
pub struct Tdf;

impl Tdf {
    /// Encrypt data to TDF format
    ///
    /// Returns a builder that allows setting KAS URL, policy, and output options.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use opentdf::{Tdf, Policy};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let policy = Policy::new("uuid".to_string(), vec![], vec![]);
    /// let encrypted = Tdf::encrypt(b"Sensitive data")
    ///     .kas_url("https://kas.example.com")
    ///     .policy(policy)
    ///     .to_bytes()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn encrypt(data: impl Into<Vec<u8>>) -> TdfEncryptBuilder {
        TdfEncryptBuilder::new(data.into())
    }

    /// Encrypt a file to TDF format
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use opentdf::{Tdf, Policy};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let policy = Policy::new("uuid".to_string(), vec![], vec![]);
    /// Tdf::encrypt_file("input.txt", "output.tdf")
    ///     .kas_url("https://kas.example.com")
    ///     .policy(policy)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn encrypt_file(
        input: impl AsRef<Path>,
        output: impl AsRef<Path>,
    ) -> TdfEncryptFileBuilder {
        TdfEncryptFileBuilder::new(input.as_ref().to_path_buf(), output.as_ref().to_path_buf())
    }

    /// Decrypt TDF data using a builder pattern
    ///
    /// Returns a builder that allows setting KAS client and output options.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use opentdf::{Tdf, kas::KasClient};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let config = opentdf::kas_discovery::OpentdfConfiguration::for_kas_connect(
    ///     "https://kas.example.com",
    /// );
    /// let kas_client = KasClient::new(&config, "token")?;
    /// let tdf_data = std::fs::read("encrypted.tdf")?;
    /// let plaintext = Tdf::decrypt(tdf_data)
    ///     .kas_client(kas_client)
    ///     .to_bytes()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "kas-client")]
    pub fn decrypt(data: impl Into<Vec<u8>>) -> TdfDecryptBuilder {
        TdfDecryptBuilder::new(data.into())
    }

    /// Decrypt a TDF file using a builder pattern
    ///
    /// Returns a builder that allows setting KAS client and output options.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use opentdf::{Tdf, kas::KasClient};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let config = opentdf::kas_discovery::OpentdfConfiguration::for_kas_connect(
    ///     "https://kas.example.com",
    /// );
    /// let kas_client = KasClient::new(&config, "token")?;
    /// let plaintext = Tdf::decrypt_file("encrypted.tdf")
    ///     .kas_client(kas_client)
    ///     .to_bytes()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "kas-client")]
    pub fn decrypt_file(path: impl AsRef<Path>) -> TdfDecryptFileBuilder {
        TdfDecryptFileBuilder::new(path.as_ref().to_path_buf())
    }
}

/// Builder for encrypting data to TDF format
pub struct TdfEncryptBuilder {
    data: Vec<u8>,
    kas_url: Option<String>,
    policy: Option<Policy>,
    mime_type: Option<String>,
    segment_size: usize,
}

impl TdfEncryptBuilder {
    pub(crate) fn new(data: Vec<u8>) -> Self {
        const DEFAULT_SEGMENT_SIZE: usize = 2 * 1024 * 1024; // 2MB
        Self {
            data,
            kas_url: None,
            policy: None,
            mime_type: None,
            segment_size: DEFAULT_SEGMENT_SIZE,
        }
    }

    /// Set the KAS URL for key access
    #[must_use]
    pub fn kas_url(mut self, url: impl Into<String>) -> Self {
        self.kas_url = Some(url.into());
        self
    }

    /// Set the access control policy
    #[must_use]
    pub fn policy(mut self, policy: Policy) -> Self {
        self.policy = Some(policy);
        self
    }

    /// Set the MIME type for the encrypted data
    #[must_use]
    pub fn mime_type(mut self, mime_type: impl Into<String>) -> Self {
        self.mime_type = Some(mime_type.into());
        self
    }

    /// Set the segment size for encryption (default: 2MB)
    #[must_use]
    pub fn segment_size(mut self, size: usize) -> Self {
        self.segment_size = size;
        self
    }

    /// Build and return encrypted TDF as bytes
    pub fn to_bytes(self) -> Result<Vec<u8>, TdfError> {
        let (manifest, segments, _encryption) = self.prepare_tdf()?;

        // Use in-memory builder
        let mut builder = TdfArchiveMemoryBuilder::new();
        builder.add_entry_with_segments(&manifest, &segments, 0)?;
        builder.finish()
    }

    /// Build and write encrypted TDF to file
    pub fn to_file(self, path: impl AsRef<Path>) -> Result<(), TdfError> {
        let (manifest, segments, _encryption) = self.prepare_tdf()?;

        // Use file-based builder
        let mut builder = TdfArchiveBuilder::new(path.as_ref())?;
        builder.add_entry_with_segments(&manifest, &segments, 0)?;
        builder.finish()?;
        Ok(())
    }

    /// Prepare TDF components (manifest, segments, encryption)
    ///
    /// This shared method is used by both to_bytes() and to_file()
    fn prepare_tdf(self) -> Result<(TdfManifest, Vec<Vec<u8>>, TdfEncryption), TdfError> {
        // Validate required fields
        let kas_url = self
            .kas_url
            .ok_or_else(|| TdfError::MissingRequiredField { field: "kas_url" })?;

        // Create encryption
        let tdf_encryption = TdfEncryption::new().map_err(|e| TdfError::CryptoError {
            algorithm: "AES-256-GCM".to_string(),
            reason: "Encryption setup failed".to_string(),
            source: Some(Box::new(e)),
        })?;

        // Encrypt with segments
        let segmented = tdf_encryption
            .encrypt_with_segments(&self.data, self.segment_size)
            .map_err(|e| TdfError::CryptoError {
                algorithm: "AES-256-GCM".to_string(),
                reason: "Encryption failed".to_string(),
                source: Some(Box::new(e)),
            })?;

        // Build manifest
        let mut manifest = TdfManifest::new("0.payload".to_string(), kas_url);
        manifest.encryption_information.method.algorithm = "AES-256-GCM".to_string();
        manifest.encryption_information.method.iv = String::new(); // Segments have their own IVs

        if let Some(mime_type) = self.mime_type {
            manifest.payload.mime_type = Some(mime_type);
        }

        // Set policy if provided
        if let Some(policy) = self.policy {
            manifest
                .set_policy(&policy)
                .map_err(|e| TdfError::PolicyValidationFailed {
                    policy_id: policy.uuid.clone(),
                    errors: vec![e.to_string()],
                })?;

            // Generate policy binding
            let policy_json = policy
                .to_json()
                .map_err(|e| TdfError::PolicyValidationFailed {
                    policy_id: policy.uuid.clone(),
                    errors: vec![format!("Policy serialization failed: {}", e)],
                })?;

            manifest.encryption_information.key_access[0]
                .generate_policy_binding_raw(&policy_json, tdf_encryption.payload_key())
                .map_err(|e| TdfError::PolicyValidationFailed {
                    policy_id: policy.uuid.clone(),
                    errors: vec![format!("Policy binding generation failed: {}", e)],
                })?;
        }

        // Add segment information
        use crate::manifest::Segment;
        for seg_info in &segmented.segment_info {
            manifest
                .encryption_information
                .integrity_information
                .segments
                .push(Segment {
                    hash: seg_info.hash.clone(),
                    segment_size: Some(seg_info.plaintext_size),
                    encrypted_segment_size: Some(seg_info.encrypted_size),
                });
        }

        // Set segment defaults
        if let Some(first_seg) = segmented.segment_info.first() {
            manifest
                .encryption_information
                .integrity_information
                .segment_size_default = first_seg.plaintext_size;
            manifest
                .encryption_information
                .integrity_information
                .encrypted_segment_size_default = first_seg.encrypted_size;
        }

        // Generate root signature
        manifest
            .encryption_information
            .integrity_information
            .generate_root_signature(&segmented.gmac_tags, tdf_encryption.payload_key())
            .map_err(|e| TdfError::CryptoError {
                algorithm: "HMAC-SHA256".to_string(),
                reason: format!("Root signature generation failed: {}", e),
                source: None,
            })?;

        Ok((manifest, segmented.segments, tdf_encryption))
    }
}

/// Builder for encrypting files to TDF format
pub struct TdfEncryptFileBuilder {
    input_path: std::path::PathBuf,
    output_path: std::path::PathBuf,
    kas_url: Option<String>,
    policy: Option<Policy>,
    mime_type: Option<String>,
    segment_size: usize,
}

impl TdfEncryptFileBuilder {
    pub(crate) fn new(input_path: std::path::PathBuf, output_path: std::path::PathBuf) -> Self {
        const DEFAULT_SEGMENT_SIZE: usize = 2 * 1024 * 1024; // 2MB
        Self {
            input_path,
            output_path,
            kas_url: None,
            policy: None,
            mime_type: None,
            segment_size: DEFAULT_SEGMENT_SIZE,
        }
    }

    /// Set the KAS URL for key access
    #[must_use]
    pub fn kas_url(mut self, url: impl Into<String>) -> Self {
        self.kas_url = Some(url.into());
        self
    }

    /// Set the access control policy
    #[must_use]
    pub fn policy(mut self, policy: Policy) -> Self {
        self.policy = Some(policy);
        self
    }

    /// Set the MIME type for the encrypted file
    #[must_use]
    pub fn mime_type(mut self, mime_type: impl Into<String>) -> Self {
        self.mime_type = Some(mime_type.into());
        self
    }

    /// Set the segment size for encryption (default: 2MB)
    #[must_use]
    pub fn segment_size(mut self, size: usize) -> Self {
        self.segment_size = size;
        self
    }

    /// Build the encrypted TDF file
    pub fn build(self) -> Result<(), TdfError> {
        let data = std::fs::read(&self.input_path)?;

        let mut builder = TdfEncryptBuilder::new(data);

        if let Some(kas_url) = self.kas_url {
            builder = builder.kas_url(kas_url);
        }

        if let Some(policy) = self.policy {
            builder = builder.policy(policy);
        }

        if let Some(mime_type) = self.mime_type {
            builder = builder.mime_type(mime_type);
        }

        builder = builder.segment_size(self.segment_size);

        builder.to_file(self.output_path)
    }
}

/// Builder for decrypting TDF data
///
/// Provides a fluent API for TDF decryption with optional KAS integration.
#[cfg(feature = "kas-client")]
pub struct TdfDecryptBuilder {
    data: Vec<u8>,
    kas_client: Option<KasClient>,
    max_payload_size: u64,
}

#[cfg(feature = "kas-client")]
impl TdfDecryptBuilder {
    pub(crate) fn new(data: Vec<u8>) -> Self {
        Self {
            data,
            kas_client: None,
            max_payload_size: DEFAULT_MAX_PAYLOAD_SIZE,
        }
    }

    /// Set the KAS client for key unwrapping
    #[must_use]
    pub fn kas_client(mut self, client: KasClient) -> Self {
        self.kas_client = Some(client);
        self
    }

    /// Set the largest encrypted payload, in bytes, that will be read into
    /// memory (default: [`DEFAULT_MAX_PAYLOAD_SIZE`]).
    ///
    /// A larger payload fails with [`TdfError::MemberTooLarge`] before any
    /// KAS request is made. See [`TdfArchive::with_max_payload_size`].
    #[must_use]
    pub fn max_payload_size(mut self, limit: u64) -> Self {
        self.max_payload_size = limit;
        self
    }

    /// Decrypt and return plaintext as bytes
    pub async fn to_bytes(self) -> Result<Vec<u8>, TdfError> {
        let kas_client = self
            .kas_client
            .ok_or_else(|| TdfError::MissingRequiredField {
                field: "kas_client",
            })?;

        let cursor = std::io::Cursor::new(self.data);
        let mut archive = TdfArchive::new(cursor)?.with_max_payload_size(self.max_payload_size);
        let entry = archive.by_index()?;
        entry.decrypt_with_kas(&kas_client).await
    }

    /// Decrypt and write plaintext to file
    pub async fn to_file(self, path: impl AsRef<Path>) -> Result<(), TdfError> {
        let plaintext = self.to_bytes().await?;
        std::fs::write(path, plaintext)?;
        Ok(())
    }
}

/// Builder for decrypting TDF files
///
/// Provides a fluent API for file-based TDF decryption with optional KAS integration.
#[cfg(feature = "kas-client")]
pub struct TdfDecryptFileBuilder {
    input_path: std::path::PathBuf,
    kas_client: Option<KasClient>,
    max_payload_size: u64,
}

#[cfg(feature = "kas-client")]
impl TdfDecryptFileBuilder {
    pub(crate) fn new(input_path: std::path::PathBuf) -> Self {
        Self {
            input_path,
            kas_client: None,
            max_payload_size: DEFAULT_MAX_PAYLOAD_SIZE,
        }
    }

    /// Set the KAS client for key unwrapping
    #[must_use]
    pub fn kas_client(mut self, client: KasClient) -> Self {
        self.kas_client = Some(client);
        self
    }

    /// Set the largest encrypted payload, in bytes, that will be read into
    /// memory (default: [`DEFAULT_MAX_PAYLOAD_SIZE`]).
    ///
    /// A larger payload fails with [`TdfError::MemberTooLarge`] before any
    /// KAS request is made. See [`TdfArchive::with_max_payload_size`].
    #[must_use]
    pub fn max_payload_size(mut self, limit: u64) -> Self {
        self.max_payload_size = limit;
        self
    }

    /// Decrypt and return plaintext as bytes
    pub async fn to_bytes(self) -> Result<Vec<u8>, TdfError> {
        let kas_client = self
            .kas_client
            .ok_or_else(|| TdfError::MissingRequiredField {
                field: "kas_client",
            })?;

        let mut archive =
            TdfArchive::open(self.input_path)?.with_max_payload_size(self.max_payload_size);
        let entry = archive.by_index()?;
        entry.decrypt_with_kas(&kas_client).await
    }

    /// Decrypt and write plaintext to file
    pub async fn to_file(self, output_path: impl AsRef<Path>) -> Result<(), TdfError> {
        let plaintext = self.to_bytes().await?;
        std::fs::write(output_path, plaintext)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::NamedTempFile;

    #[test]
    fn test_encrypt_to_bytes() -> Result<(), Box<dyn std::error::Error>> {
        let data = b"Hello, TDF!";

        let encrypted = Tdf::encrypt(data)
            .kas_url("https://kas.example.com")
            .to_bytes()?;

        assert!(!encrypted.is_empty());
        Ok(())
    }

    #[test]
    fn test_encrypt_to_file() -> Result<(), Box<dyn std::error::Error>> {
        let temp_file = NamedTempFile::new()?;
        let data = b"Hello, TDF!";

        Tdf::encrypt(data)
            .kas_url("https://kas.example.com")
            .to_file(temp_file.path())?;

        assert!(temp_file.path().exists());
        Ok(())
    }

    #[test]
    fn test_encrypt_file() -> Result<(), Box<dyn std::error::Error>> {
        let input_file = NamedTempFile::new()?;
        let output_file = NamedTempFile::new()?;

        std::fs::write(input_file.path(), b"File contents")?;

        Tdf::encrypt_file(input_file.path(), output_file.path())
            .kas_url("https://kas.example.com")
            .build()?;

        assert!(output_file.path().exists());
        Ok(())
    }

    #[test]
    fn test_missing_kas_url_error() {
        let data = b"Hello, TDF!";

        let result = Tdf::encrypt(data).to_bytes();

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.error_code(), "OPENTDF_E_FIELD_REQUIRED");
        assert!(err.to_string().contains("kas_url"));
    }

    #[test]
    fn test_with_policy() -> Result<(), Box<dyn std::error::Error>> {
        let policy = Policy::new(
            "test-uuid".to_string(),
            vec![],
            vec!["user@example.com".to_string()],
        );

        let temp_file = NamedTempFile::new()?;

        Tdf::encrypt(b"Test data")
            .kas_url("https://kas.example.com")
            .policy(policy)
            .mime_type("text/plain")
            .to_file(temp_file.path())?;

        assert!(temp_file.path().exists());
        Ok(())
    }

    /// The decrypt builders pass their payload limit to the archive reader,
    /// which refuses an oversized payload before any KAS request is made.
    #[cfg(feature = "kas-client")]
    #[tokio::test]
    async fn decrypt_builders_honour_max_payload_size() -> Result<(), Box<dyn std::error::Error>> {
        fn kas_client() -> KasClient {
            let config = crate::kas_discovery::OpentdfConfiguration::for_kas_connect(
                "https://kas.example.com",
            );
            match KasClient::new(&config, "token") {
                Ok(client) => client,
                Err(e) => panic!("KAS client: {e}"),
            }
        }

        let encrypted = Tdf::encrypt(b"more than eight bytes of payload")
            .kas_url("https://kas.example.com")
            .to_bytes()?;

        let err = Tdf::decrypt(encrypted.clone())
            .kas_client(kas_client())
            .max_payload_size(8)
            .to_bytes()
            .await
            .expect_err("payload is over the limit");
        assert!(
            matches!(&err, TdfError::MemberTooLarge { limit: 8, .. }),
            "{err:?}"
        );

        let temp_file = NamedTempFile::new()?;
        std::fs::write(temp_file.path(), &encrypted)?;
        let err = Tdf::decrypt_file(temp_file.path())
            .kas_client(kas_client())
            .max_payload_size(8)
            .to_bytes()
            .await
            .expect_err("payload is over the limit");
        assert!(
            matches!(&err, TdfError::MemberTooLarge { limit: 8, .. }),
            "{err:?}"
        );
        Ok(())
    }
}