1use opentdf::prelude::*;
2use std::collections::HashMap;
3use std::io::Cursor;
4use wasm_bindgen::prelude::*;
5
6mod kas;
7mod kas_trust;
8pub mod webcrypto;
10
11#[wasm_bindgen(start)]
13pub fn init() {
14 console_error_panic_hook::set_once();
15}
16
17#[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#[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 let kas_key_response = kas::fetch_kas_public_key(kas_url).await?;
86
87 let data_bytes = BASE64
89 .decode(data)
90 .map_err(|e| format!("Failed to decode data: {}", e))?;
91
92 let policy: Policy =
94 serde_json::from_str(policy_json).map_err(|e| format!("Failed to parse policy: {}", e))?;
95
96 let tdf_encryption =
98 TdfEncryption::new().map_err(|e| format!("Failed to create encryption: {}", e))?;
99
100 let segment_size = 1024 * 1024; let segmented_payload = tdf_encryption
103 .encrypt_with_segments(&data_bytes, segment_size)
104 .map_err(|e| format!("Failed to encrypt: {}", e))?;
105
106 let wrapped_key =
108 kas::wrap_key_with_rsa_oaep(tdf_encryption.payload_key(), &kas_key_response.public_key)
109 .await?;
110
111 let ciphertext_bytes: Vec<u8> = segmented_payload
113 .segments
114 .iter()
115 .flat_map(|s| s.iter().copied())
116 .collect();
117
118 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(); manifest
125 .set_policy(&policy)
126 .map_err(|e| format!("Failed to set policy: {}", e))?;
127
128 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 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 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 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 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 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 Ok(BASE64.encode(&tdf_bytes))
186}
187
188#[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 let tdf_bytes = BASE64
208 .decode(tdf_data)
209 .map_err(|e| format!("Failed to decode TDF: {}", e))?;
210
211 let cursor = Cursor::new(tdf_bytes);
213 let mut archive = TdfArchive::new(cursor).map_err(|e| format!("Failed to open TDF: {}", e))?;
214
215 let entry = archive
217 .by_index()
218 .map_err(|e| format!("Failed to read TDF entry: {}", e))?;
219
220 serde_json::to_string(&entry.manifest)
222 .map_err(|e| format!("Failed to serialize manifest: {}", e))
223}
224
225#[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 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 let rewrap_endpoint = kas_trust::trusted_rewrap_endpoint(&entry.manifest, allowed_kas_urls)
291 .map_err(|e| e.to_string())?;
292
293 let ephemeral_keypair = kas::generate_rsa_keypair().await?;
295
296 let unsigned_request =
298 kas::build_rewrap_request(&entry.manifest, &ephemeral_keypair.public_key_pem)?;
299
300 let signed_token = kas::create_signed_jwt(&unsigned_request)?;
302
303 let rewrap_response =
305 kas::post_rewrap_request(&rewrap_endpoint, kas_token, &signed_token).await?;
306
307 let payload_key =
309 kas::unwrap_rsa_oaep(&rewrap_response.wrapped_key, &ephemeral_keypair.private_key).await?;
310
311 let plaintext = entry
317 .decrypt_with_key(&payload_key)
318 .map_err(|e| format!("Decryption failed: {}", e))?;
319
320 Ok(BASE64.encode(&plaintext))
322}
323
324#[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#[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 let policy: AttributePolicy =
365 serde_json::from_str(policy_json).map_err(|e| format!("Failed to parse policy: {}", e))?;
366
367 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 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 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 policy
415 .evaluate(&user_attrs)
416 .map_err(|e| format!("Policy evaluation failed: {}", e))
417}
418
419#[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#[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 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 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 #[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}