diff --git a/apps/maple-agent/crates/maple-agent/src/agent/provider.rs b/apps/maple-agent/crates/maple-agent/src/agent/provider.rs index 3b7da749f..1385227ca 100644 --- a/apps/maple-agent/crates/maple-agent/src/agent/provider.rs +++ b/apps/maple-agent/crates/maple-agent/src/agent/provider.rs @@ -924,7 +924,6 @@ fn opensecret_error_kind_message(error: maple_sdk::Error) -> String { ATTESTATION_VERIFICATION_ERROR_MESSAGE.to_string() } maple_sdk::Error::Session(_) - | maple_sdk::Error::KeyExchange(_) | maple_sdk::Error::Encryption(_) | maple_sdk::Error::Decryption(_) | maple_sdk::Error::InvalidResponse(_) @@ -1067,7 +1066,6 @@ pub(crate) fn opensecret_error_category(error: &maple_sdk::Error) -> &'static st maple_sdk::Error::Crypto(_) => "crypto", maple_sdk::Error::AttestationVerificationFailed(_) => "attestation", maple_sdk::Error::Session(_) => "session", - maple_sdk::Error::KeyExchange(_) => "key_exchange", maple_sdk::Error::Encryption(_) => "encryption", maple_sdk::Error::Decryption(_) => "decryption", maple_sdk::Error::Authentication(_) => "authentication", diff --git a/apps/maple-research/frontend/src-tauri/src/native_oauth.rs b/apps/maple-research/frontend/src-tauri/src/native_oauth.rs index 29852df47..174fee75f 100644 --- a/apps/maple-research/frontend/src-tauri/src/native_oauth.rs +++ b/apps/maple-research/frontend/src-tauri/src/native_oauth.rs @@ -230,7 +230,6 @@ fn map_sdk_error(action: &'static str, error: &maple_sdk::Error) -> String { maple_sdk::Error::Crypto(_) => "crypto", maple_sdk::Error::AttestationVerificationFailed(_) => "attestation", maple_sdk::Error::Session(_) => "session", - maple_sdk::Error::KeyExchange(_) => "key_exchange", maple_sdk::Error::Encryption(_) => "encryption", maple_sdk::Error::Decryption(_) => "decryption", maple_sdk::Error::Authentication(_) => "authentication", diff --git a/scripts/ci/build-sdk-publish.sh b/scripts/ci/build-sdk-publish.sh index 342b11ec3..b3beb64db 100755 --- a/scripts/ci/build-sdk-publish.sh +++ b/scripts/ci/build-sdk-publish.sh @@ -78,7 +78,6 @@ nix develop --no-update-lock-file ./sdk -c bash -euo pipefail -c ' src/lib/test/*.test.ts \ src/lib/test/integration/attestation.test.ts \ src/lib/test/integration/developerHook.test.ts \ - src/lib/test/integration/liveAttestation.test.ts \ src/lib/test/integration/pcr.test.ts \ src/lib/test/integration/platformPushSettings.test.ts \ src/lib/test/integration/web.test.ts \ diff --git a/sdk/bun.lock b/sdk/bun.lock index 5b6eead38..ae096b643 100644 --- a/sdk/bun.lock +++ b/sdk/bun.lock @@ -8,7 +8,6 @@ "@peculiar/x509": "1.14.3", "@stablelib/base64": "2.0.1", "@stablelib/chacha20poly1305": "2.0.1", - "@stablelib/random": "2.0.1", "cbor2": "1.12.0", "openai": "6.0.0", "tweetnacl": "1.0.3", @@ -287,8 +286,6 @@ "@stablelib/poly1305": ["@stablelib/poly1305@2.0.1", "", { "dependencies": { "@stablelib/constant-time": "^2.0.1", "@stablelib/wipe": "^2.0.1" } }, "sha512-D8xfZcL/5zeVARJ9I2fZOUCnZvsJx8G4JDQvD+ecsnaCildPtqZDwqqjtOc4cfHAdScrMjOzUVsssjXUTBw3YQ=="], - "@stablelib/random": ["@stablelib/random@2.0.1", "", { "dependencies": { "@stablelib/binary": "^2.0.1", "@stablelib/wipe": "^2.0.1" } }, "sha512-W6GAtXEEs7r+dSbuBsvoFmlyL3gLxle41tQkjKu17dDWtDdjhVUbtRfRCQcCUeczwkgjQxMPopgwYEvxXtHXGw=="], - "@stablelib/wipe": ["@stablelib/wipe@2.0.1", "", {}, "sha512-1eU2K9EgOcV4qc9jcP6G72xxZxEm5PfeI5H55l08W95b4oRJaqhmlWRc4xZAm6IVSKhVNxMi66V67hCzzuMTAg=="], "@types/argparse": ["@types/argparse@1.0.38", "", {}, "sha512-ebDJ9b0e702Yr7pWgB0jzm+CX4Srzz8RcXtLJDJB+BSccqMa36uyH/zUsSYao5+BD1ytv3k3rPYCq4mAE1hsXA=="], diff --git a/sdk/package.json b/sdk/package.json index b792e73b8..a4e0803b4 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -46,7 +46,6 @@ "@peculiar/x509": "1.14.3", "@stablelib/base64": "2.0.1", "@stablelib/chacha20poly1305": "2.0.1", - "@stablelib/random": "2.0.1", "cbor2": "1.12.0", "openai": "6.0.0", "tweetnacl": "1.0.3", diff --git a/sdk/rust/src/crypto.rs b/sdk/rust/src/crypto.rs index 95cd67f7c..ab97ae795 100644 --- a/sdk/rust/src/crypto.rs +++ b/sdk/rust/src/crypto.rs @@ -1,11 +1,5 @@ -use crate::error::{Error, Result}; -use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; -use chacha20poly1305::{ - aead::{Aead, KeyInit, Nonce}, - ChaCha20Poly1305, -}; use rand_core::{OsRng, RngCore}; -use x25519_dalek::{EphemeralSecret, PublicKey as X25519PublicKey, SharedSecret, StaticSecret}; +use x25519_dalek::{PublicKey as X25519PublicKey, SharedSecret, StaticSecret}; // Re-export for tests pub use x25519_dalek::PublicKey; @@ -26,132 +20,23 @@ pub fn derive_shared_secret(secret: &StaticSecret, their_public: &X25519PublicKe secret.diffie_hellman(their_public) } -pub fn encrypt_message(plaintext: &[u8], key: &[u8; 32]) -> Result> { - encrypt_data(key, plaintext) -} - -pub fn decrypt_message(ciphertext: &[u8], key: &[u8; 32]) -> Result> { - decrypt_data(key, ciphertext) -} - pub fn generate_random_bytes() -> [u8; N] { let mut bytes = [0u8; N]; OsRng.fill_bytes(&mut bytes); bytes } -pub fn generate_ephemeral_keypair() -> (EphemeralSecret, PublicKey) { - let secret = EphemeralSecret::random_from_rng(OsRng); - let public = PublicKey::from(&secret); - (secret, public) -} - -pub fn generate_static_keypair() -> (StaticSecret, PublicKey) { - let secret = StaticSecret::random_from_rng(OsRng); - let public = PublicKey::from(&secret); - (secret, public) -} - -pub fn perform_key_exchange(secret: EphemeralSecret, their_public: &PublicKey) -> SharedSecret { - secret.diffie_hellman(their_public) -} - -pub fn perform_static_key_exchange( - secret: &StaticSecret, - their_public: &PublicKey, -) -> SharedSecret { - secret.diffie_hellman(their_public) -} - -#[allow(deprecated)] -pub fn encrypt_data(key: &[u8; 32], plaintext: &[u8]) -> Result> { - let cipher = ChaCha20Poly1305::new_from_slice(key) - .map_err(|e| Error::Crypto(format!("Failed to create cipher: {}", e)))?; - - let nonce_bytes = generate_random_bytes::<12>(); - let nonce = Nonce::::from_slice(&nonce_bytes); - - let ciphertext = cipher - .encrypt(nonce, plaintext) - .map_err(|e| Error::Encryption(format!("Encryption failed: {}", e)))?; - - // Prepend nonce to ciphertext - let mut result = Vec::with_capacity(12 + ciphertext.len()); - result.extend_from_slice(&nonce_bytes); - result.extend_from_slice(&ciphertext); - - Ok(result) -} - -#[allow(deprecated)] -pub fn decrypt_data(key: &[u8; 32], encrypted_data: &[u8]) -> Result> { - if encrypted_data.len() < 12 { - return Err(Error::Decryption("Encrypted data too short".to_string())); - } - - let (nonce_bytes, ciphertext) = encrypted_data.split_at(12); - let nonce = Nonce::::from_slice(nonce_bytes); - - let cipher = ChaCha20Poly1305::new_from_slice(key) - .map_err(|e| Error::Crypto(format!("Failed to create cipher: {}", e)))?; - - cipher - .decrypt(nonce, ciphertext) - .map_err(|e| Error::Decryption(format!("Decryption failed: {}", e))) -} - -#[allow(deprecated)] -pub fn decrypt_session_key(shared_secret: &SharedSecret, encrypted_data: &str) -> Result<[u8; 32]> { - let encrypted = BASE64.decode(encrypted_data)?; - - if encrypted.len() < 12 { - return Err(Error::Decryption( - "Encrypted session key too short".to_string(), - )); - } - - let (nonce_bytes, ciphertext) = encrypted.split_at(12); - let nonce = Nonce::::from_slice(nonce_bytes); - - let cipher = ChaCha20Poly1305::new_from_slice(shared_secret.as_bytes()) - .map_err(|e| Error::Crypto(format!("Failed to create cipher: {}", e)))?; - - let session_key_vec = cipher - .decrypt(nonce, ciphertext) - .map_err(|e| Error::Decryption(format!("Failed to decrypt session key: {}", e)))?; - - if session_key_vec.len() != 32 { - return Err(Error::Decryption("Invalid session key length".to_string())); - } - - let mut session_key = [0u8; 32]; - session_key.copy_from_slice(&session_key_vec); - Ok(session_key) -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn test_encrypt_decrypt() { - let key = generate_random_bytes::<32>(); - let plaintext = b"Hello, World!"; - - let encrypted = encrypt_data(&key, plaintext).unwrap(); - let decrypted = decrypt_data(&key, &encrypted).unwrap(); - - assert_eq!(plaintext.to_vec(), decrypted); - } - #[test] fn test_key_exchange() { - // Use static secrets for testing since ephemeral secrets are consumed - let (alice_secret, alice_public) = generate_static_keypair(); - let (bob_secret, bob_public) = generate_static_keypair(); + let alice = generate_key_pair(); + let bob = generate_key_pair(); - let alice_shared = perform_static_key_exchange(&alice_secret, &bob_public); - let bob_shared = perform_static_key_exchange(&bob_secret, &alice_public); + let alice_shared = derive_shared_secret(&alice.secret, &bob.public); + let bob_shared = derive_shared_secret(&bob.secret, &alice.public); assert_eq!(alice_shared.as_bytes(), bob_shared.as_bytes()); } diff --git a/sdk/rust/src/error.rs b/sdk/rust/src/error.rs index f13791aa4..a998b5e42 100644 --- a/sdk/rust/src/error.rs +++ b/sdk/rust/src/error.rs @@ -20,9 +20,6 @@ pub enum Error { #[error("Session error: {0}")] Session(String), - #[error("Key exchange failed: {0}")] - KeyExchange(String), - #[error("Encryption error: {0}")] Encryption(String), diff --git a/sdk/rust/src/session.rs b/sdk/rust/src/session.rs index e8a7b9bf8..d74dfc586 100644 --- a/sdk/rust/src/session.rs +++ b/sdk/rust/src/session.rs @@ -1,7 +1,6 @@ use crate::error::{Error, Result}; -use crate::types::{SessionState, TokenPair}; +use crate::types::TokenPair; use std::sync::{Arc, RwLock}; -use uuid::Uuid; use zeroize::Zeroizing; #[derive(Debug, Clone)] @@ -36,21 +35,18 @@ struct CredentialState { } pub struct SessionManager { - session: Arc>>, credentials: Arc>, } impl SessionManager { pub fn new() -> Self { Self { - session: Arc::new(RwLock::new(None)), credentials: Arc::new(RwLock::new(CredentialState::default())), } } pub fn new_with_api_key(api_key: String) -> Self { Self { - session: Arc::new(RwLock::new(None)), credentials: Arc::new(RwLock::new(CredentialState { api_key: Some(api_key), generation: 1, @@ -90,39 +86,6 @@ impl SessionManager { Ok(()) } - pub fn set_session(&self, session_id: Uuid, session_key: [u8; 32]) -> Result<()> { - let mut session_guard = self - .session - .write() - .map_err(|e| Error::Session(format!("Failed to acquire session write lock: {}", e)))?; - - *session_guard = Some(SessionState { - session_id, - session_key, - }); - - Ok(()) - } - - pub fn get_session(&self) -> Result> { - let session_guard = self - .session - .read() - .map_err(|e| Error::Session(format!("Failed to acquire session read lock: {}", e)))?; - - Ok(session_guard.clone()) - } - - pub fn clear_session(&self) -> Result<()> { - let mut session_guard = self - .session - .write() - .map_err(|e| Error::Session(format!("Failed to acquire session write lock: {}", e)))?; - - *session_guard = None; - Ok(()) - } - pub fn set_tokens(&self, access_token: String, refresh_token: Option) -> Result<()> { let mut credentials = self.credentials.write().map_err(|e| { Error::Authentication(format!("Failed to acquire credentials write lock: {}", e)) @@ -368,7 +331,6 @@ impl SessionManager { } pub fn clear_all(&self) -> Result<()> { - self.clear_session()?; let mut credentials = self.credentials.write().map_err(|e| { Error::Authentication(format!("Failed to acquire credentials write lock: {}", e)) })?; @@ -389,7 +351,6 @@ impl SessionManager { return Ok(false); } - self.clear_session()?; credentials.tokens = None; credentials.api_key = None; credentials.generation = credentials.generation.wrapping_add(1); @@ -409,28 +370,6 @@ impl Default for SessionManager { mod tests { use super::*; - #[test] - fn test_session_management() { - let manager = SessionManager::new(); - - // Initially empty - assert!(manager.get_session().unwrap().is_none()); - - // Set session - let session_id = Uuid::new_v4(); - let session_key = [0u8; 32]; - manager.set_session(session_id, session_key).unwrap(); - - // Retrieve session - let session = manager.get_session().unwrap().unwrap(); - assert_eq!(session.session_id, session_id); - assert_eq!(session.session_key, session_key); - - // Clear session - manager.clear_session().unwrap(); - assert!(manager.get_session().unwrap().is_none()); - } - #[test] fn test_token_management() { let manager = SessionManager::new(); diff --git a/sdk/rust/src/transport_v2/client.rs b/sdk/rust/src/transport_v2/client.rs index 2ee09b695..30309a4f2 100644 --- a/sdk/rust/src/transport_v2/client.rs +++ b/sdk/rust/src/transport_v2/client.rs @@ -212,8 +212,7 @@ impl TransportV2Client { }) } - /// Send exactly one encrypted request. This method never retries or falls - /// back to transport v1. + /// Send exactly one encrypted request. This method never retries. #[cfg(test)] pub(crate) async fn send( &self, diff --git a/sdk/rust/src/transport_v2/mod.rs b/sdk/rust/src/transport_v2/mod.rs index ff552e647..f136cdf28 100644 --- a/sdk/rust/src/transport_v2/mod.rs +++ b/sdk/rust/src/transport_v2/mod.rs @@ -1,7 +1,7 @@ -//! Private, dormant client engine for the second attested transport. +//! Private client engine for Transport V2, the SDK's only attested transport. //! -//! This module owns only the wire protocol. The existing public SDK remains on -//! transport v1 until a later stack layer deliberately adapts it to this API. +//! This module owns only the wire protocol. `OpenSecretClient` adapts the +//! public SDK API to it. pub(crate) mod client; mod crypto; diff --git a/sdk/rust/src/types.rs b/sdk/rust/src/types.rs index 8b9b3fefd..3b3cbeda2 100644 --- a/sdk/rust/src/types.rs +++ b/sdk/rust/src/types.rs @@ -3,7 +3,8 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; use uuid::Uuid; -// Attestation & Key Exchange Types +// Public attestation document types (`GET /attestation/{nonce}`). The client's +// own sessions use Transport V2 and do not fetch this document. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AttestationRequest { pub nonce: String, @@ -14,29 +15,6 @@ pub struct AttestationResponse { pub attestation_document: String, } -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct KeyExchangeRequest { - pub client_public_key: String, - pub nonce: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct KeyExchangeResponse { - pub encrypted_session_key: String, - pub session_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EncryptedRequest { - pub encrypted: String, // Base64-encoded (nonce + ciphertext) -} - -#[derive(Debug, Clone)] -pub struct SessionState { - pub session_id: Uuid, - pub session_key: [u8; 32], -} - // Token Management Types #[derive(Debug, Clone)] pub struct TokenPair { @@ -99,13 +77,6 @@ pub struct LogoutRequest { pub push_device_id: Option, } -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EncryptedResponse { - pub encrypted: String, - #[serde(skip)] - _phantom: std::marker::PhantomData, -} - #[derive(Debug, Clone, PartialEq, Eq, Default)] pub enum NullableField { #[default] diff --git a/sdk/rust/tests/crypto.rs b/sdk/rust/tests/crypto.rs index c56acb3f3..cf0cbf805 100644 --- a/sdk/rust/tests/crypto.rs +++ b/sdk/rust/tests/crypto.rs @@ -1,8 +1,4 @@ -use base64::Engine; -use maple_sdk::crypto::{ - decrypt_message, decrypt_session_key, derive_shared_secret, encrypt_message, generate_key_pair, -}; -use maple_sdk::Result; +use maple_sdk::crypto::{derive_shared_secret, generate_key_pair}; #[test] fn test_key_generation() { @@ -33,113 +29,3 @@ fn test_ecdh_key_exchange() { // Shared secret should be 32 bytes assert_eq!(alice_shared.as_bytes().len(), 32); } - -#[test] -fn test_encryption_decryption() -> Result<()> { - let key = [42u8; 32]; // Test key - let plaintext = b"Hello, OpenSecret!"; - - // Encrypt - let ciphertext = encrypt_message(plaintext, &key)?; - - // Ciphertext should be different from plaintext - assert_ne!(&ciphertext[..], plaintext); - - // Ciphertext should be longer (includes nonce and tag) - assert!(ciphertext.len() > plaintext.len()); - - // Decrypt - let decrypted = decrypt_message(&ciphertext, &key)?; - - // Should recover original plaintext - assert_eq!(decrypted, plaintext); - - Ok(()) -} - -#[test] -fn test_encryption_with_different_nonces() -> Result<()> { - let key = [42u8; 32]; - let plaintext = b"Test message"; - - // Encrypt the same message twice - let ciphertext1 = encrypt_message(plaintext, &key)?; - let ciphertext2 = encrypt_message(plaintext, &key)?; - - // Ciphertexts should be different (different nonces) - assert_ne!(ciphertext1, ciphertext2); - - // But both should decrypt to the same plaintext - let decrypted1 = decrypt_message(&ciphertext1, &key)?; - let decrypted2 = decrypt_message(&ciphertext2, &key)?; - - assert_eq!(decrypted1, plaintext); - assert_eq!(decrypted2, plaintext); - - Ok(()) -} - -#[test] -fn test_decryption_with_wrong_key_fails() { - let key1 = [1u8; 32]; - let key2 = [2u8; 32]; - let plaintext = b"Secret message"; - - // Encrypt with key1 - let ciphertext = encrypt_message(plaintext, &key1).unwrap(); - - // Try to decrypt with key2 - should fail - let result = decrypt_message(&ciphertext, &key2); - - assert!(result.is_err()); -} - -#[test] -fn test_session_key_decryption() -> Result<()> { - // Simulate server and client key exchange - let client_keypair = generate_key_pair(); - let server_keypair = generate_key_pair(); - - // Derive shared secret (what the server would do) - let shared_secret = derive_shared_secret(&server_keypair.secret, &client_keypair.public); - - // Server creates a session key - let session_key = [99u8; 32]; - - // Server encrypts the session key with the shared secret - let encrypted_session_key = encrypt_message(&session_key, shared_secret.as_bytes())?; - let encrypted_b64 = base64::engine::general_purpose::STANDARD.encode(&encrypted_session_key); - - // Client decrypts the session key - let decrypted_key = decrypt_session_key(&shared_secret, &encrypted_b64)?; - - assert_eq!(decrypted_key, session_key); - - Ok(()) -} - -#[test] -fn test_invalid_base64_session_key() { - let shared_secret = - derive_shared_secret(&generate_key_pair().secret, &generate_key_pair().public); - - let result = decrypt_session_key(&shared_secret, "not-valid-base64!"); - assert!(result.is_err()); -} - -#[test] -fn test_corrupted_ciphertext() { - let key = [42u8; 32]; - let plaintext = b"Test"; - - let mut ciphertext = encrypt_message(plaintext, &key).unwrap(); - - // Corrupt the ciphertext - if let Some(byte) = ciphertext.last_mut() { - *byte = byte.wrapping_add(1); - } - - // Decryption should fail - let result = decrypt_message(&ciphertext, &key); - assert!(result.is_err()); -} diff --git a/sdk/src/global.d.ts b/sdk/src/global.d.ts index ca0ba615c..87959024f 100644 --- a/sdk/src/global.d.ts +++ b/sdk/src/global.d.ts @@ -3,12 +3,3 @@ declare module "*.der" { const content: Uint8Array; export default content; } - -interface ImportMetaEnv { - readonly VITE_TEST_NACL_PUBLIC_KEY?: string; - readonly VITE_TEST_NACL_SECRET_KEY?: string; -} - -interface ImportMeta { - readonly env: ImportMetaEnv; -} diff --git a/sdk/src/lib/api.ts b/sdk/src/lib/api.ts index 9c95ceea8..450bedea3 100644 --- a/sdk/src/lib/api.ts +++ b/sdk/src/lib/api.ts @@ -242,6 +242,9 @@ export async function requestNewVerificationCode(): Promise { ); } +// Fetches the public attestation document (`GET /attestation/{nonce}`). The +// SDK's own sessions use Transport V2 instead; `verifyAttestation` is the +// caller, for checks that verify an enclave without opening a session. export async function fetchAttestationDocument( nonce: string, explicitApiUrl?: string @@ -255,27 +258,6 @@ export async function fetchAttestationDocument( return data.attestation_document; } -export async function keyExchange( - clientPublicKey: string, - nonce: string, - explicitApiUrl?: string -): Promise<{ encrypted_session_key: string; session_id: string }> { - const url = explicitApiUrl || apiUrl; - const response = await fetch(`${url}/key_exchange`, { - method: "POST", - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify({ client_public_key: clientPublicKey, nonce }) - }); - - if (!response.ok) { - throw new Error("Key exchange failed"); - } - - return response.json(); -} - export async function requestPasswordReset( email: string, hashedSecret: string, diff --git a/sdk/src/lib/attestation.ts b/sdk/src/lib/attestation.ts index 00729a126..7670bd5d9 100644 --- a/sdk/src/lib/attestation.ts +++ b/sdk/src/lib/attestation.ts @@ -25,6 +25,14 @@ const AttestationDocumentSchema = z.object({ export type AttestationDocument = z.infer; +// Result shape of the providers' `getAttestation`. Transport V2 never exposes a +// traffic key, so `sessionKey` is always null; the field stays for consumers +// typed against the published context. +export interface Attestation { + sessionKey: Uint8Array | null; + sessionId: string | null; +} + const ParsedAttestationDocumentSchema = z.object({ protected: z.instanceof(Uint8Array), // There's an "unprotected" header in the CBOR, but we never use it @@ -319,6 +327,9 @@ async function fakeAuthenticate( return zodParsed; } +// Fetches and verifies the public attestation document for `nonce`. Nothing in +// the SDK's Transport V2 path calls this: it stays for deployment checks that +// import this module directly to verify an enclave without opening a session. export async function verifyAttestation( nonce: string, explicitApiUrl?: string diff --git a/sdk/src/lib/developer.tsx b/sdk/src/lib/developer.tsx index cff3c8900..565921fdb 100644 --- a/sdk/src/lib/developer.tsx +++ b/sdk/src/lib/developer.tsx @@ -8,7 +8,7 @@ import { EXPECTED_ROOT_CERT_HASH, ParsedAttestationView } from "./attestationForView"; -import type { AttestationDocument } from "./attestation"; +import type { Attestation, AttestationDocument } from "./attestation"; import { PcrConfig } from "./pcr"; import { clearTransportV2CredentialsIfCurrent, @@ -17,7 +17,6 @@ import { subscribeTransportV2AuthInvalidation, transportV2ProfilePublicationDecision } from "./transportV2/auth"; -import type { Attestation } from "./getAttestation"; import { getTransportV2PublicAttestation, transportV2Runtime } from "./transportV2/runtime"; import { snapshotTransportV2AuthorityScope, diff --git a/sdk/src/lib/encryption.ts b/sdk/src/lib/encryption.ts deleted file mode 100644 index a8b9685b2..000000000 --- a/sdk/src/lib/encryption.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { ChaCha20Poly1305 } from "@stablelib/chacha20poly1305"; -import { randomBytes } from "@stablelib/random"; -import { encode, decode } from "@stablelib/base64"; - -export function encryptMessage(sessionKey: Uint8Array, message: string): string { - const chacha = new ChaCha20Poly1305(sessionKey); - const nonce = randomBytes(12); - const encoder = new TextEncoder(); - const data = encoder.encode(message); - const encrypted = chacha.seal(nonce, data); - - // Prepend the nonce to the encrypted data - const result = new Uint8Array(nonce.length + encrypted.length); - result.set(nonce); - result.set(encrypted, nonce.length); - - return encode(result); -} - -export function decryptMessage(sessionKey: Uint8Array, encryptedData: string): string { - const chacha = new ChaCha20Poly1305(sessionKey); - const encryptedBytes = decode(encryptedData); - - // Extract nonce (first 12 bytes) and ciphertext - const nonceLength = 12; - const nonce = encryptedBytes.slice(0, nonceLength); - const ciphertext = encryptedBytes.slice(nonceLength); - - const decrypted = chacha.open(nonce, ciphertext); - if (!decrypted) { - throw new Error("Decryption failed"); - } - return new TextDecoder().decode(decrypted); -} diff --git a/sdk/src/lib/getAttestation.ts b/sdk/src/lib/getAttestation.ts deleted file mode 100644 index 2b57336e1..000000000 --- a/sdk/src/lib/getAttestation.ts +++ /dev/null @@ -1,361 +0,0 @@ -import { verifyAttestation, isLocalDevelopmentApiUrl } from "./attestation"; -import type { AttestationDocument } from "./attestation"; -import { getApiUrl, keyExchange } from "./api"; -import nacl from "tweetnacl"; -import { ChaCha20Poly1305 } from "@stablelib/chacha20poly1305"; -import { encode, decode } from "@stablelib/base64"; -import { - requireTrustedPcr0, - serializePcrConfig, - snapshotPcrConfig, - validatePcr0Hash, - type PcrConfig -} from "./pcr"; - -export interface Attestation { - sessionKey: Uint8Array | null; - sessionId: string | null; -} - -type NaclKeyPair = { publicKey: Uint8Array; secretKey: Uint8Array }; - -type CachedAttestationSession = { - version: 1; - apiUrl: string; - policyFingerprint: string; - sessionKey: string; - sessionId: string; - verifiedPcr0: string | "local-development"; -}; - -const SESSION_CACHE_PREFIX = "opensecret:attested-session:v1:"; -const LEGACY_SESSION_KEYS = ["sessionKey", "sessionId"]; -const SESSION_KEY_LENGTH = 32; -const SESSION_ID_MAX_LENGTH = 512; -const SESSION_CACHE_MAX_LENGTH = 4096; -const PCR0_PATTERN = /^[0-9a-f]{96}$/; -const SESSION_ID_PATTERN = /^[\x21-\x7e]+$/; - -/** @internal Exported for deterministic handshake tests, not from the package entry point. */ -export interface GetAttestationDependencies { - verifyAttestation: typeof verifyAttestation; - validatePcr0Hash: typeof validatePcr0Hash; - keyExchange: typeof keyExchange; - generateNaclKeyPair: () => NaclKeyPair; - decryptSessionKey: ( - encryptedSessionKey: string, - clientSecretKey: Uint8Array, - serverPublicKey: Uint8Array - ) => Uint8Array | null; - randomUUID: () => string; -} - -function generateNaclKeyPair(): NaclKeyPair { - const testNaclPublicKey = import.meta.env.VITE_TEST_NACL_PUBLIC_KEY; - const testNaclSecretKey = import.meta.env.VITE_TEST_NACL_SECRET_KEY; - - if (testNaclPublicKey && testNaclSecretKey) { - return { - publicKey: decode(testNaclPublicKey), - secretKey: decode(testNaclSecretKey) - }; - } - - return nacl.box.keyPair(); -} - -function decryptSessionKey( - encryptedSessionKey: string, - clientSecretKey: Uint8Array, - serverPublicKey: Uint8Array -): Uint8Array | null { - const sharedSecret = nacl.scalarMult(clientSecretKey, serverPublicKey); - const encryptedData = decode(encryptedSessionKey); - const nonceLength = 12; - const decryptionNonce = encryptedData.slice(0, nonceLength); - const ciphertext = encryptedData.slice(nonceLength); - return new ChaCha20Poly1305(sharedSecret).open(decryptionNonce, ciphertext); -} - -const defaultDependencies: GetAttestationDependencies = { - verifyAttestation, - validatePcr0Hash, - keyExchange, - generateNaclKeyPair, - decryptSessionKey, - randomUUID: () => window.crypto.randomUUID() -}; - -function canonicalizeApiUrl(apiUrl: string): string { - let url: URL; - try { - url = new URL(apiUrl); - } catch { - throw new Error("Attestation requires a valid API URL."); - } - - if (url.protocol !== "https:" && url.protocol !== "http:") { - throw new Error("Attestation API URL must use HTTP or HTTPS."); - } - if (url.username || url.password || url.search || url.hash) { - throw new Error("Attestation API URL must not contain credentials, a query, or a fragment."); - } - - const path = url.pathname === "/" ? "" : url.pathname.replace(/\/+$/, ""); - return `${url.origin}${path}`; -} - -async function sha256Hex(value: string): Promise { - const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)); - return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); -} - -async function getAttestationScope(apiUrl: string, pcrConfig?: PcrConfig) { - const canonicalApiUrl = canonicalizeApiUrl(apiUrl); - const policyFingerprint = await sha256Hex(serializePcrConfig(pcrConfig)); - const scopeFingerprint = await sha256Hex(`${canonicalApiUrl}\n${policyFingerprint}`); - return { - apiUrl: canonicalApiUrl, - policyFingerprint, - cacheKey: `${SESSION_CACHE_PREFIX}${scopeFingerprint}` - }; -} - -function getSessionStorage(): Storage | undefined { - try { - return globalThis.sessionStorage; - } catch { - return undefined; - } -} - -function removeStorageItem(key: string): void { - try { - getSessionStorage()?.removeItem(key); - } catch { - // Storage can be unavailable in sandboxed browser contexts. A fresh, - // verified in-memory session is still safe to use for the current request. - } -} - -function removeLegacySession(): void { - for (const key of LEGACY_SESSION_KEYS) removeStorageItem(key); -} - -function readCachedSession( - cacheKey: string, - apiUrl: string, - policyFingerprint: string, - localDevelopment: boolean -): Attestation | undefined { - let raw: string | null; - try { - raw = getSessionStorage()?.getItem(cacheKey) || null; - } catch { - return undefined; - } - if (!raw) return undefined; - - try { - if (raw.length > SESSION_CACHE_MAX_LENGTH) { - throw new Error("Cached attestation session is too large."); - } - const cached = JSON.parse(raw) as Partial; - const validPcrEvidence = localDevelopment - ? cached.verifiedPcr0 === "local-development" - : typeof cached.verifiedPcr0 === "string" && PCR0_PATTERN.test(cached.verifiedPcr0); - if ( - cached.version !== 1 || - cached.apiUrl !== apiUrl || - cached.policyFingerprint !== policyFingerprint || - typeof cached.sessionId !== "string" || - cached.sessionId.length === 0 || - cached.sessionId.length > SESSION_ID_MAX_LENGTH || - !SESSION_ID_PATTERN.test(cached.sessionId) || - typeof cached.sessionKey !== "string" || - !validPcrEvidence - ) { - throw new Error("Invalid cached attestation session."); - } - - const sessionKey = decode(cached.sessionKey); - if (sessionKey.length !== SESSION_KEY_LENGTH) { - throw new Error("Invalid cached attestation session key."); - } - return { sessionKey, sessionId: cached.sessionId }; - } catch { - removeStorageItem(cacheKey); - return undefined; - } -} - -function writeCachedSession(cacheKey: string, cached: CachedAttestationSession): void { - try { - getSessionStorage()?.setItem(cacheKey, JSON.stringify(cached)); - } catch { - // A storage failure must not turn a verified handshake into an unverified - // one. Continue with the verified in-memory session and simply skip reuse. - } -} - -/** @internal Exported for cache migration and integration tests. */ -export async function getAttestationSessionStorageKey( - apiUrl: string, - pcrConfig?: PcrConfig -): Promise { - return (await getAttestationScope(apiUrl, pcrConfig)).cacheKey; -} - -/** @internal Test helper; not exported from the package entry point. */ -export async function cacheAttestationSessionForTesting( - apiUrl: string, - pcrConfig: PcrConfig | undefined, - attestation: { sessionKey: Uint8Array; sessionId: string }, - verifiedPcr0: string -): Promise { - const scope = await getAttestationScope(apiUrl, pcrConfig); - writeCachedSession(scope.cacheKey, { - version: 1, - apiUrl: scope.apiUrl, - policyFingerprint: scope.policyFingerprint, - sessionKey: encode(attestation.sessionKey), - sessionId: attestation.sessionId, - verifiedPcr0 - }); -} - -/** Clears both vulnerable legacy entries and all policy-scoped SDK sessions. */ -export function clearAttestationSessions(): void { - removeLegacySession(); - const storage = getSessionStorage(); - if (!storage) return; - - const keys: string[] = []; - try { - for (let index = 0; index < storage.length; index += 1) { - const key = storage.key(index); - if (key && (key.startsWith(SESSION_CACHE_PREFIX) || LEGACY_SESSION_KEYS.includes(key))) { - keys.push(key); - } - } - } catch { - return; - } - for (const key of keys) removeStorageItem(key); -} - -export async function getAttestation( - forceRefresh?: boolean, - explicitApiUrl?: string, - pcrConfig?: PcrConfig -): Promise { - return getAttestationWithDependencies( - forceRefresh, - explicitApiUrl, - pcrConfig, - defaultDependencies - ); -} - -/** @internal Exported for deterministic handshake tests, not from the package entry point. */ -export async function getAttestationWithDependencies( - forceRefresh: boolean | undefined, - explicitApiUrl: string | undefined, - pcrConfig: PcrConfig | undefined, - dependencies: GetAttestationDependencies -): Promise { - removeLegacySession(); - - const configuredApiUrl = explicitApiUrl || getApiUrl(); - if (!configuredApiUrl) { - throw new Error("Attestation requires a configured API URL."); - } - - const policy = snapshotPcrConfig(pcrConfig); - const scope = await getAttestationScope(configuredApiUrl, policy); - const localDevelopment = isLocalDevelopmentApiUrl(scope.apiUrl); - - console.groupCollapsed("Attestation"); - try { - if (forceRefresh) { - removeStorageItem(scope.cacheKey); - } else { - const cached = readCachedSession( - scope.cacheKey, - scope.apiUrl, - scope.policyFingerprint, - localDevelopment - ); - if (cached) { - console.log("Using existing PCR-verified attestation from session storage."); - return cached; - } - } - - const attestationNonce = dependencies.randomUUID(); - console.log("Generated attestation nonce:", attestationNonce); - const document: AttestationDocument = await dependencies.verifyAttestation( - attestationNonce, - scope.apiUrl - ); - - if (!document.public_key) { - throw new Error("Invalid attestation document: missing enclave public key."); - } - - let verifiedPcr0: string | "local-development"; - if (localDevelopment) { - verifiedPcr0 = "local-development"; - console.warn("LOCAL DEVELOPMENT: PCR0 verification is bypassed for exact HTTP loopback."); - } else { - const trustedPcr = await requireTrustedPcr0( - document.pcrs, - policy, - dependencies.validatePcr0Hash - ); - verifiedPcr0 = trustedPcr.hash; - console.log("Attestation PCR0 trust verification succeeded."); - } - - const clientKeyPair = dependencies.generateNaclKeyPair(); - const { encrypted_session_key, session_id } = await dependencies.keyExchange( - encode(clientKeyPair.publicKey), - attestationNonce, - scope.apiUrl - ); - - if ( - typeof session_id !== "string" || - session_id.length === 0 || - session_id.length > SESSION_ID_MAX_LENGTH || - !SESSION_ID_PATTERN.test(session_id) - ) { - throw new Error("Key exchange returned an invalid session ID."); - } - - const decryptedSessionKey = dependencies.decryptSessionKey( - encrypted_session_key, - clientKeyPair.secretKey, - new Uint8Array(document.public_key) - ); - if (!decryptedSessionKey || decryptedSessionKey.length !== SESSION_KEY_LENGTH) { - throw new Error("Failed to decrypt a valid session key."); - } - - writeCachedSession(scope.cacheKey, { - version: 1, - apiUrl: scope.apiUrl, - policyFingerprint: scope.policyFingerprint, - sessionKey: encode(decryptedSessionKey), - sessionId: session_id, - verifiedPcr0 - }); - return { sessionKey: decryptedSessionKey, sessionId: session_id }; - } catch (error) { - removeStorageItem(scope.cacheKey); - console.error("Error verifying attestation:", error); - throw error; - } finally { - console.groupEnd(); - } -} diff --git a/sdk/src/lib/main.tsx b/sdk/src/lib/main.tsx index 7ae011fa7..ccdab6a87 100644 --- a/sdk/src/lib/main.tsx +++ b/sdk/src/lib/main.tsx @@ -11,7 +11,7 @@ import { EXPECTED_ROOT_CERT_HASH, ParsedAttestationView } from "./attestationForView"; -import type { AttestationDocument } from "./attestation"; +import type { Attestation, AttestationDocument } from "./attestation"; import type { LoginResponse, ThirdPartyTokenResponse, DocumentResponse } from "./api"; import { PcrConfig } from "./pcr"; import { @@ -20,7 +20,6 @@ import { subscribeTransportV2AuthInvalidation, transportV2ProfilePublicationDecision } from "./transportV2/auth"; -import type { Attestation } from "./getAttestation"; import { getTransportV2PublicAttestation, transportV2Runtime } from "./transportV2/runtime"; import { snapshotTransportV2AuthorityScope, diff --git a/sdk/src/lib/recovery.ts b/sdk/src/lib/recovery.ts deleted file mode 100644 index f17dfed27..000000000 --- a/sdk/src/lib/recovery.ts +++ /dev/null @@ -1,36 +0,0 @@ -export const ERROR_CONTRACT_HEADER = "x-opensecret-error-contract"; -export const ERROR_CODE_HEADER = "x-opensecret-error-code"; - -const ERROR_CONTRACT_VERSION = "1"; -const SESSION_NOT_FOUND_ERROR_CODE = "session_not_found"; -const ACCESS_TOKEN_EXPIRED_ERROR_CODE = "access_token_expired"; - -export type RecoveryAction = "renew_session" | "refresh_access_token"; - -/** - * Classify the only failures that are safe to replay before response handling. - * - * A missing contract marker means an older server, whose broad 400/401 - * behavior remains supported. Once a server advertises a contract, malformed, - * missing, future, or status-mismatched codes fail closed. - */ -export function classifyRecovery(status: number, headers: Headers): RecoveryAction | undefined { - const contractVersion = headers.get(ERROR_CONTRACT_HEADER); - - if (contractVersion === null) { - if (status === 400) return "renew_session"; - if (status === 401) return "refresh_access_token"; - return undefined; - } - - if (contractVersion !== ERROR_CONTRACT_VERSION) return undefined; - - const errorCode = headers.get(ERROR_CODE_HEADER); - if (status === 400 && errorCode === SESSION_NOT_FOUND_ERROR_CODE) { - return "renew_session"; - } - if (status === 401 && errorCode === ACCESS_TOKEN_EXPIRED_ERROR_CODE) { - return "refresh_access_token"; - } - return undefined; -} diff --git a/sdk/src/lib/test/getAttestationSecurity.test.ts b/sdk/src/lib/test/getAttestationSecurity.test.ts deleted file mode 100644 index 0d8ddaaa1..000000000 --- a/sdk/src/lib/test/getAttestationSecurity.test.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { beforeEach, describe, expect, mock, test } from "bun:test"; -import { encode } from "@stablelib/base64"; -import type { AttestationDocument } from "../attestation"; -import { - getAttestationSessionStorageKey, - getAttestationWithDependencies, - type GetAttestationDependencies -} from "../getAttestation"; -import type { PcrConfig } from "../pcr"; - -const REMOTE_API_URL = "https://enclave.example.test/api"; -const LOCAL_API_URL = "http://127.0.0.1:31110"; -const ATTESTATION_NONCE = "00000000-0000-4000-8000-000000000001"; -const TRUSTED_PCR0 = new Uint8Array(48).fill(0x2a); -const SESSION_KEY = new Uint8Array(32).fill(0x5a); -const PCR_CONFIG: PcrConfig = { - pcr0Values: [bytesToHex(TRUSTED_PCR0)], - remoteAttestation: false -}; - -function bytesToHex(bytes: Uint8Array): string { - return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); -} - -function attestationDocument(pcr0?: Uint8Array): AttestationDocument { - const pcrs = new Map(); - if (pcr0) pcrs.set(0, pcr0); - - return { - module_id: "test-enclave", - digest: "SHA384", - timestamp: Date.now(), - pcrs, - certificate: new Uint8Array([1]), - cabundle: [new Uint8Array([2])], - public_key: new Uint8Array(32).fill(0x19), - user_data: null, - nonce: new TextEncoder().encode(ATTESTATION_NONCE) - }; -} - -function dependencies( - overrides: Partial = {} -): GetAttestationDependencies { - return { - verifyAttestation: async () => attestationDocument(TRUSTED_PCR0), - validatePcr0Hash: async () => ({ - isMatch: true, - text: "PCR0 matches a test trust root" - }), - keyExchange: async () => ({ - encrypted_session_key: "test-encrypted-session-key", - session_id: "trusted-session" - }), - generateNaclKeyPair: () => ({ - publicKey: new Uint8Array(32).fill(0x11), - secretKey: new Uint8Array(32).fill(0x12) - }), - decryptSessionKey: () => SESSION_KEY, - randomUUID: () => ATTESTATION_NONCE, - ...overrides - }; -} - -async function establish( - deps: GetAttestationDependencies, - apiUrl = REMOTE_API_URL, - pcrConfig: PcrConfig | undefined = PCR_CONFIG -) { - return getAttestationWithDependencies(false, apiUrl, pcrConfig, deps); -} - -describe("attested session establishment", () => { - beforeEach(() => { - window.sessionStorage.clear(); - }); - - test("rejects an attestation with no PCR0 before key exchange", async () => { - const keyExchange = mock(async () => ({ - encrypted_session_key: "must-not-be-used", - session_id: "must-not-be-created" - })); - const validatePcr0Hash = mock(async () => ({ - isMatch: true, - text: "must not validate a missing PCR" - })); - - await expect( - establish( - dependencies({ - verifyAttestation: async () => attestationDocument(), - validatePcr0Hash, - keyExchange - }) - ) - ).rejects.toThrow(/PCR0/i); - - expect(validatePcr0Hash).not.toHaveBeenCalled(); - expect(keyExchange).not.toHaveBeenCalled(); - expect(window.sessionStorage.length).toBe(0); - }); - - test("rejects a PCR0 with the wrong SHA-384 length before key exchange", async () => { - const keyExchange = mock(async () => ({ - encrypted_session_key: "must-not-be-used", - session_id: "must-not-be-created" - })); - const validatePcr0Hash = mock(async () => ({ - isMatch: true, - text: "must not validate a malformed PCR" - })); - - await expect( - establish( - dependencies({ - verifyAttestation: async () => attestationDocument(new Uint8Array(47)), - validatePcr0Hash, - keyExchange - }) - ) - ).rejects.toThrow(/PCR0/i); - - expect(validatePcr0Hash).not.toHaveBeenCalled(); - expect(keyExchange).not.toHaveBeenCalled(); - expect(window.sessionStorage.length).toBe(0); - }); - - test("rejects an all-zero PCR0 before validation or key exchange", async () => { - const keyExchange = mock(async () => ({ - encrypted_session_key: "must-not-be-used", - session_id: "must-not-be-created" - })); - const validatePcr0Hash = mock(async () => ({ - isMatch: true, - text: "must not validate an all-zero PCR" - })); - - await expect( - establish( - dependencies({ - verifyAttestation: async () => attestationDocument(new Uint8Array(48)), - validatePcr0Hash, - keyExchange - }) - ) - ).rejects.toThrow(/PCR0/i); - - expect(validatePcr0Hash).not.toHaveBeenCalled(); - expect(keyExchange).not.toHaveBeenCalled(); - expect(window.sessionStorage.length).toBe(0); - }); - - test("rejects an unknown PCR0 before key exchange and leaves no session cache", async () => { - const keyExchange = mock(async () => ({ - encrypted_session_key: "must-not-be-used", - session_id: "must-not-be-created" - })); - const validatePcr0Hash = mock(async () => ({ - isMatch: false, - text: "PCR0 does not match a known good value" - })); - - await expect(establish(dependencies({ validatePcr0Hash, keyExchange }))).rejects.toThrow( - /PCR0/i - ); - - expect(validatePcr0Hash).toHaveBeenCalledWith( - bytesToHex(TRUSTED_PCR0), - expect.objectContaining({ ...PCR_CONFIG, environment: "production" }) - ); - expect(keyExchange).not.toHaveBeenCalled(); - expect(window.sessionStorage.length).toBe(0); - }); - - test("an allowed PCR0 establishes and reuses a policy-scoped cached session", async () => { - const verifyAttestation = mock(async () => attestationDocument(TRUSTED_PCR0)); - const validatePcr0Hash = mock(async () => ({ - isMatch: true, - text: "PCR0 matches a test trust root" - })); - const keyExchange = mock(async () => ({ - encrypted_session_key: "test-encrypted-session-key", - session_id: "trusted-session" - })); - const deps = dependencies({ verifyAttestation, validatePcr0Hash, keyExchange }); - - const established = await establish(deps); - const cached = await establish(deps); - - expect(established).toEqual({ sessionKey: SESSION_KEY, sessionId: "trusted-session" }); - expect(cached).toEqual(established); - expect(verifyAttestation).toHaveBeenCalledTimes(1); - expect(validatePcr0Hash).toHaveBeenCalledTimes(1); - expect(validatePcr0Hash).toHaveBeenCalledWith( - bytesToHex(TRUSTED_PCR0), - expect.objectContaining({ ...PCR_CONFIG, environment: "production" }) - ); - expect(keyExchange).toHaveBeenCalledTimes(1); - expect( - window.sessionStorage.getItem( - await getAttestationSessionStorageKey(REMOTE_API_URL, PCR_CONFIG) - ) - ).not.toBeNull(); - expect(window.sessionStorage.getItem("sessionKey")).toBeNull(); - expect(window.sessionStorage.getItem("sessionId")).toBeNull(); - }); - - test("a policy change cannot reuse a session established under the old trust roots", async () => { - await establish(dependencies()); - const changedPolicy: PcrConfig = { - pcr0Values: ["4c".repeat(48)], - remoteAttestation: false - }; - const keyExchange = mock(async () => ({ - encrypted_session_key: "must-not-be-used", - session_id: "must-not-be-created" - })); - const verifyAttestation = mock(async () => attestationDocument(TRUSTED_PCR0)); - - await expect( - establish( - dependencies({ - verifyAttestation, - validatePcr0Hash: async () => ({ isMatch: false, text: "not in changed policy" }), - keyExchange - }), - REMOTE_API_URL, - changedPolicy - ) - ).rejects.toThrow(/PCR0/i); - - expect(verifyAttestation).toHaveBeenCalledTimes(1); - expect(keyExchange).not.toHaveBeenCalled(); - }); - - test("production and development use distinct session cache scopes", async () => { - const productionKey = await getAttestationSessionStorageKey(REMOTE_API_URL, PCR_CONFIG); - const explicitProductionKey = await getAttestationSessionStorageKey(REMOTE_API_URL, { - ...PCR_CONFIG, - environment: "production" - }); - const developmentKey = await getAttestationSessionStorageKey(REMOTE_API_URL, { - environment: "development", - pcr0DevValues: [bytesToHex(TRUSTED_PCR0)], - remoteAttestation: false - }); - - expect(productionKey).toBe(explicitProductionKey); - expect(developmentKey).not.toBe(productionKey); - }); - - test("an environment change cannot reuse a session or reach key exchange when PCR0 mismatches", async () => { - await establish(dependencies()); - - const verifyAttestation = mock(async () => attestationDocument(TRUSTED_PCR0)); - const validatePcr0Hash = mock(async () => ({ - isMatch: false, - text: "PCR0 belongs to the production environment" - })); - const keyExchange = mock(async () => ({ - encrypted_session_key: "must-not-be-used", - session_id: "must-not-be-created" - })); - const developmentPolicy: PcrConfig = { - environment: "development", - remoteAttestation: false - }; - - await expect( - establish( - dependencies({ verifyAttestation, validatePcr0Hash, keyExchange }), - REMOTE_API_URL, - developmentPolicy - ) - ).rejects.toThrow(/PCR0/i); - - expect(verifyAttestation).toHaveBeenCalledTimes(1); - expect(validatePcr0Hash).toHaveBeenCalledWith( - bytesToHex(TRUSTED_PCR0), - expect.objectContaining(developmentPolicy) - ); - expect(keyExchange).not.toHaveBeenCalled(); - }); - - test("rejects an invalid runtime environment before attestation or key exchange", async () => { - const verifyAttestation = mock(async () => attestationDocument(TRUSTED_PCR0)); - const keyExchange = mock(async () => ({ - encrypted_session_key: "must-not-be-used", - session_id: "must-not-be-created" - })); - - await expect( - establish(dependencies({ verifyAttestation, keyExchange }), REMOTE_API_URL, { - environment: "staging" - } as unknown as PcrConfig) - ).rejects.toThrow(/environment/i); - - expect(verifyAttestation).not.toHaveBeenCalled(); - expect(keyExchange).not.toHaveBeenCalled(); - expect(window.sessionStorage.length).toBe(0); - }); - - test("ignores and removes a legacy unscoped cached session", async () => { - window.sessionStorage.setItem("sessionKey", encode(new Uint8Array(32).fill(0xff))); - window.sessionStorage.setItem("sessionId", "legacy-session"); - const verifyAttestation = mock(async () => attestationDocument(TRUSTED_PCR0)); - const keyExchange = mock(async () => ({ - encrypted_session_key: "test-encrypted-session-key", - session_id: "fresh-session" - })); - - const result = await establish(dependencies({ verifyAttestation, keyExchange })); - - expect(result).toEqual({ sessionKey: SESSION_KEY, sessionId: "fresh-session" }); - expect(verifyAttestation).toHaveBeenCalledTimes(1); - expect(keyExchange).toHaveBeenCalledTimes(1); - expect(window.sessionStorage.getItem("sessionKey")).toBeNull(); - expect(window.sessionStorage.getItem("sessionId")).toBeNull(); - }); - - test("force refresh evicts the verified session before a failed re-attestation", async () => { - await establish(dependencies()); - const cacheKey = await getAttestationSessionStorageKey(REMOTE_API_URL, PCR_CONFIG); - expect(window.sessionStorage.getItem(cacheKey)).not.toBeNull(); - - const verifyAttestation = mock(async () => { - throw new Error("attestation unavailable"); - }); - await expect( - getAttestationWithDependencies( - true, - REMOTE_API_URL, - PCR_CONFIG, - dependencies({ verifyAttestation }) - ) - ).rejects.toThrow("attestation unavailable"); - - expect(window.sessionStorage.getItem(cacheKey)).toBeNull(); - }); - - test("key exchange failure cannot leave a partial session cache", async () => { - const keyExchange = mock(async () => { - throw new Error("key exchange unavailable"); - }); - - await expect(establish(dependencies({ keyExchange }))).rejects.toThrow( - "key exchange unavailable" - ); - - expect(keyExchange).toHaveBeenCalledTimes(1); - expect(window.sessionStorage.length).toBe(0); - }); - - test("bypasses PCR validation only for an exact HTTP loopback API URL", async () => { - const validatePcr0Hash = mock(async () => { - throw new Error("loopback must not invoke PCR validation"); - }); - const keyExchange = mock(async () => ({ - encrypted_session_key: "test-encrypted-session-key", - session_id: "local-session" - })); - - const result = await establish( - dependencies({ - verifyAttestation: async () => attestationDocument(), - validatePcr0Hash, - keyExchange - }), - LOCAL_API_URL - ); - - expect(result).toEqual({ sessionKey: SESSION_KEY, sessionId: "local-session" }); - expect(validatePcr0Hash).not.toHaveBeenCalled(); - expect(keyExchange).toHaveBeenCalledTimes(1); - }); - - test.each(["https://localhost:31110", "http://localhost.example.test:31110"])( - "does not treat %s as the loopback PCR bypass", - async (apiUrl) => { - const keyExchange = mock(async () => ({ - encrypted_session_key: "must-not-be-used", - session_id: "must-not-be-created" - })); - - await expect( - establish( - dependencies({ - verifyAttestation: async () => attestationDocument(), - keyExchange - }), - apiUrl - ) - ).rejects.toThrow(/PCR0/i); - - expect(keyExchange).not.toHaveBeenCalled(); - expect(window.sessionStorage.length).toBe(0); - } - ); -}); diff --git a/sdk/src/lib/test/integration/liveAttestation.test.ts b/sdk/src/lib/test/integration/liveAttestation.test.ts deleted file mode 100644 index 16f04df7b..000000000 --- a/sdk/src/lib/test/integration/liveAttestation.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; -import { clearAttestationSessions, getAttestation } from "../../getAttestation"; - -const liveApiUrl = process.env.VITE_LIVE_ATTESTATION_API_URL; -const runLive = process.env.RUN_LIVE_ATTESTATION === "1" && Boolean(liveApiUrl); -const originalFetch = globalThis.fetch; - -function requestUrl(input: RequestInfo | URL): string { - return typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; -} - -beforeEach(() => { - clearAttestationSessions(); -}); - -afterEach(() => { - globalThis.fetch = originalFetch; - clearAttestationSessions(); -}); - -test.skipIf(!runLive)( - "hosted enclave establishes a session only after environment-scoped PCR0 validation", - async () => { - const requests: string[] = []; - globalThis.fetch = async (input, init) => { - requests.push(requestUrl(input)); - return originalFetch(input, init); - }; - - const attestation = await getAttestation(true, liveApiUrl, { - environment: "development" - }); - - expect(attestation.sessionKey).toHaveLength(32); - expect(attestation.sessionId).toBeTruthy(); - - const attestationIndex = requests.findIndex((url) => url.includes("/attestation/")); - const prodHistoryIndex = requests.findIndex((url) => url.endsWith("/pcrProdHistory.json")); - const devHistoryIndex = requests.findIndex((url) => url.endsWith("/pcrDevHistory.json")); - const keyExchangeIndex = requests.findIndex((url) => url.endsWith("/key_exchange")); - - expect(attestationIndex).toBeGreaterThanOrEqual(0); - expect(prodHistoryIndex).toBe(-1); - // A current bundled root needs no history fetch; future approved images - // still fetch and verify their signed development history before exchange. - if (devHistoryIndex >= 0) { - expect(devHistoryIndex).toBeGreaterThan(attestationIndex); - expect(keyExchangeIndex).toBeGreaterThan(devHistoryIndex); - } else { - expect(keyExchangeIndex).toBeGreaterThan(attestationIndex); - } - } -); - -test.skipIf(!runLive)( - "hosted development enclave cannot reach key exchange under production bundled trust", - async () => { - const requests: string[] = []; - globalThis.fetch = async (input, init) => { - requests.push(requestUrl(input)); - return originalFetch(input, init); - }; - - await expect( - getAttestation(true, liveApiUrl, { - environment: "production", - remoteAttestation: false - }) - ).rejects.toThrow(/PCR0/i); - - expect(requests.filter((url) => url.includes("/attestation/"))).toHaveLength(1); - expect(requests.filter((url) => url.endsWith("/key_exchange"))).toHaveLength(0); - } -); - -test.skipIf(!runLive)( - "hosted development enclave is rejected by the default production policy", - async () => { - const requests: string[] = []; - globalThis.fetch = async (input, init) => { - requests.push(requestUrl(input)); - return originalFetch(input, init); - }; - - await expect(getAttestation(true, liveApiUrl)).rejects.toThrow(/PCR0/i); - - expect(requests.filter((url) => url.includes("/attestation/"))).toHaveLength(1); - expect(requests.filter((url) => url.endsWith("/pcrProdHistory.json"))).toHaveLength(1); - expect(requests.filter((url) => url.endsWith("/pcrDevHistory.json"))).toHaveLength(0); - expect(requests.filter((url) => url.endsWith("/key_exchange"))).toHaveLength(0); - } -); diff --git a/sdk/src/lib/test/recovery.test.ts b/sdk/src/lib/test/recovery.test.ts deleted file mode 100644 index 54a337515..000000000 --- a/sdk/src/lib/test/recovery.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { - classifyRecovery, - ERROR_CODE_HEADER, - ERROR_CONTRACT_HEADER, - type RecoveryAction -} from "../recovery"; - -interface RecoveryCase { - name: string; - status: number; - contract?: string; - code?: string; - expected?: RecoveryAction; -} - -const cases: RecoveryCase[] = [ - { name: "legacy 400", status: 400, expected: "renew_session" }, - { name: "legacy 401", status: 401, expected: "refresh_access_token" }, - { name: "legacy other status", status: 422 }, - { - name: "v1 session not found", - status: 400, - contract: "1", - code: "session_not_found", - expected: "renew_session" - }, - { - name: "v1 access token expired", - status: 401, - contract: "1", - code: "access_token_expired", - expected: "refresh_access_token" - }, - { name: "v1 missing code", status: 400, contract: "1" }, - { name: "v1 unknown code", status: 400, contract: "1", code: "other" }, - { - name: "v1 malformed code", - status: 400, - contract: "1", - code: "session_not_found;foo" - }, - { - name: "v1 session code with wrong status", - status: 401, - contract: "1", - code: "session_not_found" - }, - { - name: "v1 access code with wrong status", - status: 400, - contract: "1", - code: "access_token_expired" - }, - { name: "empty contract marker", status: 400, contract: "" }, - { - name: "malformed contract marker", - status: 400, - contract: "1;foo", - code: "session_not_found" - }, - { - name: "future contract marker", - status: 400, - contract: "2", - code: "session_not_found" - }, - { - name: "legacy marker absence ignores an unversioned code", - status: 400, - code: "unknown", - expected: "renew_session" - } -]; - -describe("recovery contract classifier", () => { - for (const recoveryCase of cases) { - test(recoveryCase.name, () => { - const headers = new Headers(); - if (recoveryCase.contract !== undefined) { - headers.set(ERROR_CONTRACT_HEADER, recoveryCase.contract); - } - if (recoveryCase.code !== undefined) { - headers.set(ERROR_CODE_HEADER, recoveryCase.code); - } - - expect(classifyRecovery(recoveryCase.status, headers)).toBe(recoveryCase.expected); - }); - } - - test("duplicate contract markers fail closed", () => { - const headers = new Headers(); - headers.append(ERROR_CONTRACT_HEADER, "1"); - headers.append(ERROR_CONTRACT_HEADER, "1"); - headers.set(ERROR_CODE_HEADER, "session_not_found"); - - expect(classifyRecovery(400, headers)).toBeUndefined(); - }); - - test("duplicate error codes fail closed", () => { - const headers = new Headers(); - headers.set(ERROR_CONTRACT_HEADER, "1"); - headers.append(ERROR_CODE_HEADER, "session_not_found"); - headers.append(ERROR_CODE_HEADER, "session_not_found"); - - expect(classifyRecovery(400, headers)).toBeUndefined(); - }); -}); diff --git a/sdk/src/lib/transportV2/index.ts b/sdk/src/lib/transportV2/index.ts deleted file mode 100644 index 3cf13fecd..000000000 --- a/sdk/src/lib/transportV2/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Transport V2 is intentionally dormant: consumers inside this repository may -// exercise the engine directly, but the package entry point does not export it -// and the existing SDK continues to use Transport V1 until the coordinated -// cutover layer. -export { TransportV2Client } from "./client"; -export type { TransportV2ClientDependencies, TransportV2ClientOptions } from "./client"; -export { - TransportV2ProtocolError, - type TransportV2Credential, - type TransportV2Header, - type TransportV2Request -} from "./protocol"; -export { TransportV2RemoteError, type TransportV2LogicalResponse } from "./session";