Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions example-attestation-guest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ impl bindings::exports::elastic::hal::run::Guest for Component {
fn run() -> Vec<u8> {
// 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) {
Expand Down
21 changes: 13 additions & 8 deletions examples/basic_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,50 @@ 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()
);

// 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(())
}
92 changes: 48 additions & 44 deletions examples/enforcement_demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@ use elastic_tee_hal::enforcement::policy::{Quota, RateLimit};
use elastic_tee_hal::enforcement::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
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();

Expand All @@ -31,7 +35,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.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");
Expand All @@ -51,7 +55,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
);

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");
Expand All @@ -62,111 +66,111 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.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");
let umbrella_policy =
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),
}
}

// Test crypto (should work)
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;
Expand All @@ -180,58 +184,58 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}

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");
}
}

// ========================================================================
// 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(())
}
Loading