From bb044df449315f07ada45276ab56ea42494afb4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E5=B0=8F=E9=B8=AD?= Date: Sun, 22 Nov 2026 15:42:45 +0800 Subject: [PATCH] refactor(sse): split the write path into S3 scheme and keying mode The write entry points mixed two questions: which SSE scheme S3 asks for, and how this build forms and stores the object key. Give each a home. - `core/s3/scheme.rs` gains `resolve_write_scheme`, which validates the headers and resolves the request, then the bucket default, to a `WriteScheme`. PutObject and CreateMultipartUpload now share it; the second copy of that decision (`SseTypeV2`, `prepare_sse_configuration_v2`) is removed. - `core/keying/` gains one constructor per key source (`new_key_under_customer_key`, `new_session_key_under_customer_key`, `new_key_under_data_key`) in each mode. `keying/mod.rs` is the only place that says which mode a build writes. - `core/write.rs` only orders the steps and no longer carries any `rio-v2` conditional compilation. No behavior change. A multipart session still validates the SSE-C key at creation only in the mode that seals the session key under it. `SseTypeV2` leaves the public surface; nothing outside the crate used it. --- crates/sse/src/core/keying/direct.rs | 81 ++++++++ crates/sse/src/core/keying/mod.rs | 25 +++ crates/sse/src/core/keying/object.rs | 57 +++++- crates/sse/src/core/s3/scheme.rs | 100 ++++++---- crates/sse/src/core/write.rs | 274 ++++++++++----------------- crates/sse/src/lib.rs | 2 +- crates/sse/src/tests.rs | 10 +- 7 files changed, 339 insertions(+), 210 deletions(-) diff --git a/crates/sse/src/core/keying/direct.rs b/crates/sse/src/core/keying/direct.rs index fbe9889e7d..d141caa491 100644 --- a/crates/sse/src/core/keying/direct.rs +++ b/crates/sse/src/core/keying/direct.rs @@ -14,8 +14,20 @@ //! Direct keying: the data key encrypts the object itself, under a stored base nonce. +#[cfg(not(feature = "rio-v2"))] +use crate::core::keying::NewObjectKey; +#[cfg(not(feature = "rio-v2"))] +use crate::core::keying::material::EncryptionKeyKind; use crate::core::s3::ssec::md5_bytes; +#[cfg(not(feature = "rio-v2"))] +use crate::error::SseError; use base64_simd::STANDARD as BASE64_STANDARD; +#[cfg(not(feature = "rio-v2"))] +use rand::Rng; +#[cfg(not(feature = "rio-v2"))] +use rustfs_kms::DataKey; +#[cfg(not(feature = "rio-v2"))] +use rustfs_utils::http::object_encryption_keys::SSEType; use rustfs_utils::http::object_encryption_keys::{INTERNAL_ENCRYPTION_IV_HEADER, MINIO_INTERNAL_ENCRYPTION_IV_HEADER}; use std::collections::HashMap; @@ -48,3 +60,72 @@ pub(crate) fn generate_ssec_nonce(bucket: &str, key: &str) -> [u8; 12] { nonce.copy_from_slice(&nonce_hash[..12]); nonce } + +/// Whether a multipart session needs the customer key when it is created. +/// +/// Direct mode records only a nonce for the session; the customer key is checked +/// per part, against what the session recorded. +#[cfg(not(feature = "rio-v2"))] +pub(crate) const SESSION_KEY_NEEDS_CUSTOMER_KEY: bool = false; + +#[cfg(not(feature = "rio-v2"))] +fn random_base_nonce() -> [u8; 12] { + let mut base_nonce = [0u8; 12]; + rand::rng().fill_bytes(&mut base_nonce); + base_nonce +} + +/// SSE-C object: the customer key encrypts the object itself. +/// +/// Uses a fresh random nonce per encryption. A deterministic nonce derived from +/// (bucket, key) would repeat whenever the same object is overwritten under the same +/// SSE-C key, reusing an identical (key, nonce) pair and catastrophically breaking +/// AES-256-GCM. The nonce is persisted (see `encryption_material_to_metadata`) and read +/// back on decrypt (see [`read_stored_ssec_nonce`]). +#[cfg(not(feature = "rio-v2"))] +pub(crate) fn new_key_under_customer_key(customer_key: [u8; 32], _bucket: &str, _key: &str) -> Result { + Ok(NewObjectKey { + key_bytes: customer_key, + base_nonce: random_base_nonce(), + key_kind: EncryptionKeyKind::Direct, + sealed_key: None, + }) +} + +/// SSE-C multipart session: a nonce every part of the upload shares. +/// +/// Generates a real random nonce for the session and persists it (see +/// `encryption_material_to_metadata`). Every part of this upload reads the same +/// persisted nonce back, so all parts share one nonce without reintroducing the +/// deterministic (bucket, key) reuse hazard. `key_bytes` stays a placeholder: it is +/// neither used for encryption nor persisted; the real customer key is validated per +/// part on upload. +#[cfg(not(feature = "rio-v2"))] +pub(crate) fn new_session_key_under_customer_key( + _customer_key: Option<[u8; 32]>, + _bucket: &str, + _key: &str, +) -> Result { + Ok(NewObjectKey { + key_bytes: [0; 32], + base_nonce: random_base_nonce(), + key_kind: EncryptionKeyKind::Direct, + sealed_key: None, + }) +} + +/// Managed SSE: the data key encrypts the object itself, under the nonce issued with it. +#[cfg(not(feature = "rio-v2"))] +pub(crate) fn new_key_under_data_key( + data_key: &DataKey, + _sse_type: SSEType, + _bucket: &str, + _key: &str, +) -> Result { + Ok(NewObjectKey { + key_bytes: data_key.plaintext_key, + base_nonce: data_key.nonce, + key_kind: EncryptionKeyKind::Direct, + sealed_key: None, + }) +} diff --git a/crates/sse/src/core/keying/mod.rs b/crates/sse/src/core/keying/mod.rs index 10e9826ef3..d2cf71983a 100644 --- a/crates/sse/src/core/keying/mod.rs +++ b/crates/sse/src/core/keying/mod.rs @@ -20,3 +20,28 @@ pub(crate) mod material; pub(crate) mod metadata; #[cfg(feature = "rio-v2")] pub(crate) mod object; + +use crate::core::keying::material::{EncryptionKeyKind, ManagedSealedKey}; + +/// The key a new object is encrypted with, in the mode this build writes. +pub(crate) struct NewObjectKey { + /// Key handed to the stream cipher. + pub(crate) key_bytes: [u8; 32], + /// Base nonce the stream cipher derives its block nonces from. + pub(crate) base_nonce: [u8; 12], + /// The mode `key_bytes` belongs to. + pub(crate) key_kind: EncryptionKeyKind, + /// The sealed form to store, in a mode that seals a separate object key. + pub(crate) sealed_key: Option, +} + +// The mode new objects are written in. Every build reads every mode it can +// recognize; writing picks exactly one, and this is the only place that says which. +#[cfg(not(feature = "rio-v2"))] +pub(crate) use direct::{ + SESSION_KEY_NEEDS_CUSTOMER_KEY, new_key_under_customer_key, new_key_under_data_key, new_session_key_under_customer_key, +}; +#[cfg(feature = "rio-v2")] +pub(crate) use object::{ + SESSION_KEY_NEEDS_CUSTOMER_KEY, new_key_under_customer_key, new_key_under_data_key, new_session_key_under_customer_key, +}; diff --git a/crates/sse/src/core/keying/object.rs b/crates/sse/src/core/keying/object.rs index df839e785a..68dcfbcb52 100644 --- a/crates/sse/src/core/keying/object.rs +++ b/crates/sse/src/core/keying/object.rs @@ -14,7 +14,8 @@ //! Object keying: a derived object key, sealed in the MinIO-compatible format. -use crate::core::keying::material::ManagedSealedKey; +use crate::core::keying::NewObjectKey; +use crate::core::keying::material::{EncryptionKeyKind, ManagedSealedKey}; use crate::error::SseError; use aes_gcm::aead::{Aead, KeyInit, Payload}; use aes_gcm::{Aes256Gcm, Nonce}; @@ -22,6 +23,7 @@ use base64_simd::STANDARD as BASE64_STANDARD; use chacha20poly1305::ChaCha20Poly1305; use hmac::{Hmac, Mac}; use rand::RngExt; +use rustfs_kms::DataKey; use rustfs_utils::http::object_encryption_keys::{ INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER, MINIO_INTERNAL_ENCRYPTION_IV_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER, @@ -273,3 +275,56 @@ pub(crate) fn parse_minio_managed_sealed_key( Ok(Some(ManagedSealedKey { iv, sealed_key })) } + +/// Whether a multipart session needs the customer key when it is created. +/// +/// Object mode seals the session's object key under the customer key, so the key +/// has to be present, and valid, at that point. +pub(crate) const SESSION_KEY_NEEDS_CUSTOMER_KEY: bool = true; + +/// Derive a fresh object key from `external_key` and seal it under the same key. +fn new_sealed_object_key(external_key: [u8; 32], sse_type: SSEType, bucket: &str, key: &str) -> Result { + let object_key = derive_object_key(external_key)?; + let sealed_key = seal_object_key(object_key, external_key, sse_type, bucket, key)?; + Ok(NewObjectKey { + key_bytes: object_key, + base_nonce: [0; 12], + key_kind: EncryptionKeyKind::Object, + sealed_key: Some(sealed_key), + }) +} + +/// SSE-C object: an object key sealed under the customer key. +pub(crate) fn new_key_under_customer_key(customer_key: [u8; 32], bucket: &str, key: &str) -> Result { + new_sealed_object_key(customer_key, SSEType::SseC, bucket, key) +} + +/// SSE-C multipart session: an object key sealed under the customer key. +/// +/// A session created without its customer key has nothing to seal and records a +/// placeholder instead. +pub(crate) fn new_session_key_under_customer_key( + customer_key: Option<[u8; 32]>, + bucket: &str, + key: &str, +) -> Result { + match customer_key { + Some(customer_key) => new_sealed_object_key(customer_key, SSEType::SseC, bucket, key), + None => Ok(NewObjectKey { + key_bytes: [0; 32], + base_nonce: [0; 12], + key_kind: EncryptionKeyKind::Direct, + sealed_key: None, + }), + } +} + +/// Managed SSE: an object key sealed under the data key. +pub(crate) fn new_key_under_data_key( + data_key: &DataKey, + sse_type: SSEType, + bucket: &str, + key: &str, +) -> Result { + new_sealed_object_key(data_key.plaintext_key, sse_type, bucket, key) +} diff --git a/crates/sse/src/core/s3/scheme.rs b/crates/sse/src/core/s3/scheme.rs index 951fdb3f46..e270ee3597 100644 --- a/crates/sse/src/core/s3/scheme.rs +++ b/crates/sse/src/core/s3/scheme.rs @@ -14,11 +14,13 @@ //! Which SSE scheme and which key a request resolves to: the request first, then the bucket default. +use crate::core::s3::headers::validate_sse_headers_for_write; use crate::error::SseError; use crate::host::SseHost; use crate::{LOG_COMPONENT_STORAGE, LOG_SUBSYSTEM_SSE}; use rustfs_utils::http::headers::{AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS}; use rustfs_utils::http::object_encryption_keys::SSEType; +use std::collections::HashMap; use tracing::debug; pub const DEFAULT_SSE_ALGORITHM: &str = "AES256"; @@ -167,52 +169,86 @@ where requested_kms_key_id.or_else(bucket_default_kms_key_id) } -#[derive(Clone)] -pub enum SseTypeV2 { - SseS3(String), - SseKms(String, Option), - SseC(String, String, String), +/// The SSE headers of a write request, as the S3 layer received them. +pub(crate) struct WriteSchemeHeaders<'a> { + pub(crate) server_side_encryption: Option, + pub(crate) ssekms_key_id: Option, + pub(crate) ssekms_context: Option<&'a HashMap>, + pub(crate) sse_customer_algorithm: Option, + pub(crate) sse_customer_key: Option, + pub(crate) sse_customer_key_md5: Option, } -impl std::fmt::Debug for SseTypeV2 { +/// The scheme a write resolved to, in S3's terms. +#[derive(Clone)] +pub(crate) enum WriteScheme { + /// `AES256`: the server chooses the wrapping key and the caller names none. + SseS3, + /// `aws:kms`, under the key the request or the bucket default named, if either did. + SseKms { key_id: Option }, + /// A key the client supplies; only its MD5 is ever stored. + SseC { + algorithm: String, + key: String, + key_md5: String, + }, +} + +impl std::fmt::Debug for WriteScheme { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { - Self::SseS3(_) => "SseS3(..)", - Self::SseKms(_, _) => "SseKms(..)", - Self::SseC(_, _, _) => "SseC(..)", + Self::SseS3 => "SseS3", + Self::SseKms { .. } => "SseKms(..)", + Self::SseC { .. } => "SseC(..)", }) } } -pub(crate) async fn prepare_sse_configuration_v2( +/// Decide the scheme of a write: validate the headers, then the request first and the +/// bucket default second. +/// +/// Every write goes through here, an object and a multipart session alike, so the two +/// cannot resolve the same headers differently. +pub(crate) async fn resolve_write_scheme( host: &dyn SseHost, bucket: &str, - server_side_encryption: Option, - customer_algorithm: Option, - customer_key: Option, - customer_key_md5: Option, - ssekms_key_id: Option, -) -> Result, SseError> { - if let Some(customer_algorithm) = customer_algorithm - && let Some(customer_key_md5) = customer_key_md5 + headers: WriteSchemeHeaders<'_>, +) -> Result, SseError> { + validate_sse_headers_for_write( + headers.server_side_encryption.as_deref(), + headers.ssekms_key_id.as_ref(), + headers.ssekms_context, + headers.sse_customer_algorithm.as_ref(), + headers.sse_customer_key.as_ref(), + headers.sse_customer_key_md5.as_ref(), + true, + )?; + + // Validation admits SSE-C headers only as a complete set, and never beside the + // managed ones, so their presence alone decides. + if let (Some(algorithm), Some(key), Some(key_md5)) = + (headers.sse_customer_algorithm, headers.sse_customer_key, headers.sse_customer_key_md5) { - // if create_multipart_upload request, customer_key is not provided - let customer_key = customer_key.unwrap_or_default(); - - return Ok(Some(SseTypeV2::SseC(customer_algorithm, customer_key, customer_key_md5))); + return Ok(Some(WriteScheme::SseC { algorithm, key, key_md5 })); } - let sse_config = prepare_sse_configuration(host, bucket, server_side_encryption, ssekms_key_id).await?; + let Some(config) = prepare_sse_configuration(host, bucket, headers.server_side_encryption, headers.ssekms_key_id).await? + else { + return Ok(None); + }; - if let Some(sse_config) = sse_config { - return match sse_config.effective_sse.as_str() { - AMZ_ENCRYPTION_AES => Ok(Some(SseTypeV2::SseS3(sse_config.effective_sse))), - AMZ_ENCRYPTION_KMS => Ok(Some(SseTypeV2::SseKms(sse_config.effective_sse.clone(), sse_config.effective_kms_key_id))), - _ => Ok(None), - }; - } - - Ok(None) + Ok(match config.effective_sse.as_str() { + AMZ_ENCRYPTION_AES => { + // Validation admits a key id only beside `aws:kms`, and the bucket default's + // key is consulted only for `aws:kms`. + debug_assert!(config.effective_kms_key_id.is_none(), "SSE-S3 never names a KMS key"); + Some(WriteScheme::SseS3) + } + AMZ_ENCRYPTION_KMS => Some(WriteScheme::SseKms { + key_id: config.effective_kms_key_id, + }), + _ => None, + }) } /// Scheme a managed-SSE header names, defaulting to SSE-S3 the same way the diff --git a/crates/sse/src/core/write.rs b/crates/sse/src/core/write.rs index e5621310d4..8c2374fe71 100644 --- a/crates/sse/src/core/write.rs +++ b/crates/sse/src/core/write.rs @@ -16,26 +16,24 @@ use crate::core::audit::{envelope_master_key_version, record_managed_kms_outcome}; use crate::core::keying::context::{build_object_encryption_context, reject_kms_context_location_override}; -use crate::core::keying::material::{EncryptionKeyKind, EncryptionMaterial}; -#[cfg(feature = "rio-v2")] -use crate::core::keying::object::{derive_object_key, seal_object_key}; +use crate::core::keying::material::EncryptionMaterial; +use crate::core::keying::{ + SESSION_KEY_NEEDS_CUSTOMER_KEY, new_key_under_customer_key, new_key_under_data_key, new_session_key_under_customer_key, +}; use crate::core::request::SseKmsPrincipal; use crate::core::s3::authorization::authorize_sse_kms_key; -use crate::core::s3::headers::validate_sse_headers_for_write; use crate::core::s3::scheme::{ - DEFAULT_SSE_ALGORITHM, SseTypeV2, is_managed_sse, managed_sse_type, prepare_sse_configuration, prepare_sse_configuration_v2, + DEFAULT_SSE_ALGORITHM, WriteScheme, WriteSchemeHeaders, is_managed_sse, managed_sse_type, resolve_write_scheme, }; use crate::core::s3::ssec::{SsecParams, ssec_invalid_request, validate_ssec_params, verify_ssec_key_match}; use crate::error::SseError; use crate::host::SseHost; use crate::kms::provider::get_sse_dek_provider; use base64_simd::STANDARD as BASE64_STANDARD; -#[cfg(not(feature = "rio-v2"))] -use rand::Rng; use rustfs_kms::KmsUnavailableError; use rustfs_policy::policy::action::KmsAction; use rustfs_s3_types::S3ErrorCode; -use rustfs_utils::http::headers::AMZ_ENCRYPTION_AES; +use rustfs_utils::http::headers::{AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS}; use rustfs_utils::http::object_encryption_keys::SSEType; use std::collections::HashMap; @@ -179,50 +177,45 @@ impl EncryptionRequest<'_> { /// } /// ``` pub async fn sse_encryption(host: &dyn SseHost, request: EncryptionRequest<'_>) -> Result, SseError> { - validate_sse_headers_for_write( - request.server_side_encryption.as_deref(), - request.ssekms_key_id.as_ref(), - request.ssekms_context.as_ref(), - request.sse_customer_algorithm.as_ref(), - request.sse_customer_key.as_ref(), - request.sse_customer_key_md5.as_ref(), - true, - )?; + let scheme = resolve_write_scheme( + host, + request.bucket, + WriteSchemeHeaders { + server_side_encryption: request.server_side_encryption, + ssekms_key_id: request.ssekms_key_id, + ssekms_context: request.ssekms_context.as_ref(), + sse_customer_algorithm: request.sse_customer_algorithm, + sse_customer_key: request.sse_customer_key, + sse_customer_key_md5: request.sse_customer_key_md5, + }, + ) + .await?; - // Priority 1: SSE-C (customer-provided key) - if let (Some(algorithm), Some(key), Some(key_md5)) = - (request.sse_customer_algorithm, request.sse_customer_key, request.sse_customer_key_md5) - { - return apply_ssec_encryption_material(request.bucket, request.key, algorithm, key, key_md5, request.content_size) - .await - .map(Some); - } + let (server_side_encryption, kms_key_id) = match scheme { + None => return Ok(None), + Some(WriteScheme::SseC { algorithm, key, key_md5 }) => { + return apply_ssec_encryption_material(request.bucket, request.key, algorithm, key, key_md5, request.content_size) + .await + .map(Some); + } + Some(WriteScheme::SseS3) => (String::from(AMZ_ENCRYPTION_AES), None), + Some(WriteScheme::SseKms { key_id }) => (String::from(AMZ_ENCRYPTION_KMS), key_id), + }; - // Priority 2: Managed SSE (SSE-S3 or SSE-KMS) - let sse_config = - prepare_sse_configuration(host, request.bucket, request.server_side_encryption, request.ssekms_key_id).await?; - - if let Some(sse_config) = sse_config - && is_managed_sse(&sse_config.effective_sse) - { - return apply_managed_encryption_material( - host, - ManagedEncryptionRequest { - bucket: request.bucket, - key: request.key, - server_side_encryption: sse_config.effective_sse, - kms_key_id: sse_config.effective_kms_key_id, - ssekms_context: request.ssekms_context, - content_size: request.content_size, - principal: request.principal, - }, - ) - .await - .map(Some); - } - - // No encryption requested - Ok(None) + apply_managed_encryption_material( + host, + ManagedEncryptionRequest { + bucket: request.bucket, + key: request.key, + server_side_encryption, + kms_key_id, + ssekms_context: request.ssekms_context, + content_size: request.content_size, + principal: request.principal, + }, + ) + .await + .map(Some) } /// **Core API**: Apply encryption based on request parameters @@ -257,67 +250,46 @@ pub async fn sse_prepare_encryption( host: &dyn SseHost, request: PrepareEncryptionRequest<'_>, ) -> Result, SseError> { - validate_sse_headers_for_write( - request.server_side_encryption.as_deref(), - request.ssekms_key_id.as_ref(), - request.ssekms_context.as_ref(), - request.sse_customer_algorithm.as_ref(), - request.sse_customer_key.as_ref(), - request.sse_customer_key_md5.as_ref(), - true, - )?; - - let sse_type = prepare_sse_configuration_v2( + let scheme = resolve_write_scheme( host, request.bucket, - request.server_side_encryption, - request.sse_customer_algorithm, - request.sse_customer_key.clone(), - request.sse_customer_key_md5, - request.ssekms_key_id, + WriteSchemeHeaders { + server_side_encryption: request.server_side_encryption, + ssekms_key_id: request.ssekms_key_id, + ssekms_context: request.ssekms_context.as_ref(), + sse_customer_algorithm: request.sse_customer_algorithm, + sse_customer_key: request.sse_customer_key, + sse_customer_key_md5: request.sse_customer_key_md5, + }, ) .await?; - // apply encryption material - let material = match sse_type { - Some(SseTypeV2::SseS3(sse)) => { - apply_managed_encryption_material( - host, - ManagedEncryptionRequest { - bucket: request.bucket, - key: request.key, - server_side_encryption: sse, - kms_key_id: None, - ssekms_context: request.ssekms_context, - content_size: 0, - principal: request.principal, - }, - ) - .await? - } - Some(SseTypeV2::SseKms(sse, kms_key_id)) => { - apply_managed_encryption_material( - host, - ManagedEncryptionRequest { - bucket: request.bucket, - key: request.key, - server_side_encryption: sse, - kms_key_id, - ssekms_context: request.ssekms_context, - content_size: 0, - principal: request.principal, - }, - ) - .await? - } - Some(SseTypeV2::SseC(algorithm, _, key_md5)) => { - apply_ssec_prepare_encryption_material(request.bucket, request.key, algorithm, request.sse_customer_key, key_md5) - .await? - } + let (server_side_encryption, kms_key_id) = match scheme { None => return Ok(None), + Some(WriteScheme::SseC { algorithm, key, key_md5 }) => { + return apply_ssec_prepare_encryption_material(request.bucket, request.key, algorithm, Some(key), key_md5) + .await + .map(Some); + } + Some(WriteScheme::SseS3) => (String::from(AMZ_ENCRYPTION_AES), None), + Some(WriteScheme::SseKms { key_id }) => (String::from(AMZ_ENCRYPTION_KMS), key_id), }; - Ok(Some(material)) + // A session records no plaintext size: the parts decide it. + apply_managed_encryption_material( + host, + ManagedEncryptionRequest { + bucket: request.bucket, + key: request.key, + server_side_encryption, + kms_key_id, + ssekms_context: request.ssekms_context, + content_size: 0, + principal: request.principal, + }, + ) + .await + .map(Some) } async fn apply_ssec_prepare_encryption_material( @@ -327,47 +299,35 @@ async fn apply_ssec_prepare_encryption_material( sse_key: Option, sse_key_md5: String, ) -> Result { - #[cfg(feature = "rio-v2")] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = if let Some(sse_key) = sse_key { - let validated = validate_ssec_params(SsecParams { - algorithm: algorithm.clone(), - key: sse_key, - key_md5: sse_key_md5.clone(), - })?; - let object_key = derive_object_key(validated.key_bytes)?; - let sealed_key = seal_object_key(object_key, validated.key_bytes, SSEType::SseC, bucket, key)?; - (object_key, [0; 12], EncryptionKeyKind::Object, Some(sealed_key)) - } else { - ([0; 32], [0; 12], EncryptionKeyKind::Direct, None) - }; - - #[cfg(not(feature = "rio-v2"))] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = { - let _ = (bucket, key, sse_key); - // Generate a real random nonce for the multipart session and persist it (see - // `encryption_material_to_metadata`). Every part of this upload reads the same - // persisted nonce back via `apply_ssec_decryption_material`, so all parts share one - // nonce without reintroducing the deterministic (bucket, key) reuse hazard. - // key_bytes stays a placeholder here: it is neither used for encryption nor persisted; - // the real customer key is validated per part on upload. - let mut base_nonce = [0u8; 12]; - rand::rng().fill_bytes(&mut base_nonce); - ([0; 32], base_nonce, EncryptionKeyKind::Direct, None) + // The customer key is validated here only in a mode that seals the session's + // key under it. Otherwise it is validated per part, against what the session + // records. + let customer_key = match sse_key { + Some(sse_key) if SESSION_KEY_NEEDS_CUSTOMER_KEY => Some( + validate_ssec_params(SsecParams { + algorithm: algorithm.clone(), + key: sse_key, + key_md5: sse_key_md5.clone(), + })? + .key_bytes, + ), + _ => None, }; + let object_key = new_session_key_under_customer_key(customer_key, bucket, key)?; Ok(EncryptionMaterial { sse_type: SSEType::SseC, server_side_encryption: String::from(AMZ_ENCRYPTION_AES), kms_key_id: None, algorithm, - key_bytes, - base_nonce, + key_bytes: object_key.key_bytes, + base_nonce: object_key.base_nonce, encrypted_data_key: None, customer_key_md5: Some(sse_key_md5), original_size: None, - key_kind, + key_kind: object_key.key_kind, managed_kms_context: None, - managed_sealed_key, + managed_sealed_key: object_key.sealed_key, }) } @@ -386,26 +346,7 @@ async fn apply_ssec_encryption_material( }; let validated = validate_ssec_params(params)?; - - #[cfg(feature = "rio-v2")] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = { - let object_key = derive_object_key(validated.key_bytes)?; - let sealed_key = seal_object_key(object_key, validated.key_bytes, SSEType::SseC, bucket, key)?; - (object_key, [0; 12], EncryptionKeyKind::Object, Some(sealed_key)) - }; - - #[cfg(not(feature = "rio-v2"))] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = { - // Use a fresh random nonce per encryption. A deterministic nonce derived from - // (bucket, key) would repeat whenever the same object is overwritten under the same - // SSE-C key, reusing an identical (key, nonce) pair and catastrophically breaking - // AES-256-GCM. The nonce is persisted (see `encryption_material_to_metadata`) and read - // back on decrypt (see `apply_ssec_decryption_material`). - let _ = (bucket, key); - let mut base_nonce = [0u8; 12]; - rand::rng().fill_bytes(&mut base_nonce); - (validated.key_bytes, base_nonce, EncryptionKeyKind::Direct, None) - }; + let object_key = new_key_under_customer_key(validated.key_bytes, bucket, key)?; // Build metadata Ok(EncryptionMaterial { @@ -413,14 +354,14 @@ async fn apply_ssec_encryption_material( server_side_encryption: String::from(AMZ_ENCRYPTION_AES), kms_key_id: None, algorithm: validated.algorithm, - key_bytes, - base_nonce, + key_bytes: object_key.key_bytes, + base_nonce: object_key.base_nonce, encrypted_data_key: None, customer_key_md5: Some(validated.key_md5), original_size: Some(content_size), - key_kind, + key_kind: object_key.key_kind, managed_kms_context: None, - managed_sealed_key, + managed_sealed_key: object_key.sealed_key, }) } @@ -568,30 +509,21 @@ pub(crate) async fn apply_managed_encryption_material_inner( let (data_key, encrypted_data_key) = provider.generate_sse_dek(&object_context, &kms_key_to_use).await?; let algorithm = server_side_encryption.as_str().to_string(); - #[cfg(feature = "rio-v2")] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = { - let object_key = derive_object_key(data_key.plaintext_key)?; - let sealed_key = seal_object_key(object_key, data_key.plaintext_key, encryption_type, bucket, key)?; - (object_key, [0u8; 12], EncryptionKeyKind::Object, Some(sealed_key)) - }; - - #[cfg(not(feature = "rio-v2"))] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = - (data_key.plaintext_key, data_key.nonce, EncryptionKeyKind::Direct, None); + let object_key = new_key_under_data_key(&data_key, encryption_type, bucket, key)?; Ok(EncryptionMaterial { sse_type: encryption_type, server_side_encryption, kms_key_id: Some(kms_key_to_use), algorithm, - key_bytes, - base_nonce, + key_bytes: object_key.key_bytes, + base_nonce: object_key.base_nonce, encrypted_data_key: Some(encrypted_data_key), customer_key_md5: None, original_size: Some(content_size), - key_kind, + key_kind: object_key.key_kind, managed_kms_context: matches!(encryption_type, SSEType::SseKms).then_some(ssekms_context.unwrap_or_default()), - managed_sealed_key, + managed_sealed_key: object_key.sealed_key, }) } diff --git a/crates/sse/src/lib.rs b/crates/sse/src/lib.rs index 33ccba9878..d77cb5fc86 100644 --- a/crates/sse/src/lib.rs +++ b/crates/sse/src/lib.rs @@ -90,7 +90,7 @@ pub use crate::core::s3::headers::{ extract_ssec_params_from_headers, extract_ssekms_context_from_headers, project_sse_read_response_headers, validate_sse_headers_for_read, validate_sse_headers_for_write, }; -pub use crate::core::s3::scheme::{DEFAULT_SSE_ALGORITHM, SseTypeV2, bucket_default_write_sse}; +pub use crate::core::s3::scheme::{DEFAULT_SSE_ALGORITHM, bucket_default_write_sse}; pub use crate::core::s3::ssec::{ssec_invalid_request, validate_ssec_for_read}; pub use crate::core::write::{EncryptionRequest, PrepareEncryptionRequest, sse_encryption, sse_prepare_encryption}; pub use crate::error::{KMS_KEY_NOT_FOUND_ERROR_CODE, SseError, data_plane_kms_error}; diff --git a/crates/sse/src/tests.rs b/crates/sse/src/tests.rs index a7a20d08e2..2037cb7a26 100644 --- a/crates/sse/src/tests.rs +++ b/crates/sse/src/tests.rs @@ -1127,11 +1127,11 @@ fn native_material_debug_withholds_decryption_keys() { #[test] fn native_material_debug_withholds_customer_key() { - let material = crate::core::s3::scheme::SseTypeV2::SseC( - "AES256".to_owned(), - "fixture-key-must-stay-private".to_owned(), - "fixture-md5".to_owned(), - ); + let material = crate::core::s3::scheme::WriteScheme::SseC { + algorithm: "AES256".to_owned(), + key: "fixture-key-must-stay-private".to_owned(), + key_md5: "fixture-md5".to_owned(), + }; let diagnostic = format!("{material:?}"); assert!( !diagnostic.contains("fixture-key-must-stay-private"),