|
| 1 | +//! HPKE encryption for a future enterprise identity-backup service. |
| 2 | +//! |
| 3 | +//! This module only creates the opaque client envelope. Recipient enrollment, |
| 4 | +//! upload, authorization, storage, and recovery are deliberately outside its |
| 5 | +//! scope. In particular, this is a native Rust API and is not registered as a |
| 6 | +//! Tauri command: renderer-controlled recipient keys would turn encryption into |
| 7 | +//! an nsec export path. |
| 8 | +//! |
| 9 | +//! This is a pure sealing component, not an active [`crate::app_state::AppState`] |
| 10 | +//! backup operation. A future enrollment/upload path must serialize identity |
| 11 | +//! selection and sealing with `AppState::identity_mutation`, obtain the live |
| 12 | +//! identity through `AppState::signing_keys()`, and bind its public key to the |
| 13 | +//! authenticated enrollment before upload. This API alone does not protect |
| 14 | +//! against identity lock, loss, or concurrent rotation, and its tests do not |
| 15 | +//! claim that runtime integration. |
| 16 | +
|
| 17 | +use std::fmt; |
| 18 | + |
| 19 | +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; |
| 20 | +use nostr::{PublicKey, SecretKey}; |
| 21 | +use rustls::crypto::{ |
| 22 | + aws_lc_rs::hpke::DH_KEM_P256_HKDF_SHA256_AES_256, |
| 23 | + hpke::{Hpke, HpkePublicKey}, |
| 24 | +}; |
| 25 | +use serde::{Deserialize, Serialize}; |
| 26 | +use uuid::Uuid; |
| 27 | +use zeroize::Zeroizing; |
| 28 | + |
| 29 | +/// HPKE `info` bytes for every v1 nsec-backup context. |
| 30 | +pub const HPKE_INFO_V1: &[u8] = b"buzz/nsec-backup/v1"; |
| 31 | + |
| 32 | +/// Version of the envelope and associated-data contract. |
| 33 | +pub const ENVELOPE_VERSION_V1: u8 = 1; |
| 34 | + |
| 35 | +/// RFC 9180 KEM ID for DHKEM(P-256, HKDF-SHA256). |
| 36 | +pub const KEM_ID_P256_HKDF_SHA256: u16 = 0x0010; |
| 37 | + |
| 38 | +/// RFC 9180 KDF ID for HKDF-SHA256. |
| 39 | +pub const KDF_ID_HKDF_SHA256: u16 = 0x0001; |
| 40 | + |
| 41 | +/// RFC 9180 AEAD ID for AES-256-GCM. |
| 42 | +pub const AEAD_ID_AES_256_GCM: u16 = 0x0002; |
| 43 | + |
| 44 | +/// Encoded length of an uncompressed SEC1 P-256 public key. |
| 45 | +pub const P256_PUBLIC_KEY_LEN: usize = 65; |
| 46 | + |
| 47 | +/// Encoded length of a v1 ciphertext: 32 secret bytes plus a 16-byte GCM tag. |
| 48 | +pub const CIPHERTEXT_LEN: usize = 48; |
| 49 | + |
| 50 | +const AAD_DOMAIN_V1: &[u8] = b"buzz/nsec-backup/aad/v1"; |
| 51 | +const MAX_CONTEXT_FIELD_LEN: usize = 255; |
| 52 | +const P256_PUBLIC_KEY_BASE64URL_LEN: usize = 87; |
| 53 | +const CIPHERTEXT_BASE64URL_LEN: usize = 64; |
| 54 | + |
| 55 | +/// Errors produced while validating or sealing an HPKE nsec-backup envelope. |
| 56 | +/// |
| 57 | +/// Error values never contain secret-key bytes or plaintext. |
| 58 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 59 | +pub enum HpkeBackupError { |
| 60 | + /// An enrollment or envelope field did not satisfy the v1 wire contract. |
| 61 | + InvalidField { |
| 62 | + /// Name of the invalid field. |
| 63 | + field: &'static str, |
| 64 | + /// Non-sensitive validation failure. |
| 65 | + reason: &'static str, |
| 66 | + }, |
| 67 | + /// The recipient key is not an uncompressed P-256 SEC1 point. |
| 68 | + InvalidRecipientKey(&'static str), |
| 69 | + /// An envelope is inconsistent with the v1 wire contract. |
| 70 | + InvalidEnvelope(&'static str), |
| 71 | + /// HPKE rejected the recipient key or failed to seal the plaintext. |
| 72 | + EncryptionFailed, |
| 73 | +} |
| 74 | + |
| 75 | +impl fmt::Display for HpkeBackupError { |
| 76 | + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 77 | + match self { |
| 78 | + Self::InvalidField { field, reason } => { |
| 79 | + write!(formatter, "invalid backup {field}: {reason}") |
| 80 | + } |
| 81 | + Self::InvalidRecipientKey(reason) => { |
| 82 | + write!(formatter, "invalid HPKE recipient public key: {reason}") |
| 83 | + } |
| 84 | + Self::InvalidEnvelope(reason) => write!(formatter, "invalid backup envelope: {reason}"), |
| 85 | + Self::EncryptionFailed => { |
| 86 | + formatter.write_str("HPKE backup encryption failed; recipient key may be invalid") |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +impl std::error::Error for HpkeBackupError {} |
| 93 | + |
| 94 | +/// Fixed algorithm identifiers carried by a v1 envelope. |
| 95 | +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] |
| 96 | +#[serde(deny_unknown_fields)] |
| 97 | +pub struct HpkeSuiteIds { |
| 98 | + kem_id: u16, |
| 99 | + kdf_id: u16, |
| 100 | + aead_id: u16, |
| 101 | +} |
| 102 | + |
| 103 | +impl HpkeSuiteIds { |
| 104 | + const V1: Self = Self { |
| 105 | + kem_id: KEM_ID_P256_HKDF_SHA256, |
| 106 | + kdf_id: KDF_ID_HKDF_SHA256, |
| 107 | + aead_id: AEAD_ID_AES_256_GCM, |
| 108 | + }; |
| 109 | + |
| 110 | + fn is_v1(self) -> bool { |
| 111 | + self == Self::V1 |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +/// Enrollment values authenticated into one backup envelope. |
| 116 | +#[derive(Clone, Debug)] |
| 117 | +pub struct HpkeBackupEnrollment { |
| 118 | + recipient_key_id: String, |
| 119 | + service_namespace: String, |
| 120 | + owner_id: String, |
| 121 | + backup_id: Uuid, |
| 122 | + recipient_public_key: [u8; P256_PUBLIC_KEY_LEN], |
| 123 | +} |
| 124 | + |
| 125 | +impl HpkeBackupEnrollment { |
| 126 | + /// Validate enrollment metadata supplied by a trusted native integration. |
| 127 | + /// |
| 128 | + /// Identifier strings are encoded as UTF-8 bytes without normalization in |
| 129 | + /// AAD. Each must be 1 through 255 bytes and must not contain control |
| 130 | + /// characters. The backup ID is encoded as its 16 raw UUID bytes. |
| 131 | + pub fn new( |
| 132 | + recipient_key_id: impl Into<String>, |
| 133 | + service_namespace: impl Into<String>, |
| 134 | + owner_id: impl Into<String>, |
| 135 | + backup_id: Uuid, |
| 136 | + recipient_public_key_sec1: &[u8], |
| 137 | + ) -> Result<Self, HpkeBackupError> { |
| 138 | + let recipient_key_id = recipient_key_id.into(); |
| 139 | + let service_namespace = service_namespace.into(); |
| 140 | + let owner_id = owner_id.into(); |
| 141 | + validate_context_field("recipient key ID", &recipient_key_id)?; |
| 142 | + validate_context_field("service namespace", &service_namespace)?; |
| 143 | + validate_context_field("owner ID", &owner_id)?; |
| 144 | + |
| 145 | + let recipient_public_key: [u8; P256_PUBLIC_KEY_LEN] = recipient_public_key_sec1 |
| 146 | + .try_into() |
| 147 | + .map_err(|_| HpkeBackupError::InvalidRecipientKey("expected exactly 65 SEC1 bytes"))?; |
| 148 | + if recipient_public_key[0] != 0x04 { |
| 149 | + return Err(HpkeBackupError::InvalidRecipientKey( |
| 150 | + "expected uncompressed SEC1 prefix 0x04", |
| 151 | + )); |
| 152 | + } |
| 153 | + |
| 154 | + Ok(Self { |
| 155 | + recipient_key_id, |
| 156 | + service_namespace, |
| 157 | + owner_id, |
| 158 | + backup_id, |
| 159 | + recipient_public_key, |
| 160 | + }) |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +/// Opaque v1 backup envelope produced by [`seal_nostr_secret`]. |
| 165 | +/// |
| 166 | +/// JSON serialization is the wire representation. Binary HPKE values use |
| 167 | +/// URL-safe base64 with no padding. This type contains no plaintext or raw nsec |
| 168 | +/// material. |
| 169 | +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] |
| 170 | +#[serde(deny_unknown_fields)] |
| 171 | +pub struct HpkeBackupEnvelope { |
| 172 | + version: u8, |
| 173 | + suite: HpkeSuiteIds, |
| 174 | + recipient_key_id: String, |
| 175 | + service_namespace: String, |
| 176 | + owner_id: String, |
| 177 | + backup_id: String, |
| 178 | + nostr_pubkey: String, |
| 179 | + enc: String, |
| 180 | + ciphertext: String, |
| 181 | +} |
| 182 | + |
| 183 | +impl HpkeBackupEnvelope { |
| 184 | + /// Reconstruct the v1 associated-data bytes from envelope metadata. |
| 185 | + /// |
| 186 | + /// This validates fixed suite/version values and canonical metadata |
| 187 | + /// encodings before returning bytes. Receivers must separately validate |
| 188 | + /// `enc` and ciphertext through the byte accessors before HPKE open. |
| 189 | + pub fn associated_data(&self) -> Result<Vec<u8>, HpkeBackupError> { |
| 190 | + if self.version != ENVELOPE_VERSION_V1 { |
| 191 | + return Err(HpkeBackupError::InvalidEnvelope("unsupported version")); |
| 192 | + } |
| 193 | + if !self.suite.is_v1() { |
| 194 | + return Err(HpkeBackupError::InvalidEnvelope("unsupported HPKE suite")); |
| 195 | + } |
| 196 | + validate_context_field("recipient key ID", &self.recipient_key_id)?; |
| 197 | + validate_context_field("service namespace", &self.service_namespace)?; |
| 198 | + validate_context_field("owner ID", &self.owner_id)?; |
| 199 | + |
| 200 | + let backup_id = Uuid::parse_str(&self.backup_id) |
| 201 | + .map_err(|_| HpkeBackupError::InvalidEnvelope("backup ID is not a UUID"))?; |
| 202 | + if backup_id.hyphenated().to_string() != self.backup_id { |
| 203 | + return Err(HpkeBackupError::InvalidEnvelope( |
| 204 | + "backup ID is not canonical lowercase hyphenated UUID", |
| 205 | + )); |
| 206 | + } |
| 207 | + |
| 208 | + let nostr_pubkey = PublicKey::from_hex(&self.nostr_pubkey) |
| 209 | + .map_err(|_| HpkeBackupError::InvalidEnvelope("invalid Nostr public key"))?; |
| 210 | + if nostr_pubkey.to_hex() != self.nostr_pubkey { |
| 211 | + return Err(HpkeBackupError::InvalidEnvelope( |
| 212 | + "Nostr public key is not canonical lowercase hex", |
| 213 | + )); |
| 214 | + } |
| 215 | + |
| 216 | + Ok(build_aad( |
| 217 | + &self.recipient_key_id, |
| 218 | + &self.service_namespace, |
| 219 | + &self.owner_id, |
| 220 | + backup_id.as_bytes(), |
| 221 | + &nostr_pubkey.to_bytes(), |
| 222 | + )) |
| 223 | + } |
| 224 | + |
| 225 | + /// Decode and validate the RFC 9180 encapsulated P-256 public-key shape. |
| 226 | + /// |
| 227 | + /// This enforces the 65-byte uncompressed SEC1 representation and its |
| 228 | + /// `0x04` prefix. The HPKE provider validates P-256 curve membership when |
| 229 | + /// a recipient uses these bytes to open the envelope. |
| 230 | + pub fn encapsulated_key_bytes(&self) -> Result<Vec<u8>, HpkeBackupError> { |
| 231 | + let decoded = decode_canonical_base64( |
| 232 | + &self.enc, |
| 233 | + P256_PUBLIC_KEY_BASE64URL_LEN, |
| 234 | + P256_PUBLIC_KEY_LEN, |
| 235 | + "enc", |
| 236 | + )?; |
| 237 | + if decoded.first() != Some(&0x04) { |
| 238 | + return Err(HpkeBackupError::InvalidField { |
| 239 | + field: "enc", |
| 240 | + reason: "expected uncompressed SEC1 prefix 0x04", |
| 241 | + }); |
| 242 | + } |
| 243 | + Ok(decoded) |
| 244 | + } |
| 245 | + |
| 246 | + /// Decode and validate the 32-byte-secret AES-256-GCM ciphertext. |
| 247 | + pub fn ciphertext_bytes(&self) -> Result<Vec<u8>, HpkeBackupError> { |
| 248 | + decode_canonical_base64( |
| 249 | + &self.ciphertext, |
| 250 | + CIPHERTEXT_BASE64URL_LEN, |
| 251 | + CIPHERTEXT_LEN, |
| 252 | + "ciphertext", |
| 253 | + ) |
| 254 | + } |
| 255 | +} |
| 256 | + |
| 257 | +/// Seal one native Nostr secret key to a trusted HPKE backup enrollment. |
| 258 | +/// |
| 259 | +/// The function derives the Nostr public key from `secret_key` and encrypts its |
| 260 | +/// raw 32-byte secret representation in RFC 9180 Base mode. `rustls` creates a |
| 261 | +/// fresh ephemeral P-256 key for every call. HPKE Base mode does not |
| 262 | +/// authenticate the sender; future upload authorization or a separate signature |
| 263 | +/// must provide that property. |
| 264 | +pub fn seal_nostr_secret( |
| 265 | + secret_key: &SecretKey, |
| 266 | + enrollment: &HpkeBackupEnrollment, |
| 267 | +) -> Result<HpkeBackupEnvelope, HpkeBackupError> { |
| 268 | + let nostr_pubkey = PublicKey::from(secret_key.x_only_public_key(nostr::SECP256K1).0).to_hex(); |
| 269 | + let mut envelope = HpkeBackupEnvelope { |
| 270 | + version: ENVELOPE_VERSION_V1, |
| 271 | + suite: HpkeSuiteIds::V1, |
| 272 | + recipient_key_id: enrollment.recipient_key_id.clone(), |
| 273 | + service_namespace: enrollment.service_namespace.clone(), |
| 274 | + owner_id: enrollment.owner_id.clone(), |
| 275 | + backup_id: enrollment.backup_id.hyphenated().to_string(), |
| 276 | + nostr_pubkey, |
| 277 | + enc: String::new(), |
| 278 | + ciphertext: String::new(), |
| 279 | + }; |
| 280 | + let aad = envelope.associated_data()?; |
| 281 | + // This clears our buffer on drop, but not the HPKE provider's internal |
| 282 | + // plaintext copy, which can be freed without zeroization. |
| 283 | + let plaintext = Zeroizing::new(secret_key.to_secret_bytes()); |
| 284 | + |
| 285 | + let recipient = HpkePublicKey(enrollment.recipient_public_key.to_vec()); |
| 286 | + let (enc, ciphertext) = DH_KEM_P256_HKDF_SHA256_AES_256 |
| 287 | + .seal(HPKE_INFO_V1, &aad, plaintext.as_ref(), &recipient) |
| 288 | + .map_err(|_| HpkeBackupError::EncryptionFailed)?; |
| 289 | + |
| 290 | + if enc.0.len() != P256_PUBLIC_KEY_LEN || ciphertext.len() != CIPHERTEXT_LEN { |
| 291 | + return Err(HpkeBackupError::EncryptionFailed); |
| 292 | + } |
| 293 | + envelope.enc = URL_SAFE_NO_PAD.encode(enc.0); |
| 294 | + envelope.ciphertext = URL_SAFE_NO_PAD.encode(ciphertext); |
| 295 | + Ok(envelope) |
| 296 | +} |
| 297 | + |
| 298 | +fn validate_context_field(field: &'static str, value: &str) -> Result<(), HpkeBackupError> { |
| 299 | + if value.is_empty() { |
| 300 | + return Err(HpkeBackupError::InvalidField { |
| 301 | + field, |
| 302 | + reason: "must not be empty", |
| 303 | + }); |
| 304 | + } |
| 305 | + if value.len() > MAX_CONTEXT_FIELD_LEN { |
| 306 | + return Err(HpkeBackupError::InvalidField { |
| 307 | + field, |
| 308 | + reason: "must be at most 255 UTF-8 bytes", |
| 309 | + }); |
| 310 | + } |
| 311 | + if value.chars().any(char::is_control) { |
| 312 | + return Err(HpkeBackupError::InvalidField { |
| 313 | + field, |
| 314 | + reason: "must not contain control characters", |
| 315 | + }); |
| 316 | + } |
| 317 | + Ok(()) |
| 318 | +} |
| 319 | + |
| 320 | +fn build_aad( |
| 321 | + recipient_key_id: &str, |
| 322 | + service_namespace: &str, |
| 323 | + owner_id: &str, |
| 324 | + backup_id: &[u8; 16], |
| 325 | + nostr_pubkey: &[u8; 32], |
| 326 | +) -> Vec<u8> { |
| 327 | + let mut aad = Vec::with_capacity( |
| 328 | + AAD_DOMAIN_V1.len() |
| 329 | + + 7 |
| 330 | + + 6 |
| 331 | + + recipient_key_id.len() |
| 332 | + + service_namespace.len() |
| 333 | + + owner_id.len() |
| 334 | + + backup_id.len() |
| 335 | + + nostr_pubkey.len(), |
| 336 | + ); |
| 337 | + aad.extend_from_slice(AAD_DOMAIN_V1); |
| 338 | + aad.push(ENVELOPE_VERSION_V1); |
| 339 | + aad.extend_from_slice(&KEM_ID_P256_HKDF_SHA256.to_be_bytes()); |
| 340 | + aad.extend_from_slice(&KDF_ID_HKDF_SHA256.to_be_bytes()); |
| 341 | + aad.extend_from_slice(&AEAD_ID_AES_256_GCM.to_be_bytes()); |
| 342 | + push_framed(&mut aad, recipient_key_id.as_bytes()); |
| 343 | + push_framed(&mut aad, service_namespace.as_bytes()); |
| 344 | + push_framed(&mut aad, owner_id.as_bytes()); |
| 345 | + aad.extend_from_slice(backup_id); |
| 346 | + aad.extend_from_slice(nostr_pubkey); |
| 347 | + aad |
| 348 | +} |
| 349 | + |
| 350 | +fn push_framed(output: &mut Vec<u8>, value: &[u8]) { |
| 351 | + // All callers first apply MAX_CONTEXT_FIELD_LEN, which is below u16::MAX. |
| 352 | + output.extend_from_slice(&(value.len() as u16).to_be_bytes()); |
| 353 | + output.extend_from_slice(value); |
| 354 | +} |
| 355 | + |
| 356 | +fn decode_canonical_base64( |
| 357 | + value: &str, |
| 358 | + expected_encoded_len: usize, |
| 359 | + expected_decoded_len: usize, |
| 360 | + field: &'static str, |
| 361 | +) -> Result<Vec<u8>, HpkeBackupError> { |
| 362 | + // `str::len` is the UTF-8 byte length. Check it before decoding so an |
| 363 | + // untrusted JSON string cannot cause an allocation proportional to input. |
| 364 | + if value.len() != expected_encoded_len { |
| 365 | + return Err(HpkeBackupError::InvalidField { |
| 366 | + field, |
| 367 | + reason: "unexpected encoded length", |
| 368 | + }); |
| 369 | + } |
| 370 | + let decoded = URL_SAFE_NO_PAD |
| 371 | + .decode(value) |
| 372 | + .map_err(|_| HpkeBackupError::InvalidField { |
| 373 | + field, |
| 374 | + reason: "invalid base64url", |
| 375 | + })?; |
| 376 | + if decoded.len() != expected_decoded_len { |
| 377 | + return Err(HpkeBackupError::InvalidField { |
| 378 | + field, |
| 379 | + reason: "unexpected decoded length", |
| 380 | + }); |
| 381 | + } |
| 382 | + if URL_SAFE_NO_PAD.encode(&decoded) != value { |
| 383 | + return Err(HpkeBackupError::InvalidField { |
| 384 | + field, |
| 385 | + reason: "base64url is not canonical and unpadded", |
| 386 | + }); |
| 387 | + } |
| 388 | + Ok(decoded) |
| 389 | +} |
| 390 | + |
| 391 | +#[cfg(test)] |
| 392 | +#[path = "hpke_key_backup_tests.rs"] |
| 393 | +mod tests; |
0 commit comments