Skip to main content

opentdf_wasm/
lib.rs

1use opentdf::prelude::*;
2use std::collections::HashMap;
3use std::io::Cursor;
4use wasm_bindgen::prelude::*;
5
6mod kas;
7mod kas_trust;
8/// WebCrypto RSA-OAEP operations via browser's SubtleCrypto API
9pub mod webcrypto;
10
11// Set up panic hook for better error messages in the browser
12#[wasm_bindgen(start)]
13pub fn init() {
14    console_error_panic_hook::set_once();
15}
16
17/// Result type for WASM operations
18#[wasm_bindgen]
19pub struct WasmResult {
20    success: bool,
21    data: Option<String>,
22    error: Option<String>,
23}
24
25#[wasm_bindgen]
26impl WasmResult {
27    #[wasm_bindgen(getter)]
28    pub fn success(&self) -> bool {
29        self.success
30    }
31
32    #[wasm_bindgen(getter)]
33    pub fn data(&self) -> Option<String> {
34        self.data.clone()
35    }
36
37    #[wasm_bindgen(getter)]
38    pub fn error(&self) -> Option<String> {
39        self.error.clone()
40    }
41}
42
43impl WasmResult {
44    fn ok(data: String) -> Self {
45        WasmResult {
46            success: true,
47            data: Some(data),
48            error: None,
49        }
50    }
51
52    fn err(error: String) -> Self {
53        WasmResult {
54            success: false,
55            data: None,
56            error: Some(error),
57        }
58    }
59}
60
61/// Create a TDF archive with encrypted data (async)
62///
63/// This function fetches the KAS public key and wraps the DEK securely.
64/// The DEK never leaves the WASM environment.
65///
66/// # Arguments
67/// * `data` - Base64-encoded data to encrypt
68/// * `kas_url` - KAS (Key Access Service) URL
69/// * `policy_json` - JSON string containing the policy
70///
71/// # Returns
72/// Promise resolving to WasmResult with base64-encoded TDF archive
73#[wasm_bindgen]
74pub async fn tdf_create(data: String, kas_url: String, policy_json: String) -> WasmResult {
75    match _tdf_create_impl(&data, &kas_url, &policy_json).await {
76        Ok(result) => WasmResult::ok(result),
77        Err(e) => WasmResult::err(e),
78    }
79}
80
81async fn _tdf_create_impl(data: &str, kas_url: &str, policy_json: &str) -> Result<String, String> {
82    use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
83
84    // Step 1: Fetch KAS public key from the server
85    let kas_key_response = kas::fetch_kas_public_key(kas_url).await?;
86
87    // Step 2: Decode base64 input data
88    let data_bytes = BASE64
89        .decode(data)
90        .map_err(|e| format!("Failed to decode data: {}", e))?;
91
92    // Step 3: Parse policy
93    let policy: Policy =
94        serde_json::from_str(policy_json).map_err(|e| format!("Failed to parse policy: {}", e))?;
95
96    // Step 4: Create TDF encryption instance with generated keys
97    let tdf_encryption =
98        TdfEncryption::new().map_err(|e| format!("Failed to create encryption: {}", e))?;
99
100    // Step 5: Encrypt the data with segments (required for proper decryption)
101    let segment_size = 1024 * 1024; // 1MB segments (default)
102    let segmented_payload = tdf_encryption
103        .encrypt_with_segments(&data_bytes, segment_size)
104        .map_err(|e| format!("Failed to encrypt: {}", e))?;
105
106    // Step 6: Wrap the payload key with KAS public key using RSA-OAEP (via WebCrypto)
107    let wrapped_key =
108        kas::wrap_key_with_rsa_oaep(tdf_encryption.payload_key(), &kas_key_response.public_key)
109            .await?;
110
111    // Step 7: Concatenate all encrypted segments
112    let ciphertext_bytes: Vec<u8> = segmented_payload
113        .segments
114        .iter()
115        .flat_map(|s| s.iter().copied())
116        .collect();
117
118    // Step 8: Create manifest
119    let mut manifest = TdfManifest::new("0.payload".to_string(), kas_url.to_string());
120    manifest.encryption_information.method.algorithm = "AES-256-GCM".to_string();
121    manifest.encryption_information.method.iv = String::new(); // Segments have their own IVs
122
123    // Step 9: Set policy on manifest
124    manifest
125        .set_policy(&policy)
126        .map_err(|e| format!("Failed to set policy: {}", e))?;
127
128    // Step 10: Generate policy binding
129    let policy_json_bytes = policy
130        .to_json()
131        .map_err(|e| format!("Failed to serialize policy: {}", e))?;
132
133    manifest.encryption_information.key_access[0]
134        .generate_policy_binding_raw(&policy_json_bytes, tdf_encryption.payload_key())
135        .map_err(|e| format!("Failed to generate policy binding: {}", e))?;
136
137    // Step 11: Set wrapped key and kid
138    manifest.encryption_information.key_access[0].wrapped_key = wrapped_key;
139    manifest.encryption_information.key_access[0].kid = Some(kas_key_response.kid);
140
141    // Step 12: Set segment information in manifest
142    use opentdf::manifest::Segment;
143    for seg_info in &segmented_payload.segment_info {
144        manifest
145            .encryption_information
146            .integrity_information
147            .segments
148            .push(Segment {
149                hash: seg_info.hash.clone(),
150                segment_size: Some(seg_info.plaintext_size),
151                encrypted_segment_size: Some(seg_info.encrypted_size),
152            });
153    }
154
155    // Set segment defaults
156    if let Some(first_seg) = segmented_payload.segment_info.first() {
157        manifest
158            .encryption_information
159            .integrity_information
160            .segment_size_default = first_seg.plaintext_size;
161        manifest
162            .encryption_information
163            .integrity_information
164            .encrypted_segment_size_default = first_seg.encrypted_size;
165    }
166
167    // Generate root signature
168    manifest
169        .encryption_information
170        .integrity_information
171        .generate_root_signature(&segmented_payload.gmac_tags, tdf_encryption.payload_key())
172        .map_err(|e| format!("Failed to generate root signature: {}", e))?;
173
174    // Step 13: Build TDF archive in memory
175    let mut builder = TdfArchiveMemoryBuilder::new();
176    builder
177        .add_entry(&manifest, &ciphertext_bytes, 0)
178        .map_err(|e| format!("Failed to add entry: {}", e))?;
179
180    let tdf_bytes = builder
181        .finish()
182        .map_err(|e| format!("Failed to finish archive: {}", e))?;
183
184    // Step 14: Encode result as base64
185    Ok(BASE64.encode(&tdf_bytes))
186}
187
188/// Read a TDF archive and return its manifest
189///
190/// # Arguments
191/// * `tdf_data` - Base64-encoded TDF archive
192///
193/// # Returns
194/// JSON string containing the TDF manifest
195#[wasm_bindgen]
196pub fn tdf_read(tdf_data: &str) -> WasmResult {
197    match _tdf_read_impl(tdf_data) {
198        Ok(result) => WasmResult::ok(result),
199        Err(e) => WasmResult::err(e),
200    }
201}
202
203fn _tdf_read_impl(tdf_data: &str) -> Result<String, String> {
204    use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
205
206    // Decode base64 TDF data
207    let tdf_bytes = BASE64
208        .decode(tdf_data)
209        .map_err(|e| format!("Failed to decode TDF: {}", e))?;
210
211    // Open TDF archive from bytes using Cursor
212    let cursor = Cursor::new(tdf_bytes);
213    let mut archive = TdfArchive::new(cursor).map_err(|e| format!("Failed to open TDF: {}", e))?;
214
215    // Get entry and manifest
216    let entry = archive
217        .by_index()
218        .map_err(|e| format!("Failed to read TDF entry: {}", e))?;
219
220    // Serialize manifest to JSON
221    serde_json::to_string(&entry.manifest)
222        .map_err(|e| format!("Failed to serialize manifest: {}", e))
223}
224
225/// Decrypt a TDF archive using KAS rewrap protocol (async)
226///
227/// This performs the complete KAS rewrap flow:
228/// 1. Parse TDF manifest and extract policy/key access info
229/// 2. Check the manifest's KAS URL against `allowed_kas_urls`
230/// 3. Generate ephemeral RSA-2048 key pair
231/// 4. Build and sign JWT rewrap request (ES256)
232/// 5. POST to KAS /v2/rewrap endpoint with OAuth token
233/// 6. Unwrap returned key using RSA-OAEP (SHA-1)
234/// 7. Decrypt payload with AES-256-GCM
235///
236/// # Security
237/// A TDF is untrusted input and names its own KAS. The OAuth token is sent
238/// only if the origin (scheme, host and port) of that KAS URL equals the
239/// origin of an entry of `allowed_kas_urls`; otherwise decryption fails before
240/// any request is made. An empty list rejects every TDF. URLs must use
241/// `https`, except `http` for loopback hosts during development. Redirects
242/// from the KAS are not followed.
243///
244/// Only the origin of each entry is compared: the TDF still chooses the path
245/// under that origin, so list origins that are dedicated to a KAS.
246///
247/// # Arguments
248/// * `tdf_data` - Base64-encoded TDF archive
249/// * `kas_token` - OAuth bearer token for KAS authentication
250/// * `allowed_kas_urls` - URLs of the KAS instances the caller trusts with
251///   `kas_token` (e.g. `["https://kas.example.com"]`)
252///
253/// # Returns
254/// Promise resolving to WasmResult with base64-encoded plaintext
255#[wasm_bindgen]
256pub async fn tdf_decrypt_with_kas(
257    tdf_data: String,
258    kas_token: String,
259    allowed_kas_urls: Vec<String>,
260) -> WasmResult {
261    match _tdf_decrypt_with_kas_impl(&tdf_data, &kas_token, &allowed_kas_urls).await {
262        Ok(plaintext_b64) => WasmResult::ok(plaintext_b64),
263        Err(e) => WasmResult::err(e),
264    }
265}
266
267async fn _tdf_decrypt_with_kas_impl(
268    tdf_data: &str,
269    kas_token: &str,
270    allowed_kas_urls: &[String],
271) -> Result<String, String> {
272    use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
273
274    // Step 1: Parse TDF archive and extract manifest
275    let tdf_bytes = BASE64
276        .decode(tdf_data)
277        .map_err(|e| format!("Failed to decode TDF: {}", e))?;
278
279    let cursor = Cursor::new(tdf_bytes.clone());
280    let mut archive = TdfArchive::new(cursor).map_err(|e| format!("Failed to open TDF: {}", e))?;
281
282    let entry = archive
283        .by_index()
284        .map_err(|e| format!("Failed to read TDF entry: {}", e))?;
285
286    // Step 2: Decide whether the KAS named by the manifest may be contacted.
287    //
288    // The manifest is untrusted and the rewrap request carries the caller's
289    // bearer token, so this runs before anything else is done with the TDF.
290    let rewrap_endpoint = kas_trust::trusted_rewrap_endpoint(&entry.manifest, allowed_kas_urls)
291        .map_err(|e| e.to_string())?;
292
293    // Step 3: Generate ephemeral RSA-2048 key pair (via WebCrypto)
294    let ephemeral_keypair = kas::generate_rsa_keypair().await?;
295
296    // Step 4: Build unsigned rewrap request
297    let unsigned_request =
298        kas::build_rewrap_request(&entry.manifest, &ephemeral_keypair.public_key_pem)?;
299
300    // Step 5: Sign request with JWT (ES256)
301    let signed_token = kas::create_signed_jwt(&unsigned_request)?;
302
303    // Step 6: POST to the trusted KAS /v2/rewrap endpoint
304    let rewrap_response =
305        kas::post_rewrap_request(&rewrap_endpoint, kas_token, &signed_token).await?;
306
307    // Step 7: Unwrap payload key using RSA-OAEP (via WebCrypto)
308    let payload_key =
309        kas::unwrap_rsa_oaep(&rewrap_response.wrapped_key, &ephemeral_keypair.private_key).await?;
310
311    // Step 8: Decrypt payload
312    //
313    // `decrypt_with_key` verifies every manifest segment hash and the root
314    // signature against the GMAC tags of the ciphertext, and aborts before
315    // returning plaintext if either check fails.
316    let plaintext = entry
317        .decrypt_with_key(&payload_key)
318        .map_err(|e| format!("Decryption failed: {}", e))?;
319
320    // Step 9: Return base64-encoded plaintext
321    Ok(BASE64.encode(&plaintext))
322}
323
324/// Create a policy from JSON
325///
326/// # Arguments
327/// * `policy_json` - JSON string containing policy definition
328///
329/// # Returns
330/// JSON string of the validated policy
331#[wasm_bindgen]
332pub fn policy_create(policy_json: &str) -> WasmResult {
333    match _policy_create_impl(policy_json) {
334        Ok(result) => WasmResult::ok(result),
335        Err(e) => WasmResult::err(e),
336    }
337}
338
339fn _policy_create_impl(policy_json: &str) -> Result<String, String> {
340    let policy: Policy =
341        serde_json::from_str(policy_json).map_err(|e| format!("Failed to parse policy: {}", e))?;
342
343    serde_json::to_string(&policy).map_err(|e| format!("Failed to serialize policy: {}", e))
344}
345
346/// Evaluate attribute-based access control policy
347///
348/// # Arguments
349/// * `policy_json` - JSON string containing the attribute policy
350/// * `attributes_json` - JSON string containing user attributes as key-value pairs
351///
352/// # Returns
353/// Boolean indicating whether access should be granted
354#[wasm_bindgen]
355pub fn access_evaluate(policy_json: &str, attributes_json: &str) -> WasmResult {
356    match _access_evaluate_impl(policy_json, attributes_json) {
357        Ok(result) => WasmResult::ok(result.to_string()),
358        Err(e) => WasmResult::err(e),
359    }
360}
361
362fn _access_evaluate_impl(policy_json: &str, attributes_json: &str) -> Result<bool, String> {
363    // Parse attribute policy
364    let policy: AttributePolicy =
365        serde_json::from_str(policy_json).map_err(|e| format!("Failed to parse policy: {}", e))?;
366
367    // Parse user attributes
368    let attrs: HashMap<String, serde_json::Value> = serde_json::from_str(attributes_json)
369        .map_err(|e| format!("Failed to parse attributes: {}", e))?;
370
371    // Convert to AttributeIdentifier -> AttributeValue map
372    let mut user_attrs: HashMap<AttributeIdentifier, AttributeValue> = HashMap::new();
373    for (key, value) in attrs {
374        let attr_id = AttributeIdentifier::from_string(&key)
375            .map_err(|e| format!("Invalid attribute identifier '{}': {}", key, e))?;
376
377        let attr_value = match value {
378            serde_json::Value::String(s) => AttributeValue::String(s),
379            serde_json::Value::Number(n) => AttributeValue::Number(n.as_f64().unwrap_or(0.0)),
380            serde_json::Value::Bool(b) => AttributeValue::Boolean(b),
381            serde_json::Value::Array(arr) => {
382                // Try to determine array type from first element
383                if let Some(first) = arr.first() {
384                    match first {
385                        serde_json::Value::String(_) => {
386                            let strings: Vec<String> = arr
387                                .iter()
388                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
389                                .collect();
390                            AttributeValue::StringArray(strings)
391                        }
392                        serde_json::Value::Number(_) => {
393                            let numbers: Vec<f64> = arr.iter().filter_map(|v| v.as_f64()).collect();
394                            AttributeValue::NumberArray(numbers)
395                        }
396                        _ => {
397                            return Err(format!(
398                                "Unsupported array element type for attribute '{}'",
399                                key
400                            ));
401                        }
402                    }
403                } else {
404                    AttributeValue::StringArray(vec![])
405                }
406            }
407            _ => return Err(format!("Unsupported value type for attribute '{}'", key)),
408        };
409
410        user_attrs.insert(attr_id, attr_value);
411    }
412
413    // Evaluate policy
414    policy
415        .evaluate(&user_attrs)
416        .map_err(|e| format!("Policy evaluation failed: {}", e))
417}
418
419/// Create an attribute identifier from namespace:name format
420///
421/// # Arguments
422/// * `identifier` - String in format "namespace:name"
423///
424/// # Returns
425/// JSON string containing the attribute identifier
426#[wasm_bindgen]
427pub fn attribute_identifier_create(identifier: &str) -> WasmResult {
428    match _attribute_identifier_create_impl(identifier) {
429        Ok(result) => WasmResult::ok(result),
430        Err(e) => WasmResult::err(e),
431    }
432}
433
434fn _attribute_identifier_create_impl(identifier: &str) -> Result<String, String> {
435    let attr_id = AttributeIdentifier::from_string(identifier)
436        .map_err(|e| format!("Failed to create attribute identifier: {}", e))?;
437
438    serde_json::to_string(&attr_id)
439        .map_err(|e| format!("Failed to serialize attribute identifier: {}", e))
440}
441
442/// Get version information
443#[wasm_bindgen]
444pub fn version() -> String {
445    env!("CARGO_PKG_VERSION").to_string()
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451    use wasm_bindgen_test::*;
452
453    #[wasm_bindgen_test]
454    fn test_version() {
455        let v = version();
456        assert!(!v.is_empty());
457    }
458
459    #[wasm_bindgen_test]
460    fn test_attribute_identifier_create() {
461        let result = attribute_identifier_create("gov.example:clearance");
462        assert!(result.success());
463        assert!(result.data().is_some());
464    }
465
466    #[wasm_bindgen_test]
467    fn test_policy_create() {
468        let policy_json = r#"{
469            "uuid": "test-uuid",
470            "body": {
471                "attributes": [],
472                "dissem": ["user@example.com"]
473            }
474        }"#;
475
476        let result = policy_create(policy_json);
477        assert!(result.success());
478        assert!(result.data().is_some());
479    }
480
481    /// Build a base64 TDF whose manifest names `kas_url` as its KAS
482    fn tdf_naming_kas(kas_url: &str) -> String {
483        tdf_with_manifest(&TdfManifest::new(
484            "0.payload".to_string(),
485            kas_url.to_string(),
486        ))
487    }
488
489    fn tdf_with_manifest(manifest: &TdfManifest) -> String {
490        use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
491
492        let mut builder = TdfArchiveMemoryBuilder::new();
493        builder.add_entry(manifest, b"ciphertext", 0).unwrap();
494        BASE64.encode(builder.finish().unwrap())
495    }
496
497    /// The error `tdf_decrypt_with_kas` must fail with for this TDF and allowlist
498    fn expected_trust_error(kas_url: &str, allowed: &[String]) -> String {
499        let manifest = TdfManifest::new("0.payload".to_string(), kas_url.to_string());
500        kas_trust::trusted_rewrap_endpoint(&manifest, allowed)
501            .unwrap_err()
502            .to_string()
503    }
504
505    #[wasm_bindgen_test]
506    async fn test_decrypt_rejects_empty_key_access() {
507        let mut manifest = TdfManifest::new(
508            "0.payload".to_string(),
509            "https://kas.example.com".to_string(),
510        );
511        manifest.encryption_information.key_access.clear();
512
513        let result = tdf_decrypt_with_kas(
514            tdf_with_manifest(&manifest),
515            "token".to_string(),
516            vec!["https://kas.example.com".to_string()],
517        )
518        .await;
519
520        assert!(!result.success());
521        assert_eq!(
522            result.error(),
523            Some(kas_trust::KasTrustError::NoKeyAccess.to_string())
524        );
525    }
526
527    // The three tests below run where no KAS is reachable. They pass only if
528    // the export stops at the trust check: getting any further would fail with
529    // a different error (key generation or the fetch itself).
530
531    #[wasm_bindgen_test]
532    async fn test_decrypt_refuses_kas_outside_allowlist() {
533        let kas_url = "https://kas.example.com.evil.com/kas";
534        let allowed = vec!["https://kas.example.com".to_string()];
535
536        let result = tdf_decrypt_with_kas(
537            tdf_naming_kas(kas_url),
538            "token".to_string(),
539            allowed.clone(),
540        )
541        .await;
542
543        assert!(!result.success());
544        assert_eq!(
545            result.error(),
546            Some(expected_trust_error(kas_url, &allowed))
547        );
548    }
549
550    #[wasm_bindgen_test]
551    async fn test_decrypt_refuses_empty_allowlist() {
552        let kas_url = "https://kas.example.com/kas";
553
554        let result =
555            tdf_decrypt_with_kas(tdf_naming_kas(kas_url), "token".to_string(), Vec::new()).await;
556
557        assert!(!result.success());
558        assert_eq!(result.error(), Some(expected_trust_error(kas_url, &[])));
559    }
560
561    #[wasm_bindgen_test]
562    async fn test_decrypt_refuses_non_loopback_http() {
563        let kas_url = "http://kas.example.com/kas";
564        let allowed = vec!["https://kas.example.com".to_string()];
565
566        let result = tdf_decrypt_with_kas(
567            tdf_naming_kas(kas_url),
568            "token".to_string(),
569            allowed.clone(),
570        )
571        .await;
572
573        assert!(!result.success());
574        assert_eq!(
575            result.error(),
576            Some(expected_trust_error(kas_url, &allowed))
577        );
578    }
579}