diff --git a/example-attestation-guest/src/lib.rs b/example-attestation-guest/src/lib.rs index 0b59b3b..278c507 100644 --- a/example-attestation-guest/src/lib.rs +++ b/example-attestation-guest/src/lib.rs @@ -17,10 +17,7 @@ impl bindings::exports::elastic::hal::run::Guest for Component { fn run() -> Vec { // 1. Query platform info let info = platform::get_platform_info(); - let _ = format!( - "Running on {} v{}", - info.platform_type, info.version - ); + let _ = format!("Running on {} v{}", info.platform_type, info.version); // 2. Generate random nonce as report-data let report_data = match random::get_random_bytes(32) { diff --git a/examples/basic_usage.rs b/examples/basic_usage.rs index d896e60..c351b87 100644 --- a/examples/basic_usage.rs +++ b/examples/basic_usage.rs @@ -4,28 +4,33 @@ use elastic_tee_hal::{ #[tokio::main] async fn main() -> HalResult<()> { + env_logger::Builder::from_default_env() + .filter_level(log::LevelFilter::Info) + .init(); + // Initialize the HAL let hal = ElasticTeeHal::new()?; - println!("ELASTIC TEE HAL initialized successfully"); + log::info!("ELASTIC TEE HAL initialized successfully"); // Get platform information let platform = hal.platform(); let platform_info = platform.get_platform_info().await?; - println!( + log::info!( "Platform: {} v{}", - platform_info.platform_type, platform_info.version + platform_info.platform_type, + platform_info.version ); // Generate attestation if platform_info.attestation_support { let attestation = platform.generate_attestation().await?; - println!("Generated attestation: {} bytes", attestation.len()); + log::info!("Generated attestation: {} bytes", attestation.len()); } // Test cryptographic operations let crypto = hal.crypto(); let key_pair = crypto.generate_keypair().await?; - println!( + log::info!( "Generated key pair: {} byte public key", key_pair.public_key.len() ); @@ -33,16 +38,16 @@ async fn main() -> HalResult<()> { // Test secure storage let storage = hal.storage(); let container = storage.create_container("test-container").await?; - println!("Created storage container: {:?}", container); + log::info!("Created storage container: {:?}", container); let data = b"Hello, TEE World!"; let object_id = storage .store_object(container, "greeting", data.to_vec()) .await?; - println!("Stored object: {:?}", object_id); + log::info!("Stored object: {:?}", object_id); let retrieved = storage.retrieve_object(container, "greeting").await?; - println!("Retrieved: {}", String::from_utf8_lossy(&retrieved)); + log::info!("Retrieved: {}", String::from_utf8_lossy(&retrieved)); Ok(()) } diff --git a/examples/enforcement_demo.rs b/examples/enforcement_demo.rs index ae0dd24..9333ffa 100644 --- a/examples/enforcement_demo.rs +++ b/examples/enforcement_demo.rs @@ -11,13 +11,17 @@ use elastic_tee_hal::enforcement::policy::{Quota, RateLimit}; use elastic_tee_hal::enforcement::*; fn main() -> Result<(), Box> { - println!("=== ELASTIC TEE HAL - Enforcement Layer Demo ===\n"); + env_logger::Builder::from_default_env() + .filter_level(log::LevelFilter::Info) + .init(); + + log::info!("=== ELASTIC TEE HAL - Enforcement Layer Demo ===\n"); // ======================================================================== // 1. Setup: Create policy engine with multiple entities // ======================================================================== - println!("1. Setting up enforcement layer with 4 entities:\n"); + log::info!("1. Setting up enforcement layer with 4 entities:\n"); let mut policy_engine = PolicyEngine::default(); @@ -31,7 +35,7 @@ fn main() -> Result<(), Box> { .with_rate_limit("platform", RateLimit::new(10)); // 10 attestations/sec max policy_engine.add_policy(attestation_policy)?; - println!(" ✓ attestation-service: platform + capabilities only (10 ops/sec limit)"); + log::info!(" ✓ attestation-service: platform + capabilities only (10 ops/sec limit)"); // Entity B: Crypto Worker (crypto + random) let crypto_worker_id = EntityId::new("crypto-worker"); @@ -51,7 +55,7 @@ fn main() -> Result<(), Box> { ); policy_engine.add_policy(crypto_policy)?; - println!(" ✓ crypto-worker: crypto + random + clock (1000 ops/sec, 10MB quota)"); + log::info!(" ✓ crypto-worker: crypto + random + clock (1000 ops/sec, 10MB quota)"); // Entity C: Untrusted Service (very limited - only random) let untrusted_id = EntityId::new("untrusted-service"); @@ -62,7 +66,7 @@ fn main() -> Result<(), Box> { .with_rate_limit("random", RateLimit::new(100)); // Very limited policy_engine.add_policy(untrusted_policy)?; - println!(" ✓ untrusted-service: random only (100 ops/sec limit)"); + log::info!(" ✓ untrusted-service: random only (100 ops/sec limit)"); // Entity D: Umbrella Entity (full privileges + can grant) let umbrella_id = EntityId::new("supervisor"); @@ -70,53 +74,53 @@ fn main() -> Result<(), Box> { EntityPolicy::new(umbrella_id.clone(), CapabilitySet::all()).as_umbrella(); policy_engine.add_policy(umbrella_policy)?; - println!(" ✓ supervisor: all capabilities + can grant/revoke\n"); + log::info!(" ✓ supervisor: all capabilities + can grant/revoke\n"); // ======================================================================== // 2. Create enforcement layer // ======================================================================== - println!("2. Creating enforcement layer with audit logging...\n"); + log::info!("2. Creating enforcement layer with audit logging...\n"); let enforcement = EnforcementLayer::new(policy_engine); // ======================================================================== // 3. Test Entity A: Attestation Service // ======================================================================== - println!("3. Testing attestation-service (limited to platform):\n"); + log::info!("3. Testing attestation-service (limited to platform):\n"); let attestation_hal = enforcement.create_restricted_hal(&attestation_service_id)?; // This should work - has platform capability if let Some(platform) = &attestation_hal.platform { match platform.platform_info() { Ok((ptype, version, _)) => { - println!(" ✓ Platform info: {} v{}", ptype, version); + log::info!(" ✓ Platform info: {} v{}", ptype, version); } - Err(e) => println!(" ⚠ Platform info error (expected on non-TEE): {}", e), + Err(e) => log::warn!(" ⚠ Platform info error (expected on non-TEE): {}", e), } } // This should be None - no crypto capability if attestation_hal.crypto.is_none() { - println!(" ✓ Crypto interface correctly denied"); + log::info!(" ✓ Crypto interface correctly denied"); } if attestation_hal.storage.is_none() { - println!(" ✓ Storage interface correctly denied\n"); + log::info!(" ✓ Storage interface correctly denied\n"); } // ======================================================================== // 4. Test Entity B: Crypto Worker // ======================================================================== - println!("4. Testing crypto-worker (crypto + random + clock):\n"); + log::info!("4. Testing crypto-worker (crypto + random + clock):\n"); let crypto_hal = enforcement.create_restricted_hal(&crypto_worker_id)?; // Test random generation (should work) if let Some(random) = &crypto_hal.random { match random.get_random_bytes(32) { - Ok(bytes) => println!(" ✓ Generated {} random bytes", bytes.len()), - Err(e) => println!(" ✗ Random generation failed: {}", e), + Ok(bytes) => log::info!(" ✓ Generated {} random bytes", bytes.len()), + Err(e) => log::warn!(" ✗ Random generation failed: {}", e), } } @@ -124,49 +128,49 @@ fn main() -> Result<(), Box> { if let Some(crypto) = &crypto_hal.crypto { let data = b"Hello, TEE!"; match crypto.hash(data, "SHA-256") { - Ok(hash) => println!(" ✓ SHA-256 hash: {} bytes", hash.len()), - Err(e) => println!(" ✗ Hash failed: {}", e), + Ok(hash) => log::info!(" ✓ SHA-256 hash: {} bytes", hash.len()), + Err(e) => log::warn!(" ✗ Hash failed: {}", e), } } // Test clock (should work) if let Some(clock) = &crypto_hal.clock { match clock.system_time() { - Ok((secs, nanos)) => println!(" ✓ System time: {}.{:09}s", secs, nanos), - Err(e) => println!(" ✗ Clock failed: {}", e), + Ok((secs, nanos)) => log::info!(" ✓ System time: {}.{:09}s", secs, nanos), + Err(e) => log::warn!(" ✗ Clock failed: {}", e), } } // Platform should be denied if crypto_hal.platform.is_none() { - println!(" ✓ Platform interface correctly denied\n"); + log::info!(" ✓ Platform interface correctly denied\n"); } // ======================================================================== // 5. Test Entity C: Untrusted Service // ======================================================================== - println!("5. Testing untrusted-service (random only):\n"); + log::info!("5. Testing untrusted-service (random only):\n"); let untrusted_hal = enforcement.create_restricted_hal(&untrusted_id)?; // Only random should work if let Some(random) = &untrusted_hal.random { match random.get_random_bytes(16) { - Ok(bytes) => println!(" ✓ Generated {} random bytes", bytes.len()), - Err(e) => println!(" ✗ Random generation failed: {}", e), + Ok(bytes) => log::info!(" ✓ Generated {} random bytes", bytes.len()), + Err(e) => log::warn!(" ✗ Random generation failed: {}", e), } } // Everything else denied if untrusted_hal.platform.is_none() && untrusted_hal.crypto.is_none() { - println!(" ✓ Platform and crypto correctly denied\n"); + log::info!(" ✓ Platform and crypto correctly denied\n"); } // ======================================================================== // 6. Test Rate Limiting // ======================================================================== - println!("6. Testing rate limiting on crypto-worker:\n"); + log::info!("6. Testing rate limiting on crypto-worker:\n"); if let Some(crypto) = &crypto_hal.crypto { let mut successes = 0; let mut rate_limited = 0; @@ -180,12 +184,12 @@ fn main() -> Result<(), Box> { } } - println!(" - Attempted 3000 operations"); - println!(" - Successful: {}", successes); - println!(" - Rate limited: {}", rate_limited); + log::debug!(" - Attempted 3000 operations"); + log::debug!(" - Successful: {}", successes); + log::debug!(" - Rate limited: {}", rate_limited); if rate_limited > 0 { - println!(" ✓ Rate limiting is working!\n"); + log::info!(" ✓ Rate limiting is working!\n"); } } @@ -193,45 +197,45 @@ fn main() -> Result<(), Box> { // 7. Audit Log Review // ======================================================================== - println!("7. Reviewing audit log:\n"); + log::info!("7. Reviewing audit log:\n"); let audit_log = enforcement.audit_log(); let total_events = audit_log.count(); - println!(" Total events logged: {}", total_events); + log::info!(" Total events logged: {}", total_events); // Events by entity - println!("\n Events by entity:"); + log::info!("\n Events by entity:"); for entity_id in &[&attestation_service_id, &crypto_worker_id, &untrusted_id] { let count = audit_log.get_entity_events(entity_id).len(); - println!(" - {}: {} events", entity_id, count); + log::debug!(" - {}: {} events", entity_id, count); } // Events by capability - println!("\n Events by capability:"); + log::info!("\n Events by capability:"); for cap in &["platform", "crypto", "random"] { let count = audit_log.get_capability_events(cap).len(); if count > 0 { - println!(" - {}: {} events", cap, count); + log::debug!(" - {}: {} events", cap, count); } } // Failed operations let failed = audit_log.get_failed_events(); - println!("\n Failed operations: {}", failed.len()); + log::info!("\n Failed operations: {}", failed.len()); if !failed.is_empty() { for event in failed.iter().take(3) { - println!(" - {} by {} failed", event.operation, event.entity_id); + log::debug!(" - {} by {} failed", event.operation, event.entity_id); } } - println!("\n=== Enforcement Layer Demo Complete ===\n"); + log::info!("\n=== Enforcement Layer Demo Complete ===\n"); - println!("Key Takeaways:"); - println!(" ✓ Fine-grained capability control per entity"); - println!(" ✓ Rate limiting prevents resource exhaustion"); - println!(" ✓ Quota enforcement tracks usage"); - println!(" ✓ Complete audit trail of all operations"); - println!(" ✓ Umbrella entity can manage permissions dynamically"); + log::info!("Key Takeaways:"); + log::info!(" ✓ Fine-grained capability control per entity"); + log::info!(" ✓ Rate limiting prevents resource exhaustion"); + log::info!(" ✓ Quota enforcement tracks usage"); + log::info!(" ✓ Complete audit trail of all operations"); + log::info!(" ✓ Umbrella entity can manage permissions dynamically"); Ok(()) } diff --git a/examples/modular_interfaces.rs b/examples/modular_interfaces.rs index 35ebc5f..ef24df0 100644 --- a/examples/modular_interfaces.rs +++ b/examples/modular_interfaces.rs @@ -5,88 +5,90 @@ use elastic_tee_hal::interfaces::*; use elastic_tee_hal::providers::*; fn main() -> Result<(), Box> { - println!("=== ELASTIC TEE HAL - Modular Interface Demo ===\n"); + env_logger::Builder::from_default_env() + .filter_level(log::LevelFilter::Info) + .init(); + + log::info!("=== ELASTIC TEE HAL - Modular Interface Demo ===\n"); // Option 1: Use default implementations - println!("1. Using default provider:"); + log::info!("1. Using default provider:"); let provider = HalProvider::with_defaults(); if let Some(platform) = &provider.platform { let (platform_type, version, attestation_support) = platform.platform_info()?; - println!(" Platform: {}", platform_type); - println!(" Version: {}", version); - println!(" Attestation: {}", attestation_support); + log::debug!(" Platform: {}", platform_type); + log::debug!(" Version: {}", version); + log::debug!(" Attestation: {}", attestation_support); } - println!(); + log::info!(""); // Option 2: Use individual interfaces - println!("2. Using individual interfaces:"); + log::info!("2. Using individual interfaces:"); // Random interface - let random = DefaultRandomProvider::new(); + let random = DefaultRandomProvider::default(); let random_bytes = random.get_random_bytes(32)?; - println!(" Generated {} random bytes", random_bytes.len()); + log::debug!(" Generated {} random bytes", random_bytes.len()); // Crypto interface - let crypto = DefaultCryptoProvider::new(); + let crypto = DefaultCryptoProvider::default(); let test_data = b"Hello, TEE!"; let hash = crypto.hash(test_data, "SHA-256")?; - println!(" SHA-256 hash: {} bytes", hash.len()); + log::debug!(" SHA-256 hash: {} bytes", hash.len()); // Capabilities interface - let caps = DefaultCapabilitiesProvider::new(); + let caps = DefaultCapabilitiesProvider::default(); let has_rdrand = caps.has_capability("rdrand")?; - println!(" RDRAND available: {}", has_rdrand); + log::debug!(" RDRAND available: {}", has_rdrand); // Clock interface - let clock = DefaultClockProvider::new(); + let clock = DefaultClockProvider::default(); let (seconds, nanos) = clock.system_time()?; - println!(" System time: {}.{:09} seconds", seconds, nanos); - println!(); + log::debug!(" System time: {}.{:09} seconds", seconds, nanos); // Option 3: Custom composition - println!("3. Custom composition:"); + log::info!("3. Custom composition:"); let mut custom_provider = HalProvider::new(); if let Ok(platform) = DefaultPlatformProvider::new() { custom_provider.platform = Some(Box::new(platform)); } - custom_provider.crypto = Some(Box::new(DefaultCryptoProvider::new())); - custom_provider.random = Some(Box::new(DefaultRandomProvider::new())); + custom_provider.crypto = Some(Box::new(DefaultCryptoProvider::default())); + custom_provider.random = Some(Box::new(DefaultRandomProvider::default())); - println!(" ✓ Custom provider with interfaces"); - println!(); + log::info!(" ✓ Custom provider with interfaces"); + log::info!(""); // Option 4: Test attestation - println!("4. Platform attestation:"); + log::info!("4. Platform attestation:"); if let Some(platform) = &provider.platform { let nonce = b"test_nonce_for_attestation_demo_"; match platform.attestation(nonce) { Ok(attestation) => { - println!(" ✓ Attestation generated: {} bytes", attestation.len()); + log::info!(" ✓ Attestation generated: {} bytes", attestation.len()); } Err(e) => { - println!(" ⚠ Attestation error: {}", e); + log::warn!(" ⚠ Attestation error: {}", e); } } } - println!(); // Option 5: Crypto operations - println!("5. Cryptographic operations:"); + log::info!("5. Cryptographic operations:"); let keypair = crypto.generate_keypair()?; - println!(" ✓ Keypair generated:"); - println!(" Public key: {} bytes", keypair.0.len()); - println!(" Private key: {} bytes", keypair.1.len()); + log::info!(" ✓ Keypair generated:"); + log::debug!(" Public key: {} bytes", keypair.0.len()); + log::debug!(" Private key: {} bytes", keypair.1.len()); let message = b"Sign this message"; let signature = crypto.sign(message, &keypair.1)?; - println!(" ✓ Signature: {} bytes", signature.len()); + log::info!(" ✓ Signature: {} bytes", signature.len()); let valid = crypto.verify(message, &signature, &keypair.0)?; - println!(" ✓ Signature valid: {}", valid); - println!(); + log::info!(" ✓ Signature valid: {}", valid); + log::info!(""); - println!("=== All operations completed successfully ==="); + log::info!("=== All operations completed successfully ==="); Ok(()) } diff --git a/examples/rp_attestation_flow.rs b/examples/rp_attestation_flow.rs index dceb9cb..8620377 100644 --- a/examples/rp_attestation_flow.rs +++ b/examples/rp_attestation_flow.rs @@ -54,23 +54,23 @@ async fn main() -> Result<(), Box> { let rp_base = std::env::var("RP_URL").unwrap_or_else(|_| "http://127.0.0.1:8087".to_string()); let output_path = std::env::var("OUTPUT").unwrap_or_else(|_| "./decrypted.wasm".to_string()); - println!("=== Attester → Relying Party demo ==="); - println!("Relying party : {}", rp_base); - println!("Output WASM : {}", output_path); + log::info!("=== Attester → Relying Party demo ==="); + log::info!("Relying party : {}", rp_base); + log::info!("Output WASM : {}", output_path); // 1. Initialise HAL. let hal = ElasticTeeHal::new()?; - println!("✓ HAL initialised on {:?}", hal.platform_type()); + log::info!("✓ HAL initialised on {:?}", hal.platform_type()); // 2. Generate nonce. let random = RandomInterface::new(); let nonce = random.generate_nonce(32)?; - println!("✓ 32-byte nonce: {}", hex::encode(&nonce)); + log::info!("✓ 32-byte nonce: {}", hex::encode(&nonce)); // 3. ITA round-trip → EAR JWT. - println!("→ Submitting TDX quote to Intel Trust Authority…"); + log::info!("→ Submitting TDX quote to Intel Trust Authority…"); let ear_jwt = hal.attest_with_ita(&nonce).await?; - println!("✓ EAR JWT received ({} bytes)", ear_jwt.len()); + log::info!("✓ EAR JWT received ({} bytes)", ear_jwt.len()); // 4. POST EAR to relying party. let http = reqwest::Client::builder() @@ -78,7 +78,7 @@ async fn main() -> Result<(), Box> { .build()?; let attest_url = format!("{}/attest", rp_base.trim_end_matches('/')); - println!("→ POST {}", attest_url); + log::info!("→ POST {}", attest_url); let resp = http .post(&attest_url) @@ -109,11 +109,11 @@ async fn main() -> Result<(), Box> { if key_bytes.len() != 32 { return Err(format!("key length is {} bytes; expected 32", key_bytes.len()).into()); } - println!("✓ Attestation accepted, AES-256 key released"); + log::info!("✓ Attestation accepted, AES-256 key released"); // 5. Fetch encrypted WASM. let wasm_url = format!("{}{}", rp_base.trim_end_matches('/'), wasm_url_path); - println!("→ GET {}", wasm_url); + log::info!("→ GET {}", wasm_url); let enc = http .get(&wasm_url) .send() @@ -121,7 +121,7 @@ async fn main() -> Result<(), Box> { .error_for_status()? .bytes() .await?; - println!("✓ Encrypted WASM downloaded ({} bytes)", enc.len()); + log::info!("✓ Encrypted WASM downloaded ({} bytes)", enc.len()); // 6. AES-256-GCM-decrypt. Layout written by the relying party: // enc = nonce(12) || ciphertext_with_auth_tag @@ -135,7 +135,7 @@ async fn main() -> Result<(), Box> { .map_err(|e| format!("AES-GCM decrypt failed: {}", e))?; std::fs::write(&output_path, &plaintext)?; - println!( + log::info!( "✓ Decrypted WASM written to {} ({} bytes)", output_path, plaintext.len() @@ -146,14 +146,14 @@ async fn main() -> Result<(), Box> { // from `_start`. We run it here so the demo closes the loop: // attest → release key → decrypt → execute. if std::env::var("SKIP_RUN").ok().as_deref() != Some("1") { - println!("\n→ Executing decrypted WASM via wasmtime…"); + log::info!("\n→ Executing decrypted WASM via wasmtime…"); run_wasi_module(&plaintext).await?; - println!("✓ WASM execution finished"); + log::info!("✓ WASM execution finished"); } else { - println!("(SKIP_RUN=1 set — not executing the decrypted module)"); + log::info!("(SKIP_RUN=1 set — not executing the decrypted module)"); } - println!("=== DONE ==="); + log::info!("=== DONE ==="); Ok(()) } @@ -181,7 +181,7 @@ async fn run_wasi_module(wasm_bytes: &[u8]) -> Result<(), Box> { let instance = linker.instantiate_async(&mut store, &module).await?; - println!("--- BEGIN WASM stdout ---"); + log::info!("--- BEGIN WASM stdout ---"); if let Ok(start) = instance.get_typed_func::<(), ()>(&mut store, "_start") { start.call_async(&mut store, ()).await?; } else if let Ok(main) = instance.get_typed_func::<(), ()>(&mut store, "main") { @@ -189,6 +189,6 @@ async fn run_wasi_module(wasm_bytes: &[u8]) -> Result<(), Box> { } else { return Err("WASM has no `_start` or `main` export".into()); } - println!("--- END WASM stdout ---"); + log::info!("--- END WASM stdout ---"); Ok(()) } diff --git a/examples/wasmtime_linker.rs b/examples/wasmtime_linker.rs index bbd5bf3..6f868ac 100644 --- a/examples/wasmtime_linker.rs +++ b/examples/wasmtime_linker.rs @@ -6,6 +6,10 @@ use wasmtime::component::*; use wasmtime::{Config, Engine, Store}; fn main() -> anyhow::Result<()> { + env_logger::Builder::from_default_env() + .filter_level(log::LevelFilter::Info) + .init(); + // Initialize Wasmtime with component model support let mut config = Config::new(); config.wasm_component_model(true); @@ -14,47 +18,47 @@ fn main() -> anyhow::Result<()> { // Create a linker let mut linker = Linker::new(&engine); - println!("Adding ELASTIC TEE HAL interfaces to Wasmtime linker...\n"); + log::info!("Adding ELASTIC TEE HAL interfaces to Wasmtime linker...\n"); // Option 1: Add all interfaces (full HAL) - println!("Option 1: Full HAL"); + log::info!("Option 1: Full HAL"); wasmtime_bindings::add_to_linker(&mut linker)?; - println!("✓ All 11 interfaces added\n"); + log::info!("✓ All 11 interfaces added\n"); // Option 2: Add minimal interfaces only - println!("Option 2: Minimal HAL (platform, capabilities, crypto, random)"); + log::info!("Option 2: Minimal HAL (platform, capabilities, crypto, random)"); let mut linker2 = Linker::new(&engine); wasmtime_bindings::add_minimal_to_linker(&mut linker2)?; - println!("✓ 4 core interfaces added\n"); + log::info!("✓ 4 core interfaces added\n"); // Option 3: Add attestation-focused interfaces - println!("Option 3: Attestation HAL (platform, crypto, random)"); + log::info!("Option 3: Attestation HAL (platform, crypto, random)"); let mut linker3 = Linker::new(&engine); wasmtime_bindings::add_attestation_to_linker(&mut linker3)?; - println!("✓ 3 attestation interfaces added\n"); + log::info!("✓ 3 attestation interfaces added\n"); // Option 4: Add individual interfaces as needed - println!("Option 4: Custom composition (platform + crypto)"); + log::info!("Option 4: Custom composition (platform + crypto)"); let mut linker4 = Linker::new(&engine); wasmtime_bindings::platform::add_to_linker(&mut linker4)?; wasmtime_bindings::crypto::add_to_linker(&mut linker4)?; - println!("✓ 2 custom interfaces added\n"); + log::info!("✓ 2 custom interfaces added\n"); // Option 5: Storage-focused - println!("Option 5: Storage HAL"); + log::info!("Option 5: Storage HAL"); let mut linker5 = Linker::new(&engine); wasmtime_bindings::add_storage_to_linker(&mut linker5)?; - println!("✓ Storage interfaces added\n"); + log::info!("✓ Storage interfaces added\n"); // Option 6: Network-focused - println!("Option 6: Network HAL"); + log::info!("Option 6: Network HAL"); let mut linker6 = Linker::new(&engine); wasmtime_bindings::add_network_to_linker(&mut linker6)?; - println!("✓ Network interfaces added\n"); + log::info!("✓ Network interfaces added\n"); - println!("All linker configurations successful!"); - println!("\nThe linkers are now ready to instantiate WASM components"); - println!("that use the corresponding ELASTIC TEE HAL interfaces."); + log::info!("All linker configurations successful!"); + log::info!("\nThe linkers are now ready to instantiate WASM components"); + log::info!("that use the corresponding ELASTIC TEE HAL interfaces."); Ok(()) } diff --git a/hal-runtime/src/host_impl.rs b/hal-runtime/src/host_impl.rs index 87451f3..a3cadcc 100644 --- a/hal-runtime/src/host_impl.rs +++ b/hal-runtime/src/host_impl.rs @@ -6,18 +6,18 @@ use anyhow::Result; use elastic_tee_hal::{ - ElasticTeeHal, PlatformCapabilities, - crypto::CryptoInterface as HalCrypto, - storage::StorageInterface as HalStorage, clock::ClockInterface as HalClock, - random::RandomInterface as HalRandom, - sockets::SocketInterface as HalSockets, + communication::CommunicationInterface as HalComm, + communication::{BufferConfig, MessagePriority as HalMsgPriority, MessageType as HalMsgType}, + crypto::CryptoInterface as HalCrypto, + events::EventInterface as HalEvents, + events::{EventData, EventHandlerConfig, SubscriptionFilter}, gpu::GpuInterface as HalGpu, + random::RandomInterface as HalRandom, resources::ResourceInterface as HalResources, - events::EventInterface as HalEvents, - communication::CommunicationInterface as HalComm, - communication::{BufferConfig, MessageType as HalMsgType, MessagePriority as HalMsgPriority}, - events::{EventHandlerConfig, SubscriptionFilter, EventData}, + sockets::SocketInterface as HalSockets, + storage::StorageInterface as HalStorage, + ElasticTeeHal, PlatformCapabilities, }; use std::sync::atomic::{AtomicU64, Ordering}; @@ -50,9 +50,8 @@ impl HalHost { let platform = ElasticTeeHal::new()?; let capabilities = futures::executor::block_on(platform.capabilities()); - let storage = futures::executor::block_on(async { - HalStorage::new("/tmp/hal-storage").await.ok() - }); + let storage = + futures::executor::block_on(async { HalStorage::new("/tmp/hal-storage").await.ok() }); let resources = HalResources::new().ok(); @@ -81,8 +80,7 @@ impl HalHost { // ======================================================================== pub fn attestation(&mut self, report_data: Vec) -> Result, String> { - futures::executor::block_on(self.platform.attest(&report_data)) - .map_err(|e| e.to_string()) + futures::executor::block_on(self.platform.attest(&report_data)).map_err(|e| e.to_string()) } pub fn platform_info(&self) -> PlatformInfo { @@ -99,17 +97,61 @@ impl HalHost { pub fn capabilities_list(&self) -> Vec { vec![ - CapabilityInfo { feature_name: "clock".into(), supported: self.capabilities.features.clock, version: "1.0".into() }, - CapabilityInfo { feature_name: "random".into(), supported: self.capabilities.features.random, version: "1.0".into() }, - CapabilityInfo { feature_name: "storage".into(), supported: self.capabilities.features.storage, version: "1.0".into() }, - CapabilityInfo { feature_name: "secure-storage".into(), supported: self.capabilities.features.secure_storage, version: "1.0".into() }, - CapabilityInfo { feature_name: "tcp-sockets".into(), supported: self.capabilities.features.tcp_sockets, version: "1.0".into() }, - CapabilityInfo { feature_name: "udp-sockets".into(), supported: self.capabilities.features.udp_sockets, version: "1.0".into() }, - CapabilityInfo { feature_name: "tls".into(), supported: self.capabilities.features.tls_support, version: "1.0".into() }, - CapabilityInfo { feature_name: "gpu-compute".into(), supported: self.capabilities.features.gpu_compute, version: "1.0".into() }, - CapabilityInfo { feature_name: "attestation".into(), supported: self.capabilities.features.attestation, version: "1.0".into() }, - CapabilityInfo { feature_name: "events".into(), supported: self.capabilities.features.event_handling, version: "1.0".into() }, - CapabilityInfo { feature_name: "communication".into(), supported: self.capabilities.features.internal_communication, version: "1.0".into() }, + CapabilityInfo { + feature_name: "clock".into(), + supported: self.capabilities.features.clock, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "random".into(), + supported: self.capabilities.features.random, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "storage".into(), + supported: self.capabilities.features.storage, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "secure-storage".into(), + supported: self.capabilities.features.secure_storage, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "tcp-sockets".into(), + supported: self.capabilities.features.tcp_sockets, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "udp-sockets".into(), + supported: self.capabilities.features.udp_sockets, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "tls".into(), + supported: self.capabilities.features.tls_support, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "gpu-compute".into(), + supported: self.capabilities.features.gpu_compute, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "attestation".into(), + supported: self.capabilities.features.attestation, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "events".into(), + supported: self.capabilities.features.event_handling, + version: "1.0".into(), + }, + CapabilityInfo { + feature_name: "communication".into(), + supported: self.capabilities.features.internal_communication, + version: "1.0".into(), + }, ] } @@ -128,12 +170,14 @@ impl HalHost { HashAlgorithm::Sha512 => "SHA-512", HashAlgorithm::Blake3 => "SHA-384", // map to available impl }; - futures::executor::block_on(self.crypto.hash_data(algo, data)) - .map_err(|e| e.to_string()) + futures::executor::block_on(self.crypto.hash_data(algo, data)).map_err(|e| e.to_string()) } pub fn crypto_encrypt( - &self, data: &[u8], key: &[u8], algorithm: CipherAlgorithm, + &self, + data: &[u8], + key: &[u8], + algorithm: CipherAlgorithm, ) -> Result, String> { let algo = match algorithm { CipherAlgorithm::Aes256Gcm => "AES-256-GCM", @@ -144,7 +188,10 @@ impl HalHost { } pub fn crypto_decrypt( - &self, data: &[u8], key: &[u8], algorithm: CipherAlgorithm, + &self, + data: &[u8], + key: &[u8], + algorithm: CipherAlgorithm, ) -> Result, String> { let algo = match algorithm { CipherAlgorithm::Aes256Gcm => "AES-256-GCM", @@ -156,11 +203,14 @@ impl HalHost { pub fn crypto_generate_keypair(&self) -> Result { // Generate a 32-byte seed for Ed25519 - let seed = self.random.generate_key_material(32).map_err(|e| e.to_string())?; + let seed = self + .random + .generate_key_material(32) + .map_err(|e| e.to_string())?; // Load a signing context to extract the public key - let ctx = futures::executor::block_on( - self.crypto.load_key_context("Ed25519", &seed, "signing"), - ).map_err(|e| e.to_string())?; + let ctx = + futures::executor::block_on(self.crypto.load_key_context("Ed25519", &seed, "signing")) + .map_err(|e| e.to_string())?; // Sign empty data to confirm context works; public key is derived from seed // For Ed25519, public key is the last 32 bytes of the 64-byte expanded key // We return the seed as private_key so the caller can reconstruct @@ -173,20 +223,28 @@ impl HalHost { } pub fn crypto_sign(&self, data: &[u8], private_key: &[u8]) -> Result, String> { - let ctx = futures::executor::block_on( - self.crypto.load_key_context("Ed25519", private_key, "signing"), - ).map_err(|e| e.to_string())?; + let ctx = futures::executor::block_on(self.crypto.load_key_context( + "Ed25519", + private_key, + "signing", + )) + .map_err(|e| e.to_string())?; let sig = futures::executor::block_on(self.crypto.sign_data(ctx, data)) .map_err(|e| e.to_string())?; Ok(sig.signature) } pub fn crypto_verify( - &self, data: &[u8], signature: &[u8], public_key: &[u8], + &self, + data: &[u8], + signature: &[u8], + public_key: &[u8], ) -> Result { futures::executor::block_on( - self.crypto.verify_signature("Ed25519", public_key, data, signature), - ).map_err(|e| e.to_string()) + self.crypto + .verify_signature("Ed25519", public_key, data, signature), + ) + .map_err(|e| e.to_string()) } pub fn crypto_create_context(&self) -> Result { @@ -204,7 +262,9 @@ impl HalHost { // ======================================================================== fn storage(&self) -> Result<&HalStorage, String> { - self.storage.as_ref().ok_or_else(|| "Storage not initialized".to_string()) + self.storage + .as_ref() + .ok_or_else(|| "Storage not initialized".to_string()) } pub fn storage_create_container(&self, name: &str) -> Result { @@ -223,16 +283,17 @@ impl HalHost { } pub fn storage_store_object( - &self, container: u64, key: &str, data: &[u8], + &self, + container: u64, + key: &str, + data: &[u8], ) -> Result { futures::executor::block_on(self.storage()?.write_object(container, key, data)) .map_err(|e| e.to_string())?; Ok(self.next_id()) // return object handle } - pub fn storage_retrieve_object( - &self, container: u64, key: &str, - ) -> Result, String> { + pub fn storage_retrieve_object(&self, container: u64, key: &str) -> Result, String> { futures::executor::block_on(self.storage()?.read_object(container, key)) .map_err(|e| e.to_string()) } @@ -248,7 +309,9 @@ impl HalHost { } pub fn storage_get_metadata( - &self, container: u64, key: &str, + &self, + container: u64, + key: &str, ) -> Result { // Read object to get size; metadata file is internal detail let data = self.storage_retrieve_object(container, key)?; @@ -280,7 +343,9 @@ impl HalHost { let bind_addr = format!("{}:{}", addr.ip, addr.port); // For TCP, create listener; for UDP, bind socket futures::executor::block_on(async { - self.sockets.create_tcp_socket(&bind_addr).await + self.sockets + .create_tcp_socket(&bind_addr) + .await .map_err(|e| e.to_string())?; Ok::<(), String>(()) }) @@ -298,8 +363,7 @@ impl HalHost { } pub fn sockets_accept(&self, listener: u64) -> Result { - futures::executor::block_on(self.sockets.tcp_accept(listener)) - .map_err(|e| e.to_string()) + futures::executor::block_on(self.sockets.tcp_accept(listener)).map_err(|e| e.to_string()) } pub fn sockets_send(&self, socket: u64, data: &[u8]) -> Result { @@ -317,8 +381,7 @@ impl HalHost { } pub fn sockets_close(&self, socket: u64) -> Result<(), String> { - futures::executor::block_on(self.sockets.close_socket(socket)) - .map_err(|e| e.to_string()) + futures::executor::block_on(self.sockets.close_socket(socket)).map_err(|e| e.to_string()) } // ======================================================================== @@ -328,8 +391,7 @@ impl HalHost { // ======================================================================== pub fn gpu_list_adapters(&self) -> Result, String> { - futures::executor::block_on(self.gpu.get_gpu_adapters()) - .map_err(|e| e.to_string()) + futures::executor::block_on(self.gpu.get_gpu_adapters()).map_err(|e| e.to_string()) } pub fn gpu_get_adapter_info(&self, handle: u64) -> Result { @@ -343,21 +405,25 @@ impl HalHost { } pub fn gpu_create_device(&self, adapter: u64) -> Result { - futures::executor::block_on(self.gpu.create_gpu_device(adapter)) - .map_err(|e| e.to_string()) + futures::executor::block_on(self.gpu.create_gpu_device(adapter)).map_err(|e| e.to_string()) } pub fn gpu_create_buffer( - &self, device: u64, descriptor: &BufferDescriptor, + &self, + device: u64, + descriptor: &BufferDescriptor, ) -> Result { let usage = elastic_tee_hal::gpu::GpuBufferUsage { storage: matches!(descriptor.usage, BufferUsage::Storage), uniform: matches!(descriptor.usage, BufferUsage::Uniform), vertex: matches!(descriptor.usage, BufferUsage::Vertex), index: matches!(descriptor.usage, BufferUsage::Index), - map_read: false, map_write: false, - copy_src: true, copy_dst: true, - indirect: false, query_resolve: false, + map_read: false, + map_write: false, + copy_src: true, + copy_dst: true, + indirect: false, + query_resolve: false, }; let desc = elastic_tee_hal::gpu::GpuBufferDescriptor { label: None, @@ -369,34 +435,33 @@ impl HalHost { .map_err(|e| e.to_string()) } - pub fn gpu_write_buffer( - &self, buffer: u64, offset: u64, data: &[u8], - ) -> Result<(), String> { + pub fn gpu_write_buffer(&self, buffer: u64, offset: u64, data: &[u8]) -> Result<(), String> { futures::executor::block_on(self.gpu.write_gpu_buffer(buffer, offset, data)) .map_err(|e| e.to_string()) } - pub fn gpu_read_buffer( - &self, buffer: u64, offset: u64, size: u64, - ) -> Result, String> { + pub fn gpu_read_buffer(&self, buffer: u64, offset: u64, size: u64) -> Result, String> { futures::executor::block_on(self.gpu.read_gpu_buffer(buffer, offset, size)) .map_err(|e| e.to_string()) } pub fn gpu_create_compute_pipeline( - &self, device: u64, shader_code: &[u8], + &self, + device: u64, + shader_code: &[u8], ) -> Result { - futures::executor::block_on( - self.gpu.create_gpu_compute_pipeline(device, shader_code, "main", [64, 1, 1]), - ).map_err(|e| e.to_string()) + futures::executor::block_on(self.gpu.create_gpu_compute_pipeline( + device, + shader_code, + "main", + [64, 1, 1], + )) + .map_err(|e| e.to_string()) } - pub fn gpu_dispatch( - &self, pipeline: u64, x: u32, y: u32, z: u32, - ) -> Result<(), String> { - futures::executor::block_on( - self.gpu.dispatch_compute(pipeline, x, y, z), - ).map_err(|e| e.to_string()) + pub fn gpu_dispatch(&self, pipeline: u64, x: u32, y: u32, z: u32) -> Result<(), String> { + futures::executor::block_on(self.gpu.dispatch_compute(pipeline, x, y, z)) + .map_err(|e| e.to_string()) } // ======================================================================== @@ -404,11 +469,14 @@ impl HalHost { // ======================================================================== fn resources(&self) -> Result<&HalResources, String> { - self.resources.as_ref().ok_or_else(|| "Resources not initialized".to_string()) + self.resources + .as_ref() + .ok_or_else(|| "Resources not initialized".to_string()) } pub fn resources_allocate( - &self, request: &AllocationRequest, + &self, + request: &AllocationRequest, ) -> Result { let res_type = match request.resource_type { ResourceType::Memory => elastic_tee_hal::resources::ResourceType::Memory, @@ -428,9 +496,8 @@ impl HalHost { }, timeout_seconds: None, }; - let result = futures::executor::block_on( - self.resources()?.allocate_resource(hal_request), - ).map_err(|e| e.to_string())?; + let result = futures::executor::block_on(self.resources()?.allocate_resource(hal_request)) + .map_err(|e| e.to_string())?; Ok(AllocationResponse { allocation_id: result.allocation_id, granted_amount: result.granted_amount, @@ -449,9 +516,13 @@ impl HalHost { .map_err(|e| e.to_string())?; Ok(match resource_type { ResourceType::Memory => limits.max_memory_mb.saturating_sub(usage.memory_mb), - ResourceType::Cpu => (limits.max_cpu_cores as u64).saturating_sub(usage.cpu_cores as u64), + ResourceType::Cpu => { + (limits.max_cpu_cores as u64).saturating_sub(usage.cpu_cores as u64) + } ResourceType::Storage => limits.max_storage_mb.saturating_sub(usage.storage_mb), - ResourceType::Network => limits.max_network_bandwidth_mbps.saturating_sub(usage.network_bandwidth_mbps), + ResourceType::Network => limits + .max_network_bandwidth_mbps + .saturating_sub(usage.network_bandwidth_mbps), }) } @@ -491,9 +562,7 @@ impl HalHost { pub fn events_poll(&self, handle: u64) -> Result, String> { // Try to receive events without blocking - match futures::executor::block_on( - self.events.request_event_from_handler(handle, Some(0)), - ) { + match futures::executor::block_on(self.events.request_event_from_handler(handle, Some(0))) { Ok(event) => Ok(vec![EventDataWit { event_type: match event.event_type.as_str() { "platform" => EventType::Platform, @@ -521,46 +590,59 @@ impl HalHost { // ======================================================================== pub fn communication_send_message( - &self, recipient: &str, data: &[u8], encrypt: bool, + &self, + recipient: &str, + data: &[u8], + encrypt: bool, ) -> Result { // Ensure a buffer exists for this channel let buffer_name = format!("channel_{}", recipient); - let buffer = futures::executor::block_on( - self.communication.setup_communication_buffer(BufferConfig { + let buffer = futures::executor::block_on(self.communication.setup_communication_buffer( + BufferConfig { name: buffer_name, capacity: 65536, is_encrypted: encrypt, read_permissions: vec![recipient.to_string()], write_permissions: vec!["wasm-guest".to_string()], admin_permissions: vec!["admin".to_string()], - }), - ); + }, + )); let buffer_handle = match buffer { Ok(h) => h, Err(_) => { // Buffer may already exist; try to find it - let buffers = futures::executor::block_on( - self.communication.list_communication_buffers(), - ).map_err(|e| e.to_string())?; - buffers.first().ok_or("No communication buffer available")?.handle + let buffers = + futures::executor::block_on(self.communication.list_communication_buffers()) + .map_err(|e| e.to_string())?; + buffers + .first() + .ok_or("No communication buffer available")? + .handle } }; futures::executor::block_on(self.communication.push_data_to_buffer( - buffer_handle, data, "wasm-guest", + buffer_handle, + data, + "wasm-guest", HalMsgType::Data, - if encrypt { HalMsgPriority::High } else { HalMsgPriority::Normal }, - )).map_err(|e| e.to_string())?; + if encrypt { + HalMsgPriority::High + } else { + HalMsgPriority::Normal + }, + )) + .map_err(|e| e.to_string())?; Ok(self.next_id()) } pub fn communication_receive_message(&self) -> Result, String> { - let buffers = futures::executor::block_on( - self.communication.list_communication_buffers(), - ).map_err(|e| e.to_string())?; + let buffers = futures::executor::block_on(self.communication.list_communication_buffers()) + .map_err(|e| e.to_string())?; for buffer_info in buffers { if let Ok(Some(msg)) = futures::executor::block_on( - self.communication.read_data_from_buffer(buffer_info.handle, "wasm-guest"), + self.communication + .read_data_from_buffer(buffer_info.handle, "wasm-guest"), ) { return Ok(Some(Message { sender: msg.sender, @@ -575,10 +657,12 @@ impl HalHost { pub fn communication_list_workloads(&self) -> Result, String> { // Return known workload identifiers from active buffers - let buffers = futures::executor::block_on( - self.communication.list_communication_buffers(), - ).map_err(|e| e.to_string())?; - Ok(buffers.iter().map(|b| format!("workload-{}", b.name)).collect()) + let buffers = futures::executor::block_on(self.communication.list_communication_buffers()) + .map_err(|e| e.to_string())?; + Ok(buffers + .iter() + .map(|b| format!("workload-{}", b.name)) + .collect()) } // ======================================================================== @@ -594,7 +678,10 @@ impl HalHost { } pub fn clock_monotonic_time(&self) -> Result { - let time = self.clock.read_monotonic_time().map_err(|e| e.to_string())?; + let time = self + .clock + .read_monotonic_time() + .map_err(|e| e.to_string())?; Ok(WitMonotonicTime { elapsed_seconds: time.elapsed_seconds, elapsed_nanoseconds: time.elapsed_nanoseconds, @@ -607,8 +694,7 @@ impl HalHost { pub fn clock_sleep(&self, duration_ns: u64) -> Result<(), String> { let duration = std::time::Duration::from_nanos(duration_ns); - futures::executor::block_on(self.clock.sleep(duration)) - .map_err(|e| e.to_string()) + futures::executor::block_on(self.clock.sleep(duration)).map_err(|e| e.to_string()) } // ======================================================================== @@ -617,20 +703,26 @@ impl HalHost { // ======================================================================== pub fn random_get_bytes(&self, length: u32) -> Result, String> { - self.random.generate_random_bytes(length as usize) + self.random + .generate_random_bytes(length as usize) .map_err(|e| e.to_string()) } pub fn random_get_secure(&self, length: u32) -> Result, String> { // Same implementation — all our random is cryptographically secure - self.random.generate_random_bytes(length as usize) + self.random + .generate_random_bytes(length as usize) .map_err(|e| e.to_string()) } pub fn random_get_entropy_info(&self) -> Result { let is_hw = elastic_tee_hal::random::hardware_rng::is_hardware_rng_available(); Ok(EntropyInfo { - source: if is_hw { EntropySource::Hardware } else { EntropySource::Platform }, + source: if is_hw { + EntropySource::Hardware + } else { + EntropySource::Platform + }, quality: if is_hw { 100 } else { 80 }, available_bytes: 1_048_576, // 1 MB available }) @@ -664,10 +756,17 @@ pub struct CapabilityInfo { // -- crypto -- #[derive(Clone, Debug)] -pub enum HashAlgorithm { Sha256, Sha512, Blake3 } +pub enum HashAlgorithm { + Sha256, + Sha512, + Blake3, +} #[derive(Clone, Debug)] -pub enum CipherAlgorithm { Aes256Gcm, ChaCha20Poly1305 } +pub enum CipherAlgorithm { + Aes256Gcm, + ChaCha20Poly1305, +} #[derive(Clone, Debug)] pub struct KeyPair { @@ -685,7 +784,12 @@ pub struct ObjectMetadata { // -- sockets -- #[derive(Clone, Debug)] -pub enum Protocol { Tcp, Udp, Tls, Dtls } +pub enum Protocol { + Tcp, + Udp, + Tls, + Dtls, +} #[derive(Clone, Debug)] pub struct Address { @@ -695,7 +799,12 @@ pub struct Address { // -- gpu -- #[derive(Clone, Debug)] -pub enum BufferUsage { Storage, Uniform, Vertex, Index } +pub enum BufferUsage { + Storage, + Uniform, + Vertex, + Index, +} #[derive(Clone, Debug)] pub struct AdapterInfo { @@ -712,7 +821,12 @@ pub struct BufferDescriptor { // -- resources -- #[derive(Clone, Debug)] -pub enum ResourceType { Memory, Cpu, Storage, Network } +pub enum ResourceType { + Memory, + Cpu, + Storage, + Network, +} #[derive(Clone, Debug)] pub struct AllocationRequest { @@ -729,7 +843,13 @@ pub struct AllocationResponse { // -- events -- #[derive(Clone, Debug)] -pub enum EventType { Platform, Crypto, Storage, Network, Gpu } +pub enum EventType { + Platform, + Crypto, + Storage, + Network, + Gpu, +} #[derive(Clone, Debug)] pub struct EventDataWit { @@ -762,7 +882,11 @@ pub struct WitMonotonicTime { // -- random -- #[derive(Clone, Debug)] -pub enum EntropySource { Hardware, Platform, Userspace } +pub enum EntropySource { + Hardware, + Platform, + Userspace, +} #[derive(Clone, Debug)] pub struct EntropyInfo { diff --git a/hal-runtime/src/lib.rs b/hal-runtime/src/lib.rs index 41e593e..dbd818a 100644 --- a/hal-runtime/src/lib.rs +++ b/hal-runtime/src/lib.rs @@ -93,10 +93,7 @@ impl HalRuntime { let mut store = self.create_store()?; let instance = HalConsumer::instantiate_async(&mut store, &component, &linker).await?; - let report_data = instance - .elastic_hal_run() - .call_run(&mut store) - .await?; + let report_data = instance.elastic_hal_run().call_run(&mut store).await?; Ok(report_data) } diff --git a/hal-runtime/src/wit_impl.rs b/hal-runtime/src/wit_impl.rs index df337a6..3a846f6 100644 --- a/hal-runtime/src/wit_impl.rs +++ b/hal-runtime/src/wit_impl.rs @@ -128,10 +128,7 @@ impl crypto::Host for RuntimeState { self.hal.crypto_create_context() } - async fn destroy_context( - &mut self, - handle: crypto::CryptoContextHandle, - ) -> Result<(), String> { + async fn destroy_context(&mut self, handle: crypto::CryptoContextHandle) -> Result<(), String> { self.hal.crypto_destroy_context(handle) } } @@ -141,17 +138,11 @@ impl crypto::Host for RuntimeState { // ============================================================================ #[async_trait] impl storage::Host for RuntimeState { - async fn create_container( - &mut self, - name: String, - ) -> Result { + async fn create_container(&mut self, name: String) -> Result { self.hal.storage_create_container(&name) } - async fn open_container( - &mut self, - name: String, - ) -> Result { + async fn open_container(&mut self, name: String) -> Result { self.hal.storage_open_container(&name) } @@ -235,11 +226,7 @@ impl sockets::Host for RuntimeState { self.hal.sockets_bind(socket, &a) } - async fn listen( - &mut self, - socket: sockets::SocketHandle, - backlog: u32, - ) -> Result<(), String> { + async fn listen(&mut self, socket: sockets::SocketHandle, backlog: u32) -> Result<(), String> { self.hal.sockets_listen(socket, backlog) } @@ -262,11 +249,7 @@ impl sockets::Host for RuntimeState { self.hal.sockets_accept(socket) } - async fn send( - &mut self, - socket: sockets::SocketHandle, - data: Vec, - ) -> Result { + async fn send(&mut self, socket: sockets::SocketHandle, data: Vec) -> Result { self.hal.sockets_send(socket, &data) } @@ -429,10 +412,7 @@ impl events::Host for RuntimeState { self.hal.events_subscribe(et) } - async fn unsubscribe( - &mut self, - handle: events::EventSubscriptionHandle, - ) -> Result<(), String> { + async fn unsubscribe(&mut self, handle: events::EventSubscriptionHandle) -> Result<(), String> { self.hal.events_unsubscribe(handle) } diff --git a/src/crypto.rs b/src/crypto.rs index f52a3d2..f5ce8c3 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -709,59 +709,67 @@ impl Default for CryptoInterface { mod tests { use super::*; + fn init() { + static INIT: std::sync::Once = std::sync::Once::new(); + INIT.call_once(|| { + let _ = env_logger::builder().is_test(true).try_init(); + }); + } + #[tokio::test] async fn test_symmetric_encryption() { - println!("=== CRYPTO DEMO: AES-256-GCM Encryption ==="); + init(); + log::info!("=== CRYPTO DEMO: AES-256-GCM Encryption ==="); // First verify we're running in SEV-SNP environment match crate::ElasticTeeHal::new() { Ok(hal) => { if matches!(hal.platform_type(), crate::platform::PlatformType::AmdSev) { - println!("✓ VERIFIED: Running in AMD SEV-SNP Trusted Execution Environment"); - println!(" - TEE Device: /dev/sev-guest detected"); - println!(" - Hardware-accelerated encryption available"); - println!(" - Keys protected in TEE secure memory"); + log::info!("✓ VERIFIED: Running in AMD SEV-SNP Trusted Execution Environment"); + log::debug!(" - TEE Device: /dev/sev-guest detected"); + log::debug!(" - Hardware-accelerated encryption available"); + log::debug!(" - Keys protected in TEE secure memory"); } else { - println!("✓ TEE Environment detected: {:?}", hal.platform_type()); - println!(" - Hardware-accelerated encryption available"); - println!(" - Keys protected in TEE secure memory"); + log::info!("✓ TEE Environment detected: {:?}", hal.platform_type()); + log::debug!(" - Hardware-accelerated encryption available"); + log::debug!(" - Keys protected in TEE secure memory"); } } Err(_) => { - println!("⚠ Warning: Not running in verified TEE environment"); + log::warn!("⚠ Warning: Not running in verified TEE environment"); } } - println!(); + log::info!(""); let crypto = CryptoInterface::new(); let key = crypto.generate_symmetric_key("AES-256-GCM").await.unwrap(); let plaintext = b"Hello, World!"; - println!("Plaintext: {:?}", std::str::from_utf8(plaintext).unwrap()); - println!("Key length: {} bytes", key.len()); + log::debug!("Plaintext: {:?}", std::str::from_utf8(plaintext).unwrap()); + log::debug!("Key length: {} bytes", key.len()); let ciphertext = crypto .symmetric_encrypt("AES-256-GCM", &key, plaintext, None) .await .unwrap(); - println!("✓ Encrypted with AES-256-GCM in TEE"); - println!(" - Ciphertext length: {} bytes", ciphertext.len()); - println!(" - Ciphertext (hex): {}", hex::encode(&ciphertext)); + log::info!("✓ Encrypted with AES-256-GCM in TEE"); + log::debug!(" - Ciphertext length: {} bytes", ciphertext.len()); + log::debug!(" - Ciphertext (hex): {}", hex::encode(&ciphertext)); let decrypted = crypto .symmetric_decrypt("AES-256-GCM", &key, &ciphertext, None) .await .unwrap(); - println!("✓ Decrypted successfully"); - println!( + log::info!("✓ Decrypted successfully"); + log::debug!( " - Decrypted: {:?}", std::str::from_utf8(&decrypted).unwrap() ); - println!( + log::debug!( " - Plaintext == Decrypted: {}", plaintext == decrypted.as_slice() ); - println!("=== ENCRYPTION DEMO COMPLETE ===\n"); + log::info!("=== ENCRYPTION DEMO COMPLETE ===\n"); assert_eq!(plaintext, decrypted.as_slice()); } @@ -796,52 +804,53 @@ mod tests { #[tokio::test] async fn test_ed25519_signing() { - println!("=== CRYPTO DEMO: Ed25519 Digital Signing ==="); + init(); + log::info!("=== CRYPTO DEMO: Ed25519 Digital Signing ==="); // First verify we're running in SEV-SNP environment match crate::ElasticTeeHal::new() { Ok(hal) => { if matches!(hal.platform_type(), crate::platform::PlatformType::AmdSev) { - println!("✓ VERIFIED: Running in AMD SEV-SNP Trusted Execution Environment"); - println!(" - TEE Device: /dev/sev-guest detected"); - println!(" - Hardware attestation available"); - println!(" - Cryptographic operations are TEE-protected"); + log::info!("✓ VERIFIED: Running in AMD SEV-SNP Trusted Execution Environment"); + log::debug!(" - TEE Device: /dev/sev-guest detected"); + log::debug!(" - Hardware attestation available"); + log::debug!(" - Cryptographic operations are TEE-protected"); } else { - println!("✓ TEE Environment detected: {:?}", hal.platform_type()); - println!(" - Cryptographic operations are TEE-protected"); + log::info!("✓ TEE Environment detected: {:?}", hal.platform_type()); + log::debug!(" - Cryptographic operations are TEE-protected"); } } Err(_) => { - println!("⚠ Warning: Not running in verified TEE environment"); + log::warn!("⚠ Warning: Not running in verified TEE environment"); } } - println!(); + log::info!(""); let crypto = CryptoInterface::new(); let key = crypto.random.generate_key_material(32).unwrap(); let data = b"test data"; - println!("Input data: {:?}", std::str::from_utf8(data).unwrap()); - println!("Key material length: {} bytes", key.len()); + log::debug!("Input data: {:?}", std::str::from_utf8(data).unwrap()); + log::debug!("Key material length: {} bytes", key.len()); let context_handle = crypto .load_key_context("Ed25519", &key, "signing") .await .unwrap(); - println!( + log::info!( "✓ Loaded Ed25519 signing context with handle: {}", context_handle ); let signature_result = crypto.sign_data(context_handle, data).await.unwrap(); - println!("✓ Generated digital signature in TEE"); - println!(" - Algorithm: {}", signature_result.algorithm); - println!( + log::info!("✓ Generated digital signature in TEE"); + log::debug!(" - Algorithm: {}", signature_result.algorithm); + log::debug!( " - Public key: {} bytes", signature_result.public_key.len() ); - println!(" - Signature: {} bytes", signature_result.signature.len()); - println!( + log::debug!(" - Signature: {} bytes", signature_result.signature.len()); + log::debug!( " - Signature (hex): {}", hex::encode(&signature_result.signature) ); @@ -856,11 +865,11 @@ mod tests { .await .unwrap(); - println!( + log::info!( "✓ Signature verification: {}", if valid { "VALID" } else { "INVALID" } ); - println!("=== CRYPTO DEMO COMPLETE ===\n"); + log::info!("=== CRYPTO DEMO COMPLETE ===\n"); assert!(valid); } diff --git a/src/lib.rs b/src/lib.rs index d9d4bf0..e821255 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -71,24 +71,33 @@ pub struct Random; mod tests { use super::*; + fn init() { + static INIT: std::sync::Once = std::sync::Once::new(); + INIT.call_once(|| { + let _ = env_logger::builder().is_test(true).try_init(); + }); + } + #[test] fn test_hal_creation() { + init(); // Test with a specific platform since auto-detection requires actual hardware let hal = ElasticTeeHal::with_platform(platform::PlatformType::AmdSev); match &hal { Ok(_) => {} - Err(e) => println!("HAL creation failed: {:?}", e), + Err(e) => log::error!("HAL creation failed: {:?}", e), } assert!(hal.is_ok()); } #[test] fn test_platform_detection() { + init(); // Test auto-detection to see what's available let hal = ElasticTeeHal::new(); match &hal { - Ok(_) => println!("Platform auto-detection succeeded!"), - Err(e) => println!("Platform auto-detection failed: {:?}", e), + Ok(_) => log::info!("Platform auto-detection succeeded!"), + Err(e) => log::error!("Platform auto-detection failed: {:?}", e), } // Don't assert since this might fail on non-TEE hardware } diff --git a/src/platform.rs b/src/platform.rs index d03cdc8..3416fa7 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -128,11 +128,11 @@ impl ElasticTeeHal { // Check for TSM support (Trust Security Module for attestation) let has_tsm = std::path::Path::new("/sys/kernel/config/tsm/report").exists(); - println!("AMD SEV Detection:"); - println!(" - AMD CPU: {}", is_amd); - println!(" - /dev/sev-guest: {}", has_sev_guest); - println!(" - /dev/sev: {}", has_sev_dev); - println!(" - TSM support: {}", has_tsm); + log::debug!("AMD SEV Detection:"); + log::debug!(" - AMD CPU: {}", is_amd); + log::debug!(" - /dev/sev-guest: {}", has_sev_guest); + log::debug!(" - /dev/sev: {}", has_sev_dev); + log::debug!(" - TSM support: {}", has_tsm); is_amd && (has_sev_guest || has_sev_dev) && has_tsm } @@ -173,11 +173,11 @@ impl ElasticTeeHal { // Check for TDX guest flag in CPU features let has_tdx_flag = Self::has_tdx_cpu_flag(); - println!("Intel TDX Detection:"); - println!(" - Intel CPU: {}", is_intel); - println!(" - /dev/tdx_guest: {}", has_tdx_guest); - println!(" - TSM support: {}", has_tsm); - println!(" - TDX CPU flag: {}", has_tdx_flag); + log::debug!("Intel TDX Detection:"); + log::debug!(" - Intel CPU: {}", is_intel); + log::debug!(" - /dev/tdx_guest: {}", has_tdx_guest); + log::debug!(" - TSM support: {}", has_tsm); + log::debug!(" - TDX CPU flag: {}", has_tdx_flag); is_intel && has_tdx_guest && has_tsm && has_tdx_flag } diff --git a/src/random.rs b/src/random.rs index a31b66d..c936f28 100644 --- a/src/random.rs +++ b/src/random.rs @@ -205,9 +205,9 @@ pub mod hardware_rng { let is_tdx = content.contains("tdx_guest"); if is_tdx { - println!("Intel TDX Hardware RNG:"); - println!(" - RDRAND available: {}", has_rdrand); - println!(" - RDSEED available: {}", has_rdseed); + log::debug!("Intel TDX Hardware RNG:"); + log::debug!(" - RDRAND available: {}", has_rdrand); + log::debug!(" - RDSEED available: {}", has_rdseed); } has_rdrand || has_rdseed @@ -240,6 +240,13 @@ pub mod hardware_rng { mod tests { use super::*; + fn init() { + static INIT: std::sync::Once = std::sync::Once::new(); + INIT.call_once(|| { + let _ = env_logger::builder().is_test(true).try_init(); + }); + } + #[test] fn test_random_bytes_generation() { let rng = RandomInterface::new(); @@ -369,11 +376,12 @@ mod tests { #[test] fn test_hardware_rng_availability() { + init(); use hardware_rng::*; // Test availability check let available = is_hardware_rng_available(); - println!("Hardware RNG available: {}", available); + log::info!("Hardware RNG available: {}", available); // Test hardware random generation (may fall back to software) if available { diff --git a/src/sockets.rs b/src/sockets.rs index bbaf9c3..e21ca69 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -616,6 +616,13 @@ mod tests { use super::*; use tokio::time::{timeout, Duration}; + fn init() { + static INIT: std::sync::Once = std::sync::Once::new(); + INIT.call_once(|| { + let _ = env_logger::builder().is_test(true).try_init(); + }); + } + #[tokio::test] async fn test_tcp_socket_creation() { let socket_interface = SocketInterface::new(); @@ -648,27 +655,28 @@ mod tests { #[tokio::test] async fn test_tcp_connection() { - println!("=== SOCKET DEMO: TCP Connection & Data Transfer ==="); + init(); + log::info!("=== SOCKET DEMO: TCP Connection & Data Transfer ==="); // First verify we're running in SEV-SNP environment match crate::ElasticTeeHal::new() { Ok(hal) => { if matches!(hal.platform_type(), crate::platform::PlatformType::AmdSev) { - println!("✓ VERIFIED: Running in AMD SEV-SNP Trusted Execution Environment"); - println!(" - TEE Device: /dev/sev-guest detected"); - println!(" - Network traffic is TEE-isolated"); - println!(" - Memory encryption protects data in transit"); + log::info!("✓ VERIFIED: Running in AMD SEV-SNP Trusted Execution Environment"); + log::debug!(" - TEE Device: /dev/sev-guest detected"); + log::debug!(" - Network traffic is TEE-isolated"); + log::debug!(" - Memory encryption protects data in transit"); } else { - println!("✓ TEE Environment detected: {:?}", hal.platform_type()); - println!(" - Network traffic is TEE-isolated"); - println!(" - Memory encryption protects data in transit"); + log::info!("✓ TEE Environment detected: {:?}", hal.platform_type()); + log::debug!(" - Network traffic is TEE-isolated"); + log::debug!(" - Memory encryption protects data in transit"); } } Err(_) => { - println!("⚠ Warning: Not running in verified TEE environment"); + log::warn!("⚠ Warning: Not running in verified TEE environment"); } } - println!(); + log::info!(""); let socket_interface = SocketInterface::new(); @@ -683,16 +691,16 @@ mod tests { .unwrap(); let listen_addr = listener_info.local_address.unwrap(); - println!("✓ Created TCP listener on {}", listen_addr); - println!(" - Socket type: {}", listener_info.socket_type); - println!(" - Handle: {}", listener_handle); + log::info!("✓ Created TCP listener on {}", listen_addr); + log::debug!(" - Socket type: {}", listener_info.socket_type); + log::debug!(" - Handle: {}", listener_handle); // Connect in background task let socket_interface_clone = Arc::new(socket_interface); let connect_task = { let socket_interface = socket_interface_clone.clone(); let addr = format!("127.0.0.1:{}", listen_addr.port()); - println!("✓ Initiating connection to {}", addr); + log::info!("✓ Initiating connection to {}", addr); tokio::spawn(async move { socket_interface.tcp_connect(&addr).await }) }; @@ -706,19 +714,19 @@ mod tests { let accept_handle = accept_result .expect("Accept timeout") .expect("Accept failed"); - println!("✓ Accepted incoming connection"); - println!(" - Server-side handle: {}", accept_handle); + log::info!("✓ Accepted incoming connection"); + log::debug!(" - Server-side handle: {}", accept_handle); let connect_handle = connect_task .await .expect("Connect task failed") .expect("Connect failed"); - println!("✓ Client connection established"); - println!(" - Client-side handle: {}", connect_handle); + log::info!("✓ Client connection established"); + log::debug!(" - Client-side handle: {}", connect_handle); // Test data transfer let test_message = b"Hello from ELASTIC TEE HAL!"; - println!( + log::info!( "✓ Sending test message: {:?}", std::str::from_utf8(test_message).unwrap() ); @@ -727,16 +735,16 @@ mod tests { .socket_write(connect_handle, test_message) .await .unwrap(); - println!(" - Bytes sent: {}", write_result.bytes_transferred); + log::debug!(" - Bytes sent: {}", write_result.bytes_transferred); let mut buffer = [0u8; 1024]; let read_result = socket_interface_clone .socket_read(accept_handle, &mut buffer) .await .unwrap(); - println!("✓ Received message on server side"); - println!(" - Bytes received: {}", read_result.bytes_transferred); - println!( + log::info!("✓ Received message on server side"); + log::debug!(" - Bytes received: {}", read_result.bytes_transferred); + log::debug!( " - Message: {:?}", std::str::from_utf8(&buffer[..read_result.bytes_transferred]).unwrap() ); @@ -744,12 +752,12 @@ mod tests { // Verify message integrity let received_data = &buffer[..read_result.bytes_transferred]; let message_verified = received_data == test_message; - println!( + log::info!( "✓ Message integrity verification: {}", if message_verified { "PASSED" } else { "FAILED" } ); - println!("=== SOCKET DEMO COMPLETE ===\n"); + log::info!("=== SOCKET DEMO COMPLETE ===\n"); // Verify both handles are valid assert!(accept_handle > 0); @@ -834,6 +842,7 @@ mod tests { #[tokio::test] async fn test_key_context_operations() { + init(); let socket_interface = SocketInterface::new(); // Test that PKCS12 parsing doesn't crash with placeholder data @@ -847,9 +856,9 @@ mod tests { // For the placeholder implementation, we expect this to fail with a crypto error // In a real implementation with proper PKCS12 parsing, this would succeed match &result { - Ok(_) => println!("Key context operation succeeded"), + Ok(_) => log::info!("Key context operation succeeded"), Err(e) => { - println!( + log::info!( "Key context operation failed as expected with placeholder data: {:?}", e ); diff --git a/tests/tdx_all_interfaces_test.rs b/tests/tdx_all_interfaces_test.rs index 54925e3..e5a54e7 100644 --- a/tests/tdx_all_interfaces_test.rs +++ b/tests/tdx_all_interfaces_test.rs @@ -12,9 +12,17 @@ use elastic_tee_hal::resources::{ResourceInterface, ResourceLimits}; use elastic_tee_hal::*; use std::sync::Arc; +fn init() { + static INIT: std::sync::Once = std::sync::Once::new(); + INIT.call_once(|| { + let _ = env_logger::builder().is_test(true).try_init(); + }); +} + #[tokio::test] async fn test_tdx_crypto_interface_complete() { - println!("\n=== TDX CRYPTO INTERFACE TEST ==="); + init(); + log::info!("\n=== TDX CRYPTO INTERFACE TEST ==="); // Verify TDX environment let hal = ElasticTeeHal::new().expect("Failed to initialize HAL"); @@ -22,7 +30,7 @@ async fn test_tdx_crypto_interface_complete() { hal.platform_type(), platform::PlatformType::IntelTdx )); - println!("✓ Verified Intel TDX environment"); + log::info!("✓ Verified Intel TDX environment"); let crypto = CryptoInterface::new(); @@ -32,14 +40,14 @@ async fn test_tdx_crypto_interface_complete() { .await .expect("Key generation failed"); assert_eq!(key.len(), 32); - println!("✓ Generated AES-256-GCM key: {} bytes", key.len()); + log::info!("✓ Generated AES-256-GCM key: {} bytes", key.len()); let plaintext = b"TDX secure data"; let ciphertext = crypto .symmetric_encrypt("AES-256-GCM", &key, plaintext, None) .await .expect("Encryption failed"); - println!( + log::info!( "✓ Encrypted data: {} bytes -> {} bytes", plaintext.len(), ciphertext.len() @@ -50,7 +58,7 @@ async fn test_tdx_crypto_interface_complete() { .await .expect("Decryption failed"); assert_eq!(plaintext, decrypted.as_slice()); - println!("✓ Decrypted and verified data"); + log::info!("✓ Decrypted and verified data"); // Test hashing let hash = crypto @@ -58,7 +66,7 @@ async fn test_tdx_crypto_interface_complete() { .await .expect("Hashing failed"); assert_eq!(hash.len(), 32); - println!("✓ SHA-256 hash: {} bytes", hash.len()); + log::info!("✓ SHA-256 hash: {} bytes", hash.len()); // Test platform attestation with TDX measurements let nonce = b"tdx_attestation_nonce_12345678"; @@ -72,9 +80,9 @@ async fn test_tdx_crypto_interface_complete() { attestation.measurements.contains_key("MRTD") || attestation.measurements.contains_key("RTMR0") ); - println!("✓ TDX attestation generated with measurements:"); + log::info!("✓ TDX attestation generated with measurements:"); for (key, value) in &attestation.measurements { - println!(" - {}: {}", key, value); + log::debug!(" - {}: {}", key, value); } // Test sealing/unsealing (TDX-specific) @@ -87,14 +95,15 @@ async fn test_tdx_crypto_interface_complete() { .await .expect("Unsealing failed"); assert_eq!(unsealed, b"secret"); - println!("✓ TDX sealing/unsealing verified"); + log::info!("✓ TDX sealing/unsealing verified"); - println!("=== CRYPTO TEST COMPLETE ===\n"); + log::info!("=== CRYPTO TEST COMPLETE ===\n"); } #[tokio::test] async fn test_tdx_gpu_interface_complete() { - println!("\n=== TDX GPU INTERFACE TEST ==="); + init(); + log::info!("\n=== TDX GPU INTERFACE TEST ==="); // Verify TDX environment let hal = ElasticTeeHal::new().expect("Failed to initialize HAL"); @@ -102,7 +111,7 @@ async fn test_tdx_gpu_interface_complete() { hal.platform_type(), platform::PlatformType::IntelTdx )); - println!("✓ Verified Intel TDX environment"); + log::info!("✓ Verified Intel TDX environment"); let gpu = GpuInterface::new(); @@ -112,14 +121,14 @@ async fn test_tdx_gpu_interface_complete() { .await .expect("Failed to get adapters"); assert!(!adapters.is_empty()); - println!("✓ Found {} GPU adapters (TDX-compatible)", adapters.len()); + log::info!("✓ Found {} GPU adapters (TDX-compatible)", adapters.len()); for adapter_handle in &adapters { let info = gpu .get_gpu_adapter_info(*adapter_handle) .await .expect("Failed to get adapter info"); - println!(" - {} ({})", info.name, info.vendor); + log::debug!(" - {} ({})", info.name, info.vendor); // TDX should not have discrete GPUs if info.name.contains("TDX") { @@ -127,7 +136,7 @@ async fn test_tdx_gpu_interface_complete() { info.device_type, gpu::GpuDeviceType::Cpu | gpu::GpuDeviceType::VirtualGpu )); - println!(" Type: {:?} (TDX-appropriate)", info.device_type); + log::debug!(" Type: {:?} (TDX-appropriate)", info.device_type); } } @@ -136,7 +145,7 @@ async fn test_tdx_gpu_interface_complete() { .create_gpu_device(adapters[0]) .await .expect("Failed to create device"); - println!("✓ Created GPU device: {}", device_handle); + log::info!("✓ Created GPU device: {}", device_handle); // Create compute pipeline let shader = b"#version 450\nlayout(local_size_x = 1) in;\nvoid main() {}"; @@ -144,7 +153,7 @@ async fn test_tdx_gpu_interface_complete() { .create_gpu_compute_pipeline(device_handle, shader, "main", [1, 1, 1]) .await .expect("Failed to create pipeline"); - println!("✓ Created compute pipeline: {}", pipeline_handle); + log::info!("✓ Created compute pipeline: {}", pipeline_handle); // Create and use buffer let buffer_desc = GpuBufferDescriptor { @@ -163,17 +172,19 @@ async fn test_tdx_gpu_interface_complete() { .create_gpu_buffer(device_handle, &buffer_desc) .await .expect("Failed to create buffer"); - println!( + log::info!( "✓ Created GPU buffer: {} ({} bytes)", - buffer_handle, buffer_desc.size + buffer_handle, + buffer_desc.size ); - println!("=== GPU TEST COMPLETE ===\n"); + log::info!("=== GPU TEST COMPLETE ===\n"); } #[tokio::test] async fn test_tdx_resources_interface_complete() { - println!("\n=== TDX RESOURCES INTERFACE TEST ==="); + init(); + log::info!("\n=== TDX RESOURCES INTERFACE TEST ==="); // Verify TDX environment let hal = ElasticTeeHal::new().expect("Failed to initialize HAL"); @@ -181,7 +192,7 @@ async fn test_tdx_resources_interface_complete() { hal.platform_type(), platform::PlatformType::IntelTdx )); - println!("✓ Verified Intel TDX environment"); + log::info!("✓ Verified Intel TDX environment"); let resources = ResourceInterface::new().expect("Failed to create resource interface"); @@ -190,11 +201,11 @@ async fn test_tdx_resources_interface_complete() { .get_system_limits() .await .expect("Failed to get limits"); - println!("✓ System limits (TDX-adjusted):"); - println!(" - Memory: {} MB", limits.max_memory_mb); - println!(" - CPU cores: {}", limits.max_cpu_cores); - println!(" - Storage: {} MB", limits.max_storage_mb); - println!( + log::info!("✓ System limits (TDX-adjusted):"); + log::debug!(" - Memory: {} MB", limits.max_memory_mb); + log::debug!(" - CPU cores: {}", limits.max_cpu_cores); + log::debug!(" - Storage: {} MB", limits.max_storage_mb); + log::debug!( " - GPU memory: {} MB (TDX: limited)", limits.max_gpu_memory_mb ); @@ -210,14 +221,14 @@ async fn test_tdx_resources_interface_complete() { .request_additional_memory(512, "tdx_test_app") .await .expect("Memory allocation failed"); - println!("✓ Allocated 512 MB: {}", alloc.allocation_id); + log::info!("✓ Allocated 512 MB: {}", alloc.allocation_id); // Request CPU allocation let cpu_alloc = resources .request_additional_cpu(2, "tdx_test_app") .await .expect("CPU allocation failed"); - println!("✓ Allocated 2 CPU cores: {}", cpu_alloc.allocation_id); + log::info!("✓ Allocated 2 CPU cores: {}", cpu_alloc.allocation_id); // Check usage let usage = resources @@ -226,9 +237,10 @@ async fn test_tdx_resources_interface_complete() { .expect("Failed to get usage"); assert_eq!(usage.memory_mb, 512); assert_eq!(usage.cpu_cores, 2); - println!( + log::info!( "✓ Current usage: {} MB RAM, {} CPU cores", - usage.memory_mb, usage.cpu_cores + usage.memory_mb, + usage.cpu_cores ); // Get statistics @@ -236,10 +248,10 @@ async fn test_tdx_resources_interface_complete() { .get_resource_statistics() .await .expect("Failed to get stats"); - println!("✓ Resource utilization:"); - println!(" - Memory: {:.2}%", stats.memory_utilization_percent); - println!(" - CPU: {:.2}%", stats.cpu_utilization_percent); - println!(" - Total allocations: {}", stats.total_allocations); + log::info!("✓ Resource utilization:"); + log::debug!(" - Memory: {:.2}%", stats.memory_utilization_percent); + log::debug!(" - CPU: {:.2}%", stats.cpu_utilization_percent); + log::debug!(" - Total allocations: {}", stats.total_allocations); // Release resources resources @@ -250,14 +262,15 @@ async fn test_tdx_resources_interface_complete() { .release_resource(&cpu_alloc.allocation_id) .await .expect("Failed to release CPU"); - println!("✓ Released all allocations"); + log::info!("✓ Released all allocations"); - println!("=== RESOURCES TEST COMPLETE ===\n"); + log::info!("=== RESOURCES TEST COMPLETE ===\n"); } #[tokio::test] async fn test_tdx_events_interface_complete() { - println!("\n=== TDX EVENTS INTERFACE TEST ==="); + init(); + log::info!("\n=== TDX EVENTS INTERFACE TEST ==="); // Verify TDX environment let hal = ElasticTeeHal::new().expect("Failed to initialize HAL"); @@ -265,7 +278,7 @@ async fn test_tdx_events_interface_complete() { hal.platform_type(), platform::PlatformType::IntelTdx )); - println!("✓ Verified Intel TDX environment (secure event channels)"); + log::info!("✓ Verified Intel TDX environment (secure event channels)"); let events = EventInterface::new(); @@ -280,7 +293,7 @@ async fn test_tdx_events_interface_complete() { .create_event_handler(config1) .await .expect("Failed to create handler"); - println!("✓ Created event handler 1: {}", handler1); + log::info!("✓ Created event handler 1: {}", handler1); let config2 = EventHandlerConfig { name: "tdx_handler_2".to_string(), @@ -292,7 +305,7 @@ async fn test_tdx_events_interface_complete() { .create_event_handler(config2) .await .expect("Failed to create handler"); - println!("✓ Created event handler 2: {}", handler2); + log::info!("✓ Created event handler 2: {}", handler2); // Create subscriptions let filter = SubscriptionFilter { @@ -310,7 +323,7 @@ async fn test_tdx_events_interface_complete() { .request_event_subscription(handler2, filter) .await .expect("Failed to create subscription"); - println!("✓ Created subscriptions for both handlers"); + log::info!("✓ Created subscriptions for both handlers"); // Send global event let event = EventInterface::create_event( @@ -325,7 +338,7 @@ async fn test_tdx_events_interface_complete() { .send_event_global(event) .await .expect("Failed to send event"); - println!("✓ Sent TDX secure event"); + log::info!("✓ Sent TDX secure event"); // Receive events tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; @@ -335,30 +348,31 @@ async fn test_tdx_events_interface_complete() { .await .expect("Failed to receive event 1"); assert!(event1.is_some()); - println!("✓ Handler 1 received event"); + log::info!("✓ Handler 1 received event"); let event2 = events .try_request_event_from_handler(handler2) .await .expect("Failed to receive event 2"); assert!(event2.is_some()); - println!("✓ Handler 2 received event"); + log::info!("✓ Handler 2 received event"); // Get statistics let stats = events .get_event_statistics() .await .expect("Failed to get stats"); - println!("✓ Event statistics:"); - println!(" - Handlers: {}", stats.total_handlers); - println!(" - Subscriptions: {}", stats.total_subscriptions); + log::info!("✓ Event statistics:"); + log::debug!(" - Handlers: {}", stats.total_handlers); + log::debug!(" - Subscriptions: {}", stats.total_subscriptions); - println!("=== EVENTS TEST COMPLETE ===\n"); + log::info!("=== EVENTS TEST COMPLETE ===\n"); } #[tokio::test] async fn test_tdx_communication_interface_complete() { - println!("\n=== TDX COMMUNICATION INTERFACE TEST ==="); + init(); + log::info!("\n=== TDX COMMUNICATION INTERFACE TEST ==="); // Verify TDX environment let hal = ElasticTeeHal::new().expect("Failed to initialize HAL"); @@ -366,7 +380,7 @@ async fn test_tdx_communication_interface_complete() { hal.platform_type(), platform::PlatformType::IntelTdx )); - println!("✓ Verified Intel TDX environment (encrypted comm buffers)"); + log::info!("✓ Verified Intel TDX environment (encrypted comm buffers)"); let comm = CommunicationInterface::new(); @@ -384,7 +398,7 @@ async fn test_tdx_communication_interface_complete() { .setup_communication_buffer(config) .await .expect("Failed to create buffer"); - println!( + log::info!( "✓ Created TDX-encrypted communication buffer: {}", buffer_handle ); @@ -394,9 +408,9 @@ async fn test_tdx_communication_interface_complete() { .await .expect("Failed to get info"); assert!(info.is_encrypted); - println!(" - Name: {}", info.name); - println!(" - Capacity: {} bytes", info.capacity); - println!(" - Encrypted: {}", info.is_encrypted); + log::debug!(" - Name: {}", info.name); + log::debug!(" - Capacity: {} bytes", info.capacity); + log::debug!(" - Encrypted: {}", info.is_encrypted); // Push data let test_data = b"TDX secure inter-TD message"; @@ -409,7 +423,7 @@ async fn test_tdx_communication_interface_complete() { ) .await .expect("Failed to push data"); - println!("✓ Pushed {} bytes to TDX-encrypted buffer", test_data.len()); + log::info!("✓ Pushed {} bytes to TDX-encrypted buffer", test_data.len()); // Read data let message = comm @@ -421,9 +435,9 @@ async fn test_tdx_communication_interface_complete() { let message = message.unwrap(); assert_eq!(message.data, test_data); assert_eq!(message.sender, "writer1"); - println!("✓ Read and verified data from TDX-encrypted buffer"); - println!(" - Sender: {}", message.sender); - println!(" - Data: {} bytes", message.data.len()); + log::info!("✓ Read and verified data from TDX-encrypted buffer"); + log::debug!(" - Sender: {}", message.sender); + log::debug!(" - Data: {} bytes", message.data.len()); // List buffers let buffers = comm @@ -431,14 +445,15 @@ async fn test_tdx_communication_interface_complete() { .await .expect("Failed to list buffers"); assert_eq!(buffers.len(), 1); - println!("✓ Listed {} communication buffer(s)", buffers.len()); + log::info!("✓ Listed {} communication buffer(s)", buffers.len()); - println!("=== COMMUNICATION TEST COMPLETE ===\n"); + log::info!("=== COMMUNICATION TEST COMPLETE ===\n"); } #[tokio::test] async fn test_tdx_platform_capabilities_complete() { - println!("\n=== TDX PLATFORM CAPABILITIES TEST ==="); + init(); + log::info!("\n=== TDX PLATFORM CAPABILITIES TEST ==="); // Initialize HAL let hal = ElasticTeeHal::new().expect("Failed to initialize HAL"); @@ -446,7 +461,7 @@ async fn test_tdx_platform_capabilities_complete() { hal.platform_type(), platform::PlatformType::IntelTdx )); - println!("✓ Verified Intel TDX environment"); + log::info!("✓ Verified Intel TDX environment"); // Get capabilities let caps = hal.capabilities().await; @@ -454,32 +469,32 @@ async fn test_tdx_platform_capabilities_complete() { caps.platform_type, platform::PlatformType::IntelTdx )); - println!("✓ Platform type: {:?}", caps.platform_type); - println!("✓ HAL version: {}", caps.hal_version); + log::info!("✓ Platform type: {:?}", caps.platform_type); + log::info!("✓ HAL version: {}", caps.hal_version); // Check TDX-specific features - println!("✓ TDX Features:"); - println!(" - Clock: {} ✅", caps.features.clock); - println!(" - Random: {} ✅", caps.features.random); - println!(" - Storage: {} ✅", caps.features.storage); - println!(" - Secure Storage: {} ✅", caps.features.secure_storage); - println!(" - TCP Sockets: {} ✅", caps.features.tcp_sockets); - println!(" - UDP Sockets: {} ✅", caps.features.udp_sockets); - println!(" - TLS Support: {} ✅", caps.features.tls_support); - println!( + log::info!("✓ TDX Features:"); + log::info!(" - Clock: {} ✅", caps.features.clock); + log::info!(" - Random: {} ✅", caps.features.random); + log::info!(" - Storage: {} ✅", caps.features.storage); + log::info!(" - Secure Storage: {} ✅", caps.features.secure_storage); + log::info!(" - TCP Sockets: {} ✅", caps.features.tcp_sockets); + log::info!(" - UDP Sockets: {} ✅", caps.features.udp_sockets); + log::info!(" - TLS Support: {} ✅", caps.features.tls_support); + log::info!( " - GPU Compute: {} ❌ (TDX limitation)", caps.features.gpu_compute ); - println!( + log::info!( " - Dynamic Resources: {} ✅", caps.features.dynamic_resources ); - println!(" - Event Handling: {} ✅", caps.features.event_handling); - println!( + log::info!(" - Event Handling: {} ✅", caps.features.event_handling); + log::info!( " - Internal Communication: {} ✅", caps.features.internal_communication ); - println!(" - Attestation: {} ✅", caps.features.attestation); + log::info!(" - Attestation: {} ✅", caps.features.attestation); assert!( !caps.features.gpu_compute, @@ -492,10 +507,10 @@ async fn test_tdx_platform_capabilities_complete() { ); // Check crypto support - println!("✓ Cryptographic Support:"); - println!(" - Symmetric: {:?}", caps.crypto_support.symmetric_ciphers); - println!(" - Hash: {:?}", caps.crypto_support.hash_algorithms); - println!( + log::info!("✓ Cryptographic Support:"); + log::debug!(" - Symmetric: {:?}", caps.crypto_support.symmetric_ciphers); + log::debug!(" - Hash: {:?}", caps.crypto_support.hash_algorithms); + log::debug!( " - Hardware Acceleration: {}", caps.crypto_support.hardware_acceleration ); @@ -508,24 +523,25 @@ async fn test_tdx_platform_capabilities_complete() { assert!(caps.is_crypto_supported("hash", "SHA-256")); // Check resource limits - println!("✓ Platform Limits:"); - println!(" - Max Memory: {} MB", caps.limits.max_memory_mb); - println!(" - Max CPU Cores: {}", caps.limits.max_cpu_cores); - println!(" - Max Storage: {} MB", caps.limits.max_storage_mb); - println!(" - Max Sockets: {}", caps.limits.max_open_sockets); + log::info!("✓ Platform Limits:"); + log::debug!(" - Max Memory: {} MB", caps.limits.max_memory_mb); + log::debug!(" - Max CPU Cores: {}", caps.limits.max_cpu_cores); + log::debug!(" - Max Storage: {} MB", caps.limits.max_storage_mb); + log::debug!(" - Max Sockets: {}", caps.limits.max_open_sockets); - println!("=== CAPABILITIES TEST COMPLETE ===\n"); + log::info!("=== CAPABILITIES TEST COMPLETE ===\n"); } #[tokio::test] async fn test_tdx_full_integration() { - println!("\n=== TDX FULL INTEGRATION TEST ==="); - println!("Testing all interfaces working together in Intel TDX...\n"); + init(); + log::info!("\n=== TDX FULL INTEGRATION TEST ==="); + log::info!("Testing all interfaces working together in Intel TDX...\n"); // Initialize HAL let hal = ElasticTeeHal::new().expect("Failed to initialize HAL"); let platform_type = hal.platform_type(); - println!("✓ Platform: {:?}", platform_type); + log::info!("✓ Platform: {:?}", platform_type); assert!(matches!(platform_type, platform::PlatformType::IntelTdx)); // Initialize all interfaces @@ -535,7 +551,7 @@ async fn test_tdx_full_integration() { let events = EventInterface::new(); let comm = CommunicationInterface::with_crypto(crypto.clone()); - println!("✓ Initialized all interfaces"); + log::info!("✓ Initialized all interfaces"); // 1. Test crypto with attestation let attestation = crypto @@ -543,21 +559,21 @@ async fn test_tdx_full_integration() { .await .expect("Attestation failed"); assert_eq!(attestation.platform_type, "intel-tdx"); - println!("✓ [1/7] Crypto + Attestation: TDX measurements collected"); + log::info!("✓ [1/7] Crypto + Attestation: TDX measurements collected"); // 2. Test GPU (limited in TDX) let adapters = gpu .get_gpu_adapters() .await .expect("Failed to get adapters"); - println!("✓ [2/7] GPU: {} adapters (TDX-compatible)", adapters.len()); + log::info!("✓ [2/7] GPU: {} adapters (TDX-compatible)", adapters.len()); // 3. Test resource allocation with TDX overhead let mem_alloc = resources .request_additional_memory(256, "integration_test") .await .expect("Memory allocation failed"); - println!("✓ [3/7] Resources: Allocated 256 MB (TDX overhead accounted)"); + log::info!("✓ [3/7] Resources: Allocated 256 MB (TDX overhead accounted)"); // 4. Test secure event handling let handler_config = EventHandlerConfig { @@ -569,7 +585,7 @@ async fn test_tdx_full_integration() { .create_event_handler(handler_config) .await .expect("Handler creation failed"); - println!("✓ [4/7] Events: Secure event handler created"); + log::info!("✓ [4/7] Events: Secure event handler created"); // 5. Test encrypted communication let buffer_config = BufferConfig { @@ -584,7 +600,7 @@ async fn test_tdx_full_integration() { .setup_communication_buffer(buffer_config) .await .expect("Buffer creation failed"); - println!("✓ [5/7] Communication: TDX-encrypted buffer created"); + log::info!("✓ [5/7] Communication: TDX-encrypted buffer created"); // 6. Test end-to-end encrypted message flow let message = b"End-to-end TDX secure message"; @@ -604,15 +620,15 @@ async fn test_tdx_full_integration() { .expect("Failed to read message") .expect("No message received"); assert_eq!(received.data, message); - println!("✓ [6/7] End-to-end: Message encrypted, transmitted, and decrypted"); + log::info!("✓ [6/7] End-to-end: Message encrypted, transmitted, and decrypted"); // 7. Cleanup resources .release_resource(&mem_alloc.allocation_id) .await .expect("Failed to release resources"); - println!("✓ [7/7] Cleanup: All resources released"); + log::info!("✓ [7/7] Cleanup: All resources released"); - println!("\n=== FULL INTEGRATION TEST COMPLETE ==="); - println!("All 7 interfaces working correctly in Intel TDX environment!"); + log::info!("\n=== FULL INTEGRATION TEST COMPLETE ==="); + log::info!("All 7 interfaces working correctly in Intel TDX environment!"); } diff --git a/tests/tdx_integration_test.rs b/tests/tdx_integration_test.rs index 488bfc7..79c0d78 100644 --- a/tests/tdx_integration_test.rs +++ b/tests/tdx_integration_test.rs @@ -6,27 +6,35 @@ use elastic_tee_hal::{ }; use std::time::Duration; +fn init() { + static INIT: std::sync::Once = std::sync::Once::new(); + INIT.call_once(|| { + let _ = env_logger::builder().is_test(true).try_init(); + }); +} + #[tokio::test] #[ignore = "requires Intel TDX hardware (/dev/tdx_guest) and ITA_API_KEY"] async fn test_tdx_platform_detection() -> HalResult<()> { - println!("\n=== INTEL TDX PLATFORM VERIFICATION ==="); + init(); + log::info!("\n=== INTEL TDX PLATFORM VERIFICATION ==="); // Create HAL with automatic platform detection let hal = ElasticTeeHal::new()?; - println!("✓ HAL initialized successfully"); - println!(" - Platform type: {:?}", hal.platform_type()); - println!(" - Initialized: {}", hal.is_initialized()); + log::info!("✓ HAL initialized successfully"); + log::debug!(" - Platform type: {:?}", hal.platform_type()); + log::debug!(" - Initialized: {}", hal.is_initialized()); // Get capabilities let capabilities = hal.capabilities().await; - println!("\n✓ Platform capabilities retrieved"); - println!(" - HAL version: {}", capabilities.hal_version); - println!(" - Clock support: {}", capabilities.features.clock); - println!(" - Random support: {}", capabilities.features.random); - println!(" - Storage support: {}", capabilities.features.storage); - println!(" - Network support: {}", capabilities.features.tcp_sockets); - println!( + log::info!("\n✓ Platform capabilities retrieved"); + log::debug!(" - HAL version: {}", capabilities.hal_version); + log::debug!(" - Clock support: {}", capabilities.features.clock); + log::debug!(" - Random support: {}", capabilities.features.random); + log::debug!(" - Storage support: {}", capabilities.features.storage); + log::debug!(" - Network support: {}", capabilities.features.tcp_sockets); + log::debug!( " - Attestation support: {}", capabilities.features.attestation ); @@ -34,9 +42,9 @@ async fn test_tdx_platform_detection() -> HalResult<()> { // Test attestation with report data (nonce) let nonce = b"test_nonce_12345"; let attestation = hal.attest(nonce).await?; - println!("\n✓ Generated TDX attestation"); - println!(" - Attestation size: {} bytes", attestation.len()); - println!(" - Report data: {} bytes", nonce.len()); + log::info!("\n✓ Generated TDX attestation"); + log::debug!(" - Attestation size: {} bytes", attestation.len()); + log::debug!(" - Report data: {} bytes", nonce.len()); Ok(()) } @@ -44,30 +52,31 @@ async fn test_tdx_platform_detection() -> HalResult<()> { #[tokio::test] #[ignore = "requires Intel TDX hardware (/dev/tdx_guest) and ITA_API_KEY"] async fn test_tdx_clock_interface() -> HalResult<()> { - println!("\n=== INTEL TDX CLOCK INTERFACE TEST ==="); + init(); + log::info!("\n=== INTEL TDX CLOCK INTERFACE TEST ==="); let clock = ClockInterface::new(); // Test system time let time_info = clock.read_current_time()?; - println!("✓ System time read successfully"); - println!(" - Seconds since epoch: {}", time_info.seconds); - println!(" - Nanoseconds: {}", time_info.nanoseconds); + log::info!("✓ System time read successfully"); + log::debug!(" - Seconds since epoch: {}", time_info.seconds); + log::debug!(" - Nanoseconds: {}", time_info.nanoseconds); // Test monotonic time let monotonic = clock.read_monotonic_time()?; - println!("\n✓ Monotonic time read successfully"); - println!(" - Elapsed seconds: {}", monotonic.elapsed_seconds); - println!(" - Elapsed nanoseconds: {}", monotonic.elapsed_nanoseconds); + log::info!("\n✓ Monotonic time read successfully"); + log::debug!(" - Elapsed seconds: {}", monotonic.elapsed_seconds); + log::debug!(" - Elapsed nanoseconds: {}", monotonic.elapsed_nanoseconds); // Test sleep - println!("\n✓ Testing async sleep (10ms)..."); + log::info!("\n✓ Testing async sleep (10ms)..."); clock.sleep(Duration::from_millis(10)).await?; - println!(" - Sleep completed successfully"); + log::debug!(" - Sleep completed successfully"); // Test high-resolution timestamp let timestamp = clock.get_high_resolution_timestamp()?; - println!("\n✓ High-resolution timestamp: {} ns", timestamp); + log::info!("\n✓ High-resolution timestamp: {} ns", timestamp); Ok(()) } @@ -75,43 +84,47 @@ async fn test_tdx_clock_interface() -> HalResult<()> { #[tokio::test] #[ignore = "requires Intel TDX hardware (/dev/tdx_guest) and ITA_API_KEY"] async fn test_tdx_random_interface() -> HalResult<()> { - println!("\n=== INTEL TDX RANDOM INTERFACE TEST ==="); - println!("Testing hardware RNG (RDRAND/RDSEED)"); + init(); + log::info!("\n=== INTEL TDX RANDOM INTERFACE TEST ==="); + log::info!("Testing hardware RNG (RDRAND/RDSEED)"); let random = RandomInterface::new(); // Test random bytes generation let bytes = random.generate_random_bytes(32)?; - println!("\n✓ Generated 32 random bytes"); - println!( + log::info!("\n✓ Generated 32 random bytes"); + log::debug!( " - Sample: {:02x}{:02x}{:02x}{:02x}...", - bytes[0], bytes[1], bytes[2], bytes[3] + bytes[0], + bytes[1], + bytes[2], + bytes[3] ); // Test random integers let random_u32 = random.generate_random_u32()?; let random_u64 = random.generate_random_u64()?; - println!("\n✓ Generated random integers"); - println!(" - u32: {}", random_u32); - println!(" - u64: {}", random_u64); + log::info!("\n✓ Generated random integers"); + log::debug!(" - u32: {}", random_u32); + log::debug!(" - u64: {}", random_u64); // Test UUID generation let uuid = random.generate_uuid_v4()?; - println!("\n✓ Generated UUID v4: {}", uuid); + log::info!("\n✓ Generated UUID v4: {}", uuid); // Test nonce generation let nonce = random.generate_nonce(16)?; - println!("\n✓ Generated 16-byte nonce"); + log::info!("\n✓ Generated 16-byte nonce"); // Test key material generation let key_material = random.generate_key_material(32)?; - println!("✓ Generated 32-byte key material"); + log::info!("✓ Generated 32-byte key material"); // Test randomness quality let entropy = random.test_randomness_quality(10000)?; - println!("\n✓ Randomness quality test"); - println!(" - Shannon entropy: {:.4} bits/byte (max: 8.0)", entropy); - println!( + log::info!("\n✓ Randomness quality test"); + log::debug!(" - Shannon entropy: {:.4} bits/byte (max: 8.0)", entropy); + log::debug!( " - Quality: {}", if entropy > 7.5 { "EXCELLENT" } else { "POOR" } ); @@ -119,8 +132,8 @@ async fn test_tdx_random_interface() -> HalResult<()> { // Test hardware RNG detection use elastic_tee_hal::random::hardware_rng; let hw_rng_available = hardware_rng::is_hardware_rng_available(); - println!("\n✓ Hardware RNG detection"); - println!(" - RDRAND/RDSEED available: {}", hw_rng_available); + log::info!("\n✓ Hardware RNG detection"); + log::debug!(" - RDRAND/RDSEED available: {}", hw_rng_available); Ok(()) } @@ -128,57 +141,58 @@ async fn test_tdx_random_interface() -> HalResult<()> { #[tokio::test] #[ignore = "requires Intel TDX hardware (/dev/tdx_guest) and ITA_API_KEY"] async fn test_tdx_storage_interface() -> HalResult<()> { - println!("\n=== INTEL TDX STORAGE INTERFACE TEST ==="); + init(); + log::info!("\n=== INTEL TDX STORAGE INTERFACE TEST ==="); let temp_dir = tempfile::TempDir::new().unwrap(); let storage = StorageInterface::new(temp_dir.path()).await?; - println!("✓ Storage interface initialized"); - println!(" - Base path: {:?}", temp_dir.path()); + log::info!("✓ Storage interface initialized"); + log::debug!(" - Base path: {:?}", temp_dir.path()); // Test unencrypted container let container = storage.open_container("test_container", false).await?; - println!("\n✓ Created unencrypted container"); - println!(" - Handle: {}", container); + log::info!("\n✓ Created unencrypted container"); + log::debug!(" - Handle: {}", container); // Test write and read let test_data = b"Hello from Intel TDX!"; storage .write_object(container, "test_key", test_data) .await?; - println!("\n✓ Wrote object to storage"); - println!(" - Key: test_key"); - println!(" - Size: {} bytes", test_data.len()); + log::info!("\n✓ Wrote object to storage"); + log::debug!(" - Key: test_key"); + log::debug!(" - Size: {} bytes", test_data.len()); let read_data = storage.read_object(container, "test_key").await?; - println!("\n✓ Read object from storage"); - println!(" - Data: {:?}", String::from_utf8_lossy(&read_data)); + log::info!("\n✓ Read object from storage"); + log::debug!(" - Data: {:?}", String::from_utf8_lossy(&read_data)); assert_eq!(test_data, read_data.as_slice()); // Test list objects let objects = storage.list_objects(container).await?; - println!("\n✓ Listed objects in container: {:?}", objects); + log::info!("\n✓ Listed objects in container: {:?}", objects); // Test encrypted container let encrypted_container = storage.open_container("encrypted_container", true).await?; - println!("\n✓ Created encrypted container (AES-256-GCM)"); + log::info!("\n✓ Created encrypted container (AES-256-GCM)"); let secret_data = b"Secret TDX data"; storage .write_object(encrypted_container, "secret", secret_data) .await?; - println!("✓ Wrote encrypted object"); + log::info!("✓ Wrote encrypted object"); let decrypted_data = storage.read_object(encrypted_container, "secret").await?; - println!("✓ Read and decrypted object"); + log::info!("✓ Read and decrypted object"); assert_eq!(secret_data, decrypted_data.as_slice()); // Test metadata let metadata = storage.get_container_metadata(container).await?; - println!("\n✓ Container metadata:"); - println!(" - Object count: {}", metadata.object_count); - println!(" - Total size: {} bytes", metadata.total_size); - println!(" - Encrypted: {}", metadata.encrypted); + log::info!("\n✓ Container metadata:"); + log::debug!(" - Object count: {}", metadata.object_count); + log::debug!(" - Total size: {} bytes", metadata.total_size); + log::debug!(" - Encrypted: {}", metadata.encrypted); Ok(()) } @@ -186,32 +200,33 @@ async fn test_tdx_storage_interface() -> HalResult<()> { #[tokio::test] #[ignore = "requires Intel TDX hardware (/dev/tdx_guest) and ITA_API_KEY"] async fn test_tdx_network_interface() -> HalResult<()> { - println!("\n=== INTEL TDX NETWORK INTERFACE TEST ==="); - println!("Testing TCP sockets with TDX network isolation"); + init(); + log::info!("\n=== INTEL TDX NETWORK INTERFACE TEST ==="); + log::info!("Testing TCP sockets with TDX network isolation"); let sockets = SocketInterface::new(); // Test TCP socket creation let listener_handle = sockets.create_tcp_socket("127.0.0.1:0").await?; - println!("\n✓ Created TCP listener"); - println!(" - Handle: {}", listener_handle); + log::info!("\n✓ Created TCP listener"); + log::debug!(" - Handle: {}", listener_handle); // Get the actual bound address let listener_addr = sockets.get_socket_info(listener_handle).await?; - println!(" - Bound to: {:?}", listener_addr.local_address); + log::debug!(" - Bound to: {:?}", listener_addr.local_address); // Test UDP socket let udp_handle = sockets.create_udp_socket("127.0.0.1:0").await?; - println!("\n✓ Created UDP socket"); - println!(" - Handle: {}", udp_handle); + log::info!("\n✓ Created UDP socket"); + log::debug!(" - Handle: {}", udp_handle); let udp_info = sockets.get_socket_info(udp_handle).await?; - println!(" - Bound to: {:?}", udp_info.local_address); + log::debug!(" - Bound to: {:?}", udp_info.local_address); - println!("\n✓ Network interface test completed"); - println!(" - TCP sockets: working"); - println!(" - UDP sockets: working"); - println!(" - TDX network isolation: active"); + log::info!("\n✓ Network interface test completed"); + log::debug!(" - TCP sockets: working"); + log::debug!(" - UDP sockets: working"); + log::debug!(" - TDX network isolation: active"); Ok(()) } @@ -219,17 +234,18 @@ async fn test_tdx_network_interface() -> HalResult<()> { #[tokio::test] #[ignore = "requires Intel TDX hardware (/dev/tdx_guest) and ITA_API_KEY"] async fn test_tdx_all_interfaces_integration() -> HalResult<()> { - println!("\n=== INTEL TDX FULL INTEGRATION TEST ==="); - println!("Testing all 4 WASI interfaces together"); + init(); + log::info!("\n=== INTEL TDX FULL INTEGRATION TEST ==="); + log::info!("Testing all 4 WASI interfaces together"); // 1. Initialize platform let hal = ElasticTeeHal::new()?; - println!("\n[1/4] ✓ Platform initialized: {:?}", hal.platform_type()); + log::info!("\n[1/4] ✓ Platform initialized: {:?}", hal.platform_type()); // 2. Test Clock let clock = ClockInterface::new(); let time_start = clock.read_current_time()?; - println!( + log::info!( "[2/4] ✓ Clock interface working (time: {})", time_start.seconds ); @@ -237,7 +253,7 @@ async fn test_tdx_all_interfaces_integration() -> HalResult<()> { // 3. Test Random let random = RandomInterface::new(); let random_key = random.generate_key_material(32)?; - println!( + log::info!( "[3/4] ✓ Random interface working (generated {} byte key)", random_key.len() ); @@ -251,29 +267,29 @@ async fn test_tdx_all_interfaces_integration() -> HalResult<()> { .await?; let retrieved_key = storage.read_object(container, "random_key").await?; assert_eq!(random_key, retrieved_key); - println!("[4/4] ✓ Storage interface working (stored and retrieved data)"); + log::info!("[4/4] ✓ Storage interface working (stored and retrieved data)"); // 5. Verify time elapsed let time_end = clock.read_current_time()?; let elapsed = time_end.seconds - time_start.seconds; - println!("\n✓ Integration test completed in {} seconds", elapsed); + log::info!("\n✓ Integration test completed in {} seconds", elapsed); // 6. Generate final attestation with report data let report_data = b"integration_test_completed"; let attestation = hal.attest(report_data).await?; - println!("✓ Final attestation generated: {} bytes", attestation.len()); - println!( + log::info!("✓ Final attestation generated: {} bytes", attestation.len()); + log::debug!( " - Report data: {:?}", String::from_utf8_lossy(report_data) ); - println!("\n=== ALL TESTS PASSED ==="); - println!("Intel TDX environment fully functional with:"); - println!(" ✓ Platform detection and attestation"); - println!(" ✓ Clock interface (WASI-compatible)"); - println!(" ✓ Random interface (RDRAND/RDSEED)"); - println!(" ✓ Storage interface (encrypted)"); - println!(" ✓ Network interface (isolated)"); + log::info!("\n=== ALL TESTS PASSED ==="); + log::info!("Intel TDX environment fully functional with:"); + log::info!(" ✓ Platform detection and attestation"); + log::info!(" ✓ Clock interface (WASI-compatible)"); + log::info!(" ✓ Random interface (RDRAND/RDSEED)"); + log::info!(" ✓ Storage interface (encrypted)"); + log::info!(" ✓ Network interface (isolated)"); Ok(()) } @@ -285,26 +301,27 @@ async fn test_tdx_all_interfaces_integration() -> HalResult<()> { #[tokio::test] #[ignore = "requires Intel TDX hardware (/dev/tdx_guest) and ITA_API_KEY"] async fn test_ita_attestation_roundtrip() -> HalResult<()> { - println!("\n=== INTEL TRUST AUTHORITY END-TO-END TEST ==="); + init(); + log::info!("\n=== INTEL TRUST AUTHORITY END-TO-END TEST ==="); // Verify ITA key is present let api_key = std::env::var("ITA_API_KEY") .expect("ITA_API_KEY environment variable must be set to run this test"); - println!("✓ ITA_API_KEY loaded ({} chars)", api_key.len()); + log::info!("✓ ITA_API_KEY loaded ({} chars)", api_key.len()); // 1. Initialise HAL (auto-detects TDX) let hal = ElasticTeeHal::new()?; - println!("✓ HAL initialised on {:?}", hal.platform_type()); + log::info!("✓ HAL initialised on {:?}", hal.platform_type()); // 2. Generate a 32-byte random nonce as report-data let random = elastic_tee_hal::RandomInterface::new(); let nonce = random.generate_nonce(32)?; - println!("✓ Generated 32-byte nonce: {}", hex::encode(&nonce)); + log::debug!("✓ Generated 32-byte nonce: {}", hex::encode(&nonce)); // 3. Get TDX quote from hardware + submit to ITA via the dedicated // server-side API. (hal.attest() always returns measurements JSON; // the EAR JWT is only produced by attest_with_ita().) - println!("\n→ Calling hal.attest_with_ita() with nonce..."); + log::info!("\n→ Calling hal.attest_with_ita() with nonce..."); let ear_jwt = hal.attest_with_ita(&nonce).await?; let result = ear_jwt.into_bytes(); @@ -313,28 +330,28 @@ async fn test_ita_attestation_roundtrip() -> HalResult<()> { if result_str.starts_with("ey") { // Looks like a JWT (base64url always starts with "ey" for {"alg":...}) - println!("\n✓ ITA returned EAR JWT token!"); + log::info!("\n✓ ITA returned EAR JWT token!"); let parts: Vec<&str> = result_str.splitn(3, '.').collect(); - println!(" - Header : {}", parts.get(0).unwrap_or(&"")); - println!( + log::debug!(" - Header : {}", parts.get(0).unwrap_or(&"")); + log::debug!( " - Payload : {} chars (truncated)", parts.get(1).map(|s| s.len()).unwrap_or(0) ); - println!(" - Full token length: {} bytes", result.len()); - println!("\n Next step: send this EAR to your KBS to release the decryption key."); + log::debug!(" - Full token length: {} bytes", result.len()); + log::info!("\n Next step: send this EAR to your KBS to release the decryption key."); } else if result_str.starts_with("attestation-error:") { panic!("Attestation failed: {}", result_str); } else { // Raw quote returned (ITA submission failed but quote was generated) - println!("\n⚠ Raw TDX quote returned ({} bytes)", result.len()); - println!(" ITA submission may have failed. Check logs above for details."); - println!( + log::warn!("\n⚠ Raw TDX quote returned ({} bytes)", result.len()); + log::info!(" ITA submission may have failed. Check logs above for details."); + log::debug!( " Quote prefix (hex): {}", hex::encode(&result[..result.len().min(32)]) ); panic!("Expected EAR JWT but got raw quote. Check ITA_API_KEY and network connectivity."); } - println!("\n=== ITA ROUND-TRIP COMPLETE ==="); + log::info!("\n=== ITA ROUND-TRIP COMPLETE ==="); Ok(()) }