mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-23 08:27:14 +00:00
Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 750857107d | |||
| 7cda3692a6 | |||
| ae76752259 | |||
| e8144e896f | |||
| 7570d8a62d | |||
| 6eb6543192 | |||
| 857fc34af9 | |||
| 7e8e8cad23 | |||
| 18135434a7 | |||
| 7dc759f9cf | |||
| 29921163e3 | |||
| f17da41507 | |||
| 7e1b3843f5 | |||
| aff99bbdb2 | |||
| 856a270717 | |||
| 3c39a94388 | |||
| 0deff550aa | |||
| f41b022017 | |||
| 66d727279b | |||
| a8b4367c5f | |||
| b9d3aea1a5 | |||
| f034e3701b | |||
| 67e29c2143 | |||
| d6677ac005 | |||
| 40f4e5e1e2 |
@@ -57,7 +57,6 @@ rustfs-scanner 1392 20
|
||||
rustfs-scanner-metrics 90 0
|
||||
rustfs-security-governance 20 0
|
||||
rustfs-signer 34 0
|
||||
rustfs-sse 145 0
|
||||
rustfs-storage-api 34 0
|
||||
rustfs-targets 612 26
|
||||
rustfs-test-utils 1 0
|
||||
|
||||
@@ -231,7 +231,7 @@ jobs:
|
||||
# --all-targets links the same test binaries as the reader lane.
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
run: |
|
||||
cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2
|
||||
cargo build -p rustfs -p rustfs-ecstore --all-targets --features rio-v2
|
||||
cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
|
||||
|
||||
# Readers: the swift and sftp legs of test-and-lint-protocols. Built in
|
||||
|
||||
@@ -563,7 +563,7 @@ jobs:
|
||||
run: chmod go-w "$(realpath "$HOME")"
|
||||
|
||||
- name: Run rio-v2 clippy lints
|
||||
run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2 -- -D warnings
|
||||
run: cargo clippy -p rustfs -p rustfs-ecstore --all-targets --features rio-v2 -- -D warnings
|
||||
|
||||
- name: Run rio-v2 feature tests
|
||||
shell: bash
|
||||
@@ -580,7 +580,7 @@ jobs:
|
||||
rm -f target/nextest/ci/junit.xml
|
||||
./scripts/ci/resource_sampler.sh start nextest-rio-v2
|
||||
trap './scripts/ci/resource_sampler.sh stop' EXIT
|
||||
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \
|
||||
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore --features rio-v2 \
|
||||
2>&1 | tee artifacts/workspace/nextest.log
|
||||
cargo test -p rustfs --doc --features rio-v2
|
||||
|
||||
|
||||
+1
-1
@@ -94,7 +94,7 @@ refactors.
|
||||
|--------|--------------------------|----------------|
|
||||
| Foundation | `checksums`, `common`, `config`, `data-usage`, `heal-contracts`, `scanner-metrics`, `utils` | Shared configuration, data-usage models, heal domain contracts, scanner telemetry types, utilities, and checksums. |
|
||||
| I/O and storage | `concurrency`, `ecstore`, `filemeta`, `heal`, `io-core`, `io-metrics`, `lifecycle`, `lock`, `object-capacity`, `object-data-cache`, `replication`, `rio`, `rio-v2`, `s3-client`, `scanner`, `storage-api` | Erasure-coded object storage, metadata, recovery, lifecycle, replication, locking, cache, I/O pipelines, and the engine-side S3 client for remote tier/transition targets. |
|
||||
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `sse`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, server-side encryption key resolution, TLS, and security contracts. |
|
||||
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, TLS, and security contracts. |
|
||||
| Protocols and contracts | `extension-schema`, `madmin`, `protos`, `protocols`, `s3-ops`, `s3-types`, `s3select-api`, `s3select-query` | Admin, inter-node, S3, S3 Select, and optional protocol contracts. |
|
||||
| Operations and integration | `audit`, `notify`, `obs`, `targets`, `zip` | Auditing, observability, event delivery, notification targets, and archive support. |
|
||||
| Test support | `e2e_test`, `test-utils` | End-to-end validation and shared test bootstrap utilities. |
|
||||
|
||||
@@ -118,7 +118,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Four-layer regression-prevention tests guard against silent feature deletion: compile-time module assertion, module-presence unit test, cross-module `Protocol` enum assertion, end-to-end SSH banner test against the running binary
|
||||
|
||||
### Changed
|
||||
- **Startup reports the state of `RUSTFS_SSE_S3_MASTER_KEY`**: the server now checks the local SSE-S3 master key when it starts and logs one `sse_local_master_key` event with `state` `loaded`, `not_set`, or `invalid`. An unusable value used to surface only as a `400 InvalidRequest` on the first SSE-S3 request served without a KMS; it is now logged as an error at startup with the reason. Startup still succeeds and request behavior is unchanged. The line "Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3 (KMS not configured)", logged when the key was first used, is replaced by this event.
|
||||
- **Scanner bucket walkers are no longer tied to the disk count**: a new scanner key `walkers_per_disk` (`RUSTFS_SCANNER_WALKERS_PER_DISK`, `1` through `16`, default `1`) spawns that many bucket walkers per local disk of an erasure set, so a single-disk deployment can walk several buckets at once instead of one bucket, one object at a time. The walkers of one disk share its scanner admission, so a peer still sees one scan session per physical disk, and remote disks keep one walker. The walker count is what `max_concurrent_disk_scans` caps and the disk count stays the floor; the `disk_concurrency_budget` log line now reports `walkers_per_disk`, `walkers`, and the `reason` for the effective limit. The default keeps today's I/O profile because a local disk cannot yet report whether it is rotational; the design intends a higher default on flash once it can (`docs/architecture/scanner-per-bucket-convergence.md`). As groundwork for pacing, the raw-enumeration page writer inserts into its building page in place and commits pages without copying them, and a regression test pins the cost of recording 20,000 entries in one prefix so the quadratic bookkeeping removed by [#8114](https://github.com/rustfs/rustfs/pull/8114) (rustfs#8113) cannot return. No persisted format, protocol or admin API changes beyond the additional config key, which older releases preserve and ignore.
|
||||
- **Encryption and KMS work merged since `1.0.0-rc.5`** (entries were missing from this section):
|
||||
- **Persisted KMS configuration secrets** are sealed field-by-field with `RUSTFS_KMS_CONFIG_SECRET`. **When the variable is unset the secrets are persisted in cleartext and the server only warns** (`persisted KMS configuration carries cleartext secrets`); it never refuses the write. Set it, identically, on every node, and re-save the configuration to seal an existing one.
|
||||
|
||||
Generated
-28
@@ -10022,7 +10022,6 @@ dependencies = [
|
||||
"rustfs-scanner-metrics",
|
||||
"rustfs-security-governance",
|
||||
"rustfs-signer",
|
||||
"rustfs-sse",
|
||||
"rustfs-storage-api",
|
||||
"rustfs-targets",
|
||||
"rustfs-test-utils",
|
||||
@@ -11505,33 +11504,6 @@ dependencies = [
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-sse"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64-simd",
|
||||
"chacha20poly1305",
|
||||
"hmac 0.13.0",
|
||||
"http 1.5.0",
|
||||
"md-5",
|
||||
"rand 0.10.4",
|
||||
"rustfs-config",
|
||||
"rustfs-kms",
|
||||
"rustfs-policy",
|
||||
"rustfs-s3-types",
|
||||
"rustfs-utils",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.1",
|
||||
"temp-env",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-storage-api"
|
||||
version = "1.0.5"
|
||||
|
||||
@@ -61,7 +61,6 @@ members = [
|
||||
"crates/security-governance", # Security governance contracts
|
||||
"crates/extension-schema", # Extension schema contracts
|
||||
"crates/signer", # client signer
|
||||
"crates/sse", # S3 server-side encryption key resolution and metadata
|
||||
"crates/storage-api", # Storage API contracts
|
||||
"crates/test-utils", # Shared test bootstrap helpers (dev-dependency only)
|
||||
"crates/targets", # Target-specific configurations and utilities
|
||||
@@ -143,7 +142,6 @@ rustfs-scanner = { path = "crates/scanner", version = "1.0.5" }
|
||||
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.5" }
|
||||
rustfs-extension-schema = { path = "crates/extension-schema", version = "1.0.5" }
|
||||
rustfs-signer = { path = "crates/signer", version = "1.0.5" }
|
||||
rustfs-sse = { path = "crates/sse", version = "1.0.5" }
|
||||
rustfs-storage-api = { path = "crates/storage-api", version = "1.0.5" }
|
||||
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.5" }
|
||||
rustfs-targets = { path = "crates/targets", version = "1.0.5" }
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
// limitations under the License.
|
||||
|
||||
pub mod data_usage;
|
||||
pub mod scan_progress;
|
||||
pub mod usage_observation;
|
||||
|
||||
pub use data_usage::*;
|
||||
pub use scan_progress::*;
|
||||
pub use usage_observation::*;
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
//! Display-only scanner progress. These values never authorize quota admission,
|
||||
//! cache reuse, or publication of a certified usage snapshot.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub const BUCKET_SCAN_PROGRESS_VERSION: u16 = 1;
|
||||
pub const BUCKET_SCAN_PROGRESS_MAX_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// The object lives on its contributing erasure set, alongside its bucket cache.
|
||||
pub fn bucket_scan_progress_path(bucket: &str) -> String {
|
||||
format!("buckets/{bucket}/.usage-progress.json")
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum BucketScanStage {
|
||||
Enumerating,
|
||||
Scanning,
|
||||
AwaitingSources,
|
||||
Completed,
|
||||
}
|
||||
|
||||
/// One replaceable sample from a logical erasure set, never a per-disk delta.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct BucketScanProgressSource {
|
||||
pub version: u16,
|
||||
pub bucket: String,
|
||||
pub bucket_incarnation: String,
|
||||
pub pool_index: u64,
|
||||
pub set_index: u64,
|
||||
pub set_layout: [u8; 32],
|
||||
pub publication_epoch: u64,
|
||||
/// Shared durable movement scope. A writer's local admission epoch is not
|
||||
/// comparable to another node's counter, including after restart.
|
||||
#[serde(default)]
|
||||
pub movement_generation: Option<u64>,
|
||||
pub scanner_epoch: u64,
|
||||
pub scanner_cycle: u64,
|
||||
/// Unix milliseconds of the sample, preserved when an older sample is carried.
|
||||
pub updated_at: u64,
|
||||
pub stage: BucketScanStage,
|
||||
/// Accepted logical object usage; enumeration alone leaves both absent.
|
||||
pub objects: Option<u64>,
|
||||
pub size: Option<u64>,
|
||||
}
|
||||
|
||||
/// Response-only progress, deliberately separate from a bucket's total usage.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct BucketScanProgress {
|
||||
pub stage: BucketScanStage,
|
||||
pub updated_at: u64,
|
||||
pub objects: Option<u64>,
|
||||
pub size: Option<u64>,
|
||||
pub sources_observed: u64,
|
||||
pub sources_total: u64,
|
||||
}
|
||||
|
||||
impl BucketScanProgressSource {
|
||||
/// Bind a sample to shared storage scope, independently of reader-local epochs.
|
||||
pub fn matches(&self, bucket: &str, incarnation: &str, source: (u64, u64), movement_generation: u64) -> bool {
|
||||
self.version == BUCKET_SCAN_PROGRESS_VERSION
|
||||
&& self.bucket == bucket
|
||||
&& !incarnation.is_empty()
|
||||
&& incarnation != "00000000-0000-0000-0000-000000000000"
|
||||
&& self.bucket_incarnation == incarnation
|
||||
&& (self.pool_index, self.set_index) == source
|
||||
&& self.movement_generation == Some(movement_generation)
|
||||
&& self.updated_at > 0
|
||||
&& self.objects.is_some() == self.size.is_some()
|
||||
&& (self.stage != BucketScanStage::Completed || self.objects.is_some())
|
||||
&& self.stage != BucketScanStage::AwaitingSources
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold each logical source exactly once. Retries replace samples; replicas do
|
||||
/// not add to them. Missing sources remain explicit, including on first startup.
|
||||
/// Overflow or conflicting copies of a source make the view unavailable.
|
||||
/// Callers first bind each sample to the same current bucket and movement
|
||||
/// scope with [`BucketScanProgressSource::matches`].
|
||||
pub fn aggregate_bucket_scan_progress(
|
||||
sources: impl IntoIterator<Item = BucketScanProgressSource>,
|
||||
expected: &[(u64, u64)],
|
||||
) -> Option<BucketScanProgress> {
|
||||
if expected.is_empty() || expected.windows(2).any(|pair| pair[0] >= pair[1]) {
|
||||
return None;
|
||||
}
|
||||
let mut selected = BTreeMap::new();
|
||||
for sample in sources {
|
||||
let key = (sample.pool_index, sample.set_index);
|
||||
if expected.binary_search(&key).is_err() {
|
||||
return None;
|
||||
}
|
||||
if let Some(previous) = selected.insert(key, sample.clone())
|
||||
&& previous != sample
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let updated_at = selected.values().map(|sample| sample.updated_at).min()?;
|
||||
let mut objects = None;
|
||||
let mut size = None;
|
||||
for sample in selected.values() {
|
||||
match (sample.objects, sample.size) {
|
||||
(Some(count), Some(bytes)) => {
|
||||
objects = Some(objects.unwrap_or(0_u64).checked_add(count)?);
|
||||
size = Some(size.unwrap_or(0_u64).checked_add(bytes)?);
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
let complete = selected.len() == expected.len() && selected.values().all(|s| s.stage == BucketScanStage::Completed);
|
||||
Some(BucketScanProgress {
|
||||
stage: if complete {
|
||||
BucketScanStage::Completed
|
||||
} else if selected.len() < expected.len() {
|
||||
BucketScanStage::AwaitingSources
|
||||
} else if objects.is_some() {
|
||||
BucketScanStage::Scanning
|
||||
} else {
|
||||
BucketScanStage::Enumerating
|
||||
},
|
||||
updated_at,
|
||||
objects,
|
||||
size,
|
||||
sources_observed: u64::try_from(selected.len()).ok()?,
|
||||
sources_total: u64::try_from(expected.len()).ok()?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample(set: u64) -> BucketScanProgressSource {
|
||||
BucketScanProgressSource {
|
||||
version: BUCKET_SCAN_PROGRESS_VERSION,
|
||||
bucket: "bucket".into(),
|
||||
bucket_incarnation: "identity".into(),
|
||||
pool_index: 0,
|
||||
set_index: set,
|
||||
set_layout: [1; 32],
|
||||
publication_epoch: 0,
|
||||
movement_generation: Some(0),
|
||||
scanner_epoch: 3,
|
||||
scanner_cycle: 4,
|
||||
updated_at: 1000,
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(77),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_source_samples_never_double_count() {
|
||||
let one = sample(0);
|
||||
let progress = aggregate_bucket_scan_progress([one.clone(), one], &[(0, 0), (0, 1)]).expect("partial progress");
|
||||
assert_eq!(progress.objects, Some(7));
|
||||
assert_eq!(progress.size, Some(77));
|
||||
assert_eq!(progress.stage, BucketScanStage::AwaitingSources);
|
||||
assert_eq!(progress.sources_observed, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enumeration_does_not_invent_empty_usage() {
|
||||
let mut one = sample(0);
|
||||
one.stage = BucketScanStage::Enumerating;
|
||||
one.objects = None;
|
||||
one.size = None;
|
||||
let progress = aggregate_bucket_scan_progress([one], &[(0, 0)]).expect("enumeration progress");
|
||||
assert_eq!(progress.objects, None);
|
||||
assert_eq!(progress.size, None);
|
||||
assert_eq!(progress.stage, BucketScanStage::Enumerating);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_requires_every_source_and_keeps_oldest_timestamp() {
|
||||
let mut one = sample(0);
|
||||
one.stage = BucketScanStage::Completed;
|
||||
let mut two = sample(1);
|
||||
two.updated_at = 2000;
|
||||
let pending = aggregate_bucket_scan_progress([one.clone(), two.clone()], &[(0, 0), (0, 1)]).expect("pending");
|
||||
assert_eq!(pending.stage, BucketScanStage::Scanning);
|
||||
two.stage = BucketScanStage::Completed;
|
||||
let done = aggregate_bucket_scan_progress([one, two], &[(0, 0), (0, 1)]).expect("completed");
|
||||
assert_eq!((done.objects, done.size, done.updated_at), (Some(14), Some(154), 1000));
|
||||
assert_eq!(done.stage, BucketScanStage::Completed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_replicas_overflow_and_foreign_sources_are_rejected() {
|
||||
let mut other = sample(0);
|
||||
other.objects = Some(8);
|
||||
assert!(aggregate_bucket_scan_progress([sample(0), other], &[(0, 0)]).is_none());
|
||||
assert!(aggregate_bucket_scan_progress([sample(1)], &[(0, 0)]).is_none());
|
||||
let mut huge = sample(1);
|
||||
huge.size = Some(u64::MAX);
|
||||
assert!(aggregate_bucket_scan_progress([sample(0), huge], &[(0, 0), (0, 1)]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_cannot_cross_bucket_incarnation_or_movement_generation() {
|
||||
let one = sample(0);
|
||||
assert!(one.matches("bucket", "identity", (0, 0), 0));
|
||||
assert!(!one.matches("bucket", "recreated", (0, 0), 0));
|
||||
assert!(!one.matches("bucket", "identity", (0, 1), 0));
|
||||
assert!(!one.matches("bucket", "identity", (0, 0), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_reader_local_epoch_does_not_hide_shared_sample() {
|
||||
let mut one = sample(0);
|
||||
one.publication_epoch = 7;
|
||||
assert!(one.matches("bucket", "identity", (0, 0), 0));
|
||||
one.movement_generation = None;
|
||||
assert!(!one.matches("bucket", "identity", (0, 0), 0), "missing shared scope stays unknown");
|
||||
}
|
||||
}
|
||||
@@ -455,10 +455,10 @@ pub mod data_usage {
|
||||
DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage,
|
||||
init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache,
|
||||
invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached,
|
||||
load_admin_data_usage_with_memory_overlay, load_bucket_usage_from_backend_cached, load_compression_total_from_memory,
|
||||
load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
|
||||
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
|
||||
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
|
||||
load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin, load_bucket_usage_from_backend_cached,
|
||||
load_compression_total_from_memory, load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size,
|
||||
record_bucket_delete_marker_memory, record_bucket_object_delete_memory, record_bucket_object_version_write_memory,
|
||||
record_bucket_object_write_memory, record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
|
||||
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
|
||||
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
|
||||
store_data_usage_in_backend, verified_account_bucket_usage,
|
||||
|
||||
@@ -18,6 +18,8 @@ mod admin_bucket_identity;
|
||||
pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
|
||||
pub use admin_bucket_identity::verified_account_bucket_usage;
|
||||
pub mod local_snapshot;
|
||||
mod scan_progress;
|
||||
pub use scan_progress::load_bucket_scan_progress_for_admin;
|
||||
|
||||
use crate::storage_api_contracts::{
|
||||
bucket::{BucketOperations as _, BucketOptions},
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
use super::*;
|
||||
use crate::set_disk::SetDisks;
|
||||
use futures::{StreamExt, stream::BoxStream};
|
||||
use rustfs_data_usage::{
|
||||
BUCKET_SCAN_PROGRESS_MAX_BYTES, BucketScanProgress, BucketScanProgressSource, aggregate_bucket_scan_progress,
|
||||
bucket_scan_progress_path,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
type ProgressEvent = (String, BucketScanProgressSource);
|
||||
|
||||
async fn collect_progress_until<S: futures::Stream + Unpin>(deadline: tokio::time::Instant, mut stream: S) -> Vec<S::Item> {
|
||||
let mut collected = Vec::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = tokio::time::sleep_until(deadline) => break,
|
||||
item = stream.next() => match item {
|
||||
Some(item) => collected.push(item),
|
||||
None => break,
|
||||
},
|
||||
}
|
||||
}
|
||||
collected
|
||||
}
|
||||
|
||||
/// Read compact checkpoint companions only for the caller's authorized buckets.
|
||||
///
|
||||
/// These diagnostics cannot seed usage caches or authorize quotas. The request
|
||||
/// has a two-second deadline, reserving its last quarter for final movement-scope
|
||||
/// validation. Completed source reads survive stalled peers or buckets. Dropping
|
||||
/// the request cancels reads; it never lists objects or loads full scanner caches.
|
||||
pub async fn load_bucket_scan_progress_for_admin(
|
||||
store: Arc<ECStore>,
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
|
||||
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn bucket_progress_sources(
|
||||
store: Arc<ECStore>,
|
||||
bucket: String,
|
||||
sets: Arc<Vec<Arc<SetDisks>>>,
|
||||
movement_generation: u64,
|
||||
) -> BoxStream<'static, ProgressEvent> {
|
||||
let Some(incarnation) = store
|
||||
.bucket_incarnation_id_from_disk(&bucket)
|
||||
.await
|
||||
.ok()
|
||||
.filter(|id| !id.is_nil())
|
||||
else {
|
||||
return futures::stream::empty().boxed();
|
||||
};
|
||||
let incarnation = incarnation.to_string();
|
||||
let path = bucket_scan_progress_path(&bucket);
|
||||
futures::stream::iter(0..sets.len())
|
||||
.map(move |index| {
|
||||
let set = sets[index].clone();
|
||||
let bucket = bucket.clone();
|
||||
let incarnation = incarnation.clone();
|
||||
let path = path.clone();
|
||||
async move {
|
||||
let bytes = crate::config::com::read_config_limited(set.clone(), &path, BUCKET_SCAN_PROGRESS_MAX_BYTES)
|
||||
.await
|
||||
.ok()?;
|
||||
let sample: BucketScanProgressSource = serde_json::from_slice(&bytes).ok()?;
|
||||
let source = (u64::try_from(set.pool_index).ok()?, u64::try_from(set.set_index).ok()?);
|
||||
let disks = set.format.erasure.sets.get(set.set_index).filter(|disks| !disks.is_empty())?;
|
||||
if set.format.id.is_nil() || disks.iter().any(uuid::Uuid::is_nil) {
|
||||
return None;
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(set.format.id.as_bytes());
|
||||
for disk in disks {
|
||||
digest.update(disk.as_bytes());
|
||||
}
|
||||
let layout: [u8; 32] = digest.finalize().into();
|
||||
(sample.matches(&bucket, &incarnation, source, movement_generation) && sample.set_layout == layout)
|
||||
.then_some((bucket, sample))
|
||||
}
|
||||
})
|
||||
.buffer_unordered(4)
|
||||
.filter_map(futures::future::ready)
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn project_progress_samples(
|
||||
samples: Vec<ProgressEvent>,
|
||||
expected: &[(u64, u64)],
|
||||
baseline: &DataUsageInfo,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let mut buckets = HashMap::<String, Vec<BucketScanProgressSource>>::new();
|
||||
for (bucket, sample) in samples {
|
||||
buckets.entry(bucket).or_default().push(sample);
|
||||
}
|
||||
buckets
|
||||
.into_iter()
|
||||
.filter_map(|(bucket, samples)| {
|
||||
if let Some(certification) = baseline
|
||||
.buckets_usage
|
||||
.get(&bucket)
|
||||
.and_then(|usage| usage.usage_certification)
|
||||
&& samples
|
||||
.iter()
|
||||
.all(|sample| (sample.scanner_epoch, sample.scanner_cycle) <= (certification.epoch, certification.cycle))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((bucket, aggregate_bucket_scan_progress(samples, expected)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn load_progress(
|
||||
store: Arc<ECStore>,
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
read_deadline: tokio::time::Instant,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let Some(epoch) = store.scanner_data_usage_publication_epoch().await else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let Some(movement_generation) = store.scanner_durable_data_movement_generation().await else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let sets = Arc::new(store.all_set_disks());
|
||||
let mut expected = Vec::with_capacity(sets.len());
|
||||
for set in sets.iter() {
|
||||
let (Ok(pool), Ok(index)) = (u64::try_from(set.pool_index), u64::try_from(set.set_index)) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
expected.push((pool, index));
|
||||
}
|
||||
expected.sort_unstable();
|
||||
if expected.windows(2).any(|pair| pair[0] >= pair[1]) {
|
||||
return HashMap::new();
|
||||
}
|
||||
// Emit each validated source immediately. A bucket waiting for another
|
||||
// source must not hide its healthy sample behind a whole-bucket future.
|
||||
let work = futures::stream::iter(buckets.iter().cloned())
|
||||
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
|
||||
.buffer_unordered(4)
|
||||
.flatten_unordered(4);
|
||||
let samples = collect_progress_until(read_deadline, work).await;
|
||||
let progress = project_progress_samples(samples, &expected, baseline);
|
||||
if store.scanner_data_usage_publication_epoch().await != Some(epoch)
|
||||
|| store.scanner_durable_data_movement_generation().await != Some(movement_generation)
|
||||
{
|
||||
return HashMap::new();
|
||||
}
|
||||
progress
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
|
||||
use crate::config::com::save_config;
|
||||
use crate::storage_api_contracts::bucket::MakeBucketOptions;
|
||||
use rustfs_data_usage::{BUCKET_SCAN_PROGRESS_VERSION, BucketScanStage};
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn display_progress_deadline_preserves_successes_beside_a_stalled_source() {
|
||||
use futures::FutureExt;
|
||||
let stream = futures::stream::iter([
|
||||
futures::future::ready(("partial", 7)).boxed(),
|
||||
futures::future::pending().boxed(),
|
||||
futures::future::ready(("healthy", 9)).boxed(),
|
||||
])
|
||||
.buffer_unordered(3);
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
let collected = collect_progress_until(deadline, stream).await;
|
||||
assert_eq!(collected.len(), 2, "a slow source must not erase completed samples or buckets");
|
||||
assert!(collected.contains(&("partial", 7)));
|
||||
assert!(collected.contains(&("healthy", 9)));
|
||||
assert_eq!(tokio::time::Instant::now(), deadline);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn display_progress_deadline_keeps_partial_sources_and_complete_buckets() {
|
||||
use futures::FutureExt;
|
||||
let sample = |bucket: &str, set_index, objects, complete| BucketScanProgressSource {
|
||||
version: BUCKET_SCAN_PROGRESS_VERSION,
|
||||
bucket: bucket.into(),
|
||||
bucket_incarnation: uuid::Uuid::from_u128(1).to_string(),
|
||||
pool_index: 0,
|
||||
set_index,
|
||||
set_layout: [1; 32],
|
||||
publication_epoch: 0,
|
||||
movement_generation: Some(0),
|
||||
scanner_epoch: 9,
|
||||
scanner_cycle: 11,
|
||||
updated_at: 1000,
|
||||
stage: if complete {
|
||||
BucketScanStage::Completed
|
||||
} else {
|
||||
BucketScanStage::Scanning
|
||||
},
|
||||
objects: Some(objects),
|
||||
size: Some(objects * 11),
|
||||
};
|
||||
let partial: BoxStream<'static, ProgressEvent> = futures::stream::iter([
|
||||
futures::future::ready(("partial".into(), sample("partial", 0, 7, false))).boxed(),
|
||||
futures::future::pending().boxed(),
|
||||
])
|
||||
.buffer_unordered(2)
|
||||
.boxed();
|
||||
let healthy: BoxStream<'static, ProgressEvent> = futures::stream::iter([
|
||||
("healthy".into(), sample("healthy", 0, 2, true)),
|
||||
("healthy".into(), sample("healthy", 1, 3, true)),
|
||||
])
|
||||
.boxed();
|
||||
// The third bucket never resolves its identity; one source of the
|
||||
// first bucket stalls. Neither may hide the other ready events.
|
||||
let events = futures::stream::iter([
|
||||
futures::future::ready(partial).boxed(),
|
||||
futures::future::ready(healthy).boxed(),
|
||||
futures::future::pending().boxed(),
|
||||
])
|
||||
.buffer_unordered(3)
|
||||
.flatten_unordered(3);
|
||||
let baseline = DataUsageInfo::default();
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
let progress = project_progress_samples(collect_progress_until(deadline, events).await, &[(0, 0), (0, 1)], &baseline);
|
||||
assert_eq!(progress.len(), 2);
|
||||
assert_eq!(progress["partial"].stage, BucketScanStage::AwaitingSources);
|
||||
assert_eq!((progress["partial"].objects, progress["partial"].size), (Some(7), Some(77)));
|
||||
assert_eq!((progress["partial"].sources_observed, progress["partial"].sources_total), (1, 2));
|
||||
assert_eq!(progress["healthy"].stage, BucketScanStage::Completed);
|
||||
assert_eq!((progress["healthy"].objects, progress["healthy"].size), (Some(5), Some(55)));
|
||||
assert!(baseline.buckets_usage.is_empty(), "partial diagnostics never seed certified totals");
|
||||
}
|
||||
|
||||
async fn fixture() -> (Vec<tempfile::TempDir>, Arc<ECStore>, BucketScanProgressSource) {
|
||||
let (dirs, store) = isolated_store_over_temp_disks().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
store
|
||||
.make_bucket("progress", &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create progress bucket");
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk("progress")
|
||||
.await
|
||||
.expect("current incarnation");
|
||||
let set = &store.pools[0].disk_set[0];
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(set.format.id.as_bytes());
|
||||
for disk in &set.format.erasure.sets[set.set_index] {
|
||||
digest.update(disk.as_bytes());
|
||||
}
|
||||
let sample = BucketScanProgressSource {
|
||||
version: BUCKET_SCAN_PROGRESS_VERSION,
|
||||
bucket: "progress".into(),
|
||||
bucket_incarnation: incarnation.to_string(),
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
set_layout: digest.finalize().into(),
|
||||
publication_epoch: store.scanner_data_usage_publication_epoch().await.expect("publication epoch"),
|
||||
movement_generation: store.scanner_durable_data_movement_generation().await,
|
||||
scanner_epoch: 9,
|
||||
scanner_cycle: 11,
|
||||
updated_at: 1000,
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(71),
|
||||
};
|
||||
(dirs, store, sample)
|
||||
}
|
||||
|
||||
async fn save(store: &ECStore, sample: &BucketScanProgressSource) {
|
||||
save_config(
|
||||
store.pools[0].disk_set[0].clone(),
|
||||
&bucket_scan_progress_path("progress"),
|
||||
serde_json::to_vec(sample).expect("encode display sample"),
|
||||
)
|
||||
.await
|
||||
.expect("persist display sample on its source set");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn display_progress_reloads_from_shared_storage_without_promoting_usage() {
|
||||
fn assert_send<T: Send>(value: T) -> T {
|
||||
value
|
||||
}
|
||||
let (_dirs, store, mut sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let baseline = DataUsageInfo::default();
|
||||
for _ in 0..3 {
|
||||
let progress = assert_send(load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &baseline)).await;
|
||||
assert_eq!((progress["progress"].objects, progress["progress"].size), (Some(7), Some(71)));
|
||||
assert_eq!(progress["progress"].sources_observed, 1);
|
||||
assert!(baseline.buckets_usage.is_empty(), "display samples never seed exact usage");
|
||||
assert!(!baseline.is_complete_bucket_usage_snapshot());
|
||||
}
|
||||
// Another node/restarted reader may have a different admission epoch
|
||||
// and wakeup count without any persisted movement-state change.
|
||||
let gate = store.ctx.data_movement_operation_gate();
|
||||
let permit = gate.write().await;
|
||||
store.ctx.advance_data_movement_operation_epoch();
|
||||
drop(permit);
|
||||
assert_ne!(store.scanner_data_usage_publication_epoch().await, Some(sample.publication_epoch));
|
||||
assert_ne!(Some(store.scanner_data_movement_generation()), sample.movement_generation);
|
||||
let other_reader = load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &baseline).await;
|
||||
assert_eq!(
|
||||
other_reader["progress"].objects,
|
||||
Some(7),
|
||||
"local reader counters cannot hide shared progress"
|
||||
);
|
||||
sample.scanner_epoch += 1;
|
||||
sample.scanner_cycle += 1;
|
||||
sample.objects = Some(9);
|
||||
sample.size = Some(91);
|
||||
save(&store, &sample).await;
|
||||
let after_handoff = load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &baseline).await;
|
||||
assert_eq!((after_handoff["progress"].objects, after_handoff["progress"].size), (Some(9), Some(91)));
|
||||
assert!(
|
||||
load_bucket_scan_progress_for_admin(store, &[], &baseline).await.is_empty(),
|
||||
"no unauthorized bucket probes"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn display_progress_rejects_retired_identity_layout_epoch_and_corrupt_samples() {
|
||||
let (_dirs, store, sample) = fixture().await;
|
||||
for invalid in 0..6 {
|
||||
let mut stale = sample.clone();
|
||||
match invalid {
|
||||
0 => stale.bucket_incarnation = uuid::Uuid::new_v4().to_string(),
|
||||
1 => stale.set_layout = [0; 32],
|
||||
2 => stale.movement_generation = Some(stale.movement_generation.expect("shared generation") + 1),
|
||||
3 => stale.version += 1,
|
||||
4 => stale.movement_generation = None,
|
||||
_ => stale.size = None,
|
||||
}
|
||||
save(&store, &stale).await;
|
||||
assert!(
|
||||
load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &DataUsageInfo::default())
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
let path = bucket_scan_progress_path("progress");
|
||||
for bytes in [b"invalid json".to_vec(), vec![b' '; BUCKET_SCAN_PROGRESS_MAX_BYTES + 1]] {
|
||||
save_config(store.pools[0].disk_set[0].clone(), &path, bytes)
|
||||
.await
|
||||
.expect("persist malformed diagnostic fixture");
|
||||
assert!(
|
||||
load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &DataUsageInfo::default())
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,11 +229,7 @@ mod tests {
|
||||
super::super::load_server_info_usage_snapshot(store.clone()).await
|
||||
};
|
||||
let (loaded, listing, result) = collect(&store, cold_refresh, store.list_bucket_for_scanner(&options)).await;
|
||||
let loaded = loaded.expect("cold admin snapshot should load");
|
||||
assert!(loaded.usage_snapshot_admin_projection);
|
||||
assert_eq!(loaded.usage_snapshot_converged, Some(false));
|
||||
assert_eq!(loaded.buckets_usage.len(), 1);
|
||||
assert_eq!(loaded.buckets_usage["unchanged"].objects_count, 4);
|
||||
assert_eq!(loaded.unwrap().usage_snapshot_converged, Some(true));
|
||||
assert!(listing.unwrap().topology_complete);
|
||||
assert_eq!(result.current_buckets, Some(3));
|
||||
assert_eq!(result.measured_buckets, Some(1));
|
||||
|
||||
@@ -5657,6 +5657,12 @@ impl SetDisks {
|
||||
crate::bucket::retirement::is_retired(store, bucket, incarnation).await
|
||||
}
|
||||
|
||||
/// Shared durable movement generation used for display-only scan samples.
|
||||
pub async fn scanner_durable_data_movement_generation(&self) -> Option<u64> {
|
||||
let owner = runtime_sources::object_store_handle().filter(|owner| Arc::ptr_eq(&owner.ctx, &self.ctx))?;
|
||||
owner.scanner_durable_data_movement_generation().await
|
||||
}
|
||||
|
||||
/// Admit one short scanner cache publication under this set's instance
|
||||
/// movement fence. The caller must hold the returned guard through its
|
||||
/// final conditional cache write; no scan-round work belongs under it.
|
||||
|
||||
@@ -1021,6 +1021,16 @@ impl ECStore {
|
||||
self.ctx.data_movement_generation()
|
||||
}
|
||||
|
||||
/// Derive the cross-node scope from persisted movement metadata, excluding
|
||||
/// local admission/wakeup counters. Writers capture this under their
|
||||
/// movement permit; diagnostic readers validate it before and after I/O.
|
||||
pub async fn scanner_durable_data_movement_generation(&self) -> Option<u64> {
|
||||
let pool_meta = self.pool_meta.read().await.clone();
|
||||
let rebalance_meta = self.rebalance_meta.read().await.clone();
|
||||
let generation = durable_scanner_data_movement_generation(&pool_meta, rebalance_meta.as_ref());
|
||||
(generation != u64::MAX).then_some(generation)
|
||||
}
|
||||
|
||||
pub fn scanner_data_movement_generation_exhausted(&self) -> bool {
|
||||
self.ctx.data_movement_generation_exhausted()
|
||||
}
|
||||
|
||||
@@ -6,8 +6,7 @@ Applies to `crates/kms/`.
|
||||
|
||||
When changing key-management behavior, verify compatibility with:
|
||||
|
||||
- `crates/sse/` (SSE key resolution; consumes this crate on the data path)
|
||||
- `rustfs/src/storage/sse.rs` (binds `crates/sse/` to the running server)
|
||||
- `rustfs/src/storage/sse.rs`
|
||||
- `rustfs/src/admin/handlers/kms.rs`
|
||||
- `rustfs/src/admin/handlers/kms_dynamic.rs`
|
||||
- `rustfs/src/admin/handlers/kms_keys.rs`
|
||||
|
||||
@@ -411,6 +411,15 @@ pub struct AccountInfo {
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
pub struct BucketAccessInfo {
|
||||
pub name: String,
|
||||
/// Display-only accepted scan progress, never a replacement for total usage.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scan_progress: Option<BucketScanProgress>,
|
||||
/// Value provenance: certified, carried, observed or unknown. Preserve future labels.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_value_state: Option<String>,
|
||||
/// Unix milliseconds of the original complete statistic, when known.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_updated_at: Option<u64>,
|
||||
// Usage stats are absent (not zero) when no scanner snapshot covers the
|
||||
// bucket yet, so clients can distinguish "unknown" from "empty"
|
||||
// (rustfs/backlog#1306).
|
||||
@@ -429,6 +438,20 @@ pub struct BucketAccessInfo {
|
||||
pub access: AccountAccess,
|
||||
}
|
||||
|
||||
/// Accepted scan coverage for display, independent of total usage and quotas.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct BucketScanProgress {
|
||||
/// Observation stage. Clients must preserve unfamiliar diagnostic labels.
|
||||
pub stage: String,
|
||||
/// Oldest contributing measurement time in Unix milliseconds.
|
||||
pub updated_at: u64,
|
||||
/// Enumeration alone leaves both counters absent.
|
||||
pub objects: Option<u64>,
|
||||
pub size: Option<u64>,
|
||||
pub sources_observed: u64,
|
||||
pub sources_total: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
pub struct BucketDetails {
|
||||
pub versioning: bool,
|
||||
@@ -754,6 +777,33 @@ mod tests {
|
||||
assert!(!obj.contains_key("objects"));
|
||||
assert!(!obj.contains_key("object_sizes_histogram"));
|
||||
assert!(!obj.contains_key("object_versions_histogram"));
|
||||
assert!(!obj.contains_key("scan_progress"));
|
||||
assert!(!obj.contains_key("usage_value_state"));
|
||||
assert!(!obj.contains_key("usage_updated_at"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bucket_access_info_scan_progress_does_not_fill_total_usage() {
|
||||
let mut wire = serde_json::to_value(BucketAccessInfo::default()).expect("empty account bucket response");
|
||||
wire["scan_progress"] = serde_json::json!({
|
||||
"stage": "scanning", "updated_at": 1000, "objects": 7, "size": 71,
|
||||
"sources_observed": 1, "sources_total": 2,
|
||||
});
|
||||
let bucket: BucketAccessInfo = serde_json::from_value(wire.clone()).expect("decode scan progress response");
|
||||
let value = serde_json::to_value(bucket).expect("encode scan progress response");
|
||||
assert_eq!(value, wire, "scan coverage must round-trip without synthesizing total usage");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bucket_access_info_preserves_future_progress_and_provenance_values() {
|
||||
let mut wire = serde_json::to_value(BucketAccessInfo::default()).expect("empty account bucket response");
|
||||
wire["scan_progress"] = serde_json::json!({
|
||||
"stage": "future_stage", "updated_at": 1000, "objects": null, "size": null,
|
||||
"sources_observed": 1, "sources_total": 2,
|
||||
});
|
||||
wire["usage_value_state"] = serde_json::json!("future_provenance");
|
||||
let bucket: BucketAccessInfo = serde_json::from_value(wire.clone()).expect("SDK accepts future diagnostic labels");
|
||||
assert_eq!(serde_json::to_value(bucket).expect("preserve diagnostic labels"), wire);
|
||||
}
|
||||
|
||||
/// Wire pin (rustfs/backlog#1306): populated usage stats keep their
|
||||
@@ -1119,6 +1169,9 @@ mod tests {
|
||||
|
||||
let bucket_info = BucketAccessInfo {
|
||||
name: "test-bucket".to_string(),
|
||||
scan_progress: None,
|
||||
usage_value_state: None,
|
||||
usage_updated_at: None,
|
||||
size: Some(6000000),
|
||||
objects: Some(150),
|
||||
object_sizes_histogram: Some(sizes_histogram),
|
||||
|
||||
@@ -127,7 +127,7 @@ tracing-subscriber = { workspace = true, features = ["json", "env-filter", "time
|
||||
serial_test = { workspace = true }
|
||||
temp-env = { workspace = true, features = ["async_closure"] }
|
||||
uuid = { workspace = true, features = ["v4", "serde", "fast-rng", "macro-diagnostics"] }
|
||||
tokio = { workspace = true, features = ["test-util", "fs", "rt-multi-thread"] }
|
||||
tokio = { workspace = true, features = ["test-util", "fs", "process", "rt-multi-thread"] }
|
||||
# Test-only: pins the emitted scanner alert wire names against the canonical
|
||||
# EventName string forms subscribers configure (rustfs/backlog#1868).
|
||||
rustfs-s3-types.workspace = true
|
||||
|
||||
@@ -550,6 +550,10 @@ pub struct DataUsageScanCoverageReceipt {
|
||||
pub digest: [u8; 32],
|
||||
}
|
||||
|
||||
pub(crate) fn scan_measurement_time_millis(time: SystemTime) -> Option<u64> {
|
||||
u64::try_from(time.duration_since(SystemTime::UNIX_EPOCH).ok()?.as_millis()).ok()
|
||||
}
|
||||
|
||||
impl Serialize for DataUsageScanCoverageReceipt {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let mut map = serializer.serialize_map(Some(2))?;
|
||||
@@ -1089,6 +1093,9 @@ pub struct DataUsageCacheInfo {
|
||||
pub scan_bucket_observations: HashMap<String, DataUsageBucketObservation>,
|
||||
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub scan_bucket_value_origins: HashMap<String, DataUsageBucketValueOrigin>,
|
||||
/// Original accepted-frontier measurement time; absent on legacy checkpoints.
|
||||
#[serde(default)]
|
||||
pub scan_coverage_measured_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl Serialize for DataUsageCacheInfo {
|
||||
@@ -1109,6 +1116,7 @@ impl Serialize for DataUsageCacheInfo {
|
||||
+ usize::from(self.scan_progress.is_some())
|
||||
+ usize::from(self.scan_usage_watch.is_some())
|
||||
+ usize::from(self.scan_coverage_receipt.is_some())
|
||||
+ usize::from(self.scan_coverage_measured_at.is_some())
|
||||
+ usize::from(self.scan_coverage_digest.is_some())
|
||||
+ usize::from(self.tier_registry_generation.is_some())
|
||||
+ usize::from(!self.size_reconciliation.is_empty())
|
||||
@@ -1164,6 +1172,9 @@ impl Serialize for DataUsageCacheInfo {
|
||||
if let Some(receipt) = &self.scan_coverage_receipt {
|
||||
state.serialize_entry("scan_coverage_receipt", receipt)?;
|
||||
}
|
||||
if let Some(measured_at) = self.scan_coverage_measured_at {
|
||||
state.serialize_entry("scan_coverage_measured_at", &measured_at)?;
|
||||
}
|
||||
state.serialize_entry("pending_heals", &self.pending_heals)?;
|
||||
state.serialize_entry("object_lock", &crate::object_lock_cache::ObjectLockCache(&self.object_lock))?;
|
||||
state.serialize_entry("source", &self.source)?;
|
||||
@@ -1595,6 +1606,7 @@ impl DataUsageCache {
|
||||
self.info.scan_directory_source = None;
|
||||
self.info.scan_source_trees.clear();
|
||||
self.info.scan_coverage_receipt = None;
|
||||
self.info.scan_coverage_measured_at = None;
|
||||
}
|
||||
// Old readers do not understand coverage sweeps. An absent plan makes
|
||||
// their existing prepare path rebuild instead of promoting mixed data.
|
||||
@@ -1774,9 +1786,22 @@ impl DataUsageCache {
|
||||
pub(crate) fn seal_scan_frontier(&mut self, frontier: Option<&str>) -> Result<(), serde_json::Error> {
|
||||
if self.info.scan_progress.is_none() {
|
||||
self.info.scan_coverage_receipt = None;
|
||||
self.info.scan_coverage_measured_at = None;
|
||||
return Ok(());
|
||||
}
|
||||
let frontier = frontier.filter(|path| path.len() <= 16 * 1024 && self.find(path).is_some());
|
||||
let measured_at = frontier.and_then(|through| {
|
||||
if self
|
||||
.info
|
||||
.scan_coverage_receipt
|
||||
.as_ref()
|
||||
.is_some_and(|previous| previous.through == through)
|
||||
{
|
||||
self.info.scan_coverage_measured_at
|
||||
} else {
|
||||
scan_measurement_time_millis(SystemTime::now())
|
||||
}
|
||||
});
|
||||
self.info.scan_coverage_receipt = match frontier {
|
||||
Some(through) => Some(DataUsageScanCoverageReceipt {
|
||||
through: clone_cache_value(through),
|
||||
@@ -1784,6 +1809,7 @@ impl DataUsageCache {
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
self.info.scan_coverage_measured_at = measured_at;
|
||||
self.info.scan_resume_after = frontier.map(clone_cache_value);
|
||||
let reason = self
|
||||
.info
|
||||
@@ -2338,6 +2364,7 @@ impl DataUsageCache {
|
||||
}
|
||||
}
|
||||
|
||||
mod display_progress;
|
||||
mod persistence;
|
||||
mod source_tree;
|
||||
|
||||
|
||||
@@ -0,0 +1,625 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
use super::*;
|
||||
use bytes::{Buf, Bytes};
|
||||
use rustfs_data_usage::{
|
||||
BUCKET_SCAN_PROGRESS_MAX_BYTES, BUCKET_SCAN_PROGRESS_VERSION, BucketScanProgressSource, BucketScanStage,
|
||||
bucket_scan_progress_path,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::LazyLock;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
// A timed-out worker retains its permit until it exits, so repeated saves
|
||||
// cannot accumulate CPU work or decoded copies of large checkpoints.
|
||||
static DISPLAY_PROGRESS_WORKER: LazyLock<Arc<Semaphore>> = LazyLock::new(|| Arc::new(Semaphore::new(1)));
|
||||
|
||||
async fn extract_progress<F>(
|
||||
admission: crate::ScannerDataUsagePublicationAdmission,
|
||||
workers: Arc<Semaphore>,
|
||||
deadline: tokio::time::Instant,
|
||||
extract: F,
|
||||
) -> Option<BucketScanProgressSource>
|
||||
where
|
||||
F: FnOnce(CancellationToken) -> Option<BucketScanProgressSource> + Send + 'static,
|
||||
{
|
||||
// Only capture the durable movement generation under admission. CPU work
|
||||
// and waiting for the bounded worker must never retain the movement fence.
|
||||
drop(admission);
|
||||
let cancel = CancellationToken::new();
|
||||
let _cancel_on_drop = cancel.clone().drop_guard();
|
||||
let permit = tokio::time::timeout_at(deadline, workers.acquire_owned()).await.ok()?.ok()?;
|
||||
let (complete, result) = tokio::sync::oneshot::channel();
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
// A dedicated, admitted CPU worker cannot occupy the native I/O pool
|
||||
// needed to finish the primary save after this waiter has expired.
|
||||
std::thread::Builder::new()
|
||||
.name("scanner-progress".into())
|
||||
.spawn(move || {
|
||||
let _runtime = runtime.enter();
|
||||
let _permit = permit;
|
||||
let sample = (!cancel.is_cancelled() && tokio::time::Instant::now() < deadline)
|
||||
.then(|| extract(cancel))
|
||||
.flatten();
|
||||
let _ = complete.send(sample);
|
||||
})
|
||||
.ok()?;
|
||||
tokio::time::timeout_at(deadline, result).await.ok()?.ok()?
|
||||
}
|
||||
|
||||
struct ProgressInput {
|
||||
chunks: std::collections::VecDeque<Bytes>,
|
||||
cancel: CancellationToken,
|
||||
deadline: tokio::time::Instant,
|
||||
}
|
||||
|
||||
impl std::io::Read for ProgressInput {
|
||||
fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
|
||||
if self.cancel.is_cancelled() || tokio::time::Instant::now() >= self.deadline {
|
||||
return Err(std::io::Error::from(std::io::ErrorKind::TimedOut));
|
||||
}
|
||||
while self.chunks.front().is_some_and(Bytes::is_empty) {
|
||||
self.chunks.pop_front();
|
||||
}
|
||||
let Some(chunk) = self.chunks.front_mut() else { return Ok(0) };
|
||||
let count = output.len().min(chunk.len());
|
||||
output[..count].copy_from_slice(&chunk[..count]);
|
||||
chunk.advance(count);
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_display_progress<S: ScannerObjectIO>(
|
||||
store: Arc<S>,
|
||||
path: &str,
|
||||
) -> StorageResult<(Option<BucketScanProgressSource>, DataUsageCacheRevision)> {
|
||||
let opts = ObjectOptions {
|
||||
no_lock: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut reader = match store
|
||||
.get_object_reader(RUSTFS_META_BUCKET, path, None, HeaderMap::new(), &opts)
|
||||
.await
|
||||
{
|
||||
Ok(reader) => reader,
|
||||
Err(Error::ConfigNotFound | Error::FileNotFound | Error::ObjectNotFound(..)) => {
|
||||
return Ok((None, DataUsageCacheRevision::Missing));
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let revision = reader
|
||||
.object_info
|
||||
.etag
|
||||
.as_ref()
|
||||
.filter(|etag| !etag.is_empty())
|
||||
.map(|etag| DataUsageCacheRevision::Etag(etag.clone()))
|
||||
.ok_or_else(|| Error::other("scanner progress object has no revision"))?;
|
||||
let mut bytes = Vec::new();
|
||||
(&mut reader)
|
||||
.take(u64::try_from(BUCKET_SCAN_PROGRESS_MAX_BYTES).map_err(Error::other)? + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.await?;
|
||||
let sample = (bytes.len() <= BUCKET_SCAN_PROGRESS_MAX_BYTES)
|
||||
.then(|| serde_json::from_slice(&bytes).ok())
|
||||
.flatten();
|
||||
Ok((sample, revision))
|
||||
}
|
||||
|
||||
impl DataUsageCache {
|
||||
/// Extract accepted coverage, never the mixed old/new running root total.
|
||||
/// Physical replicas are alternative samples of one logical source.
|
||||
pub(crate) fn display_scan_progress(&self, movement_generation: u64) -> Option<BucketScanProgressSource> {
|
||||
let identity = self.info.scan_identity.filter(|identity| identity.is_valid())?;
|
||||
let source = self.info.source?;
|
||||
let updated_at = u64::try_from(
|
||||
self.info
|
||||
.last_update?
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.ok()?
|
||||
.as_millis(),
|
||||
)
|
||||
.ok()?;
|
||||
if self.info.name.is_empty() || self.info.name == DATA_USAGE_ROOT {
|
||||
return None;
|
||||
}
|
||||
let completed = if self.info.snapshot_complete {
|
||||
self.checked_flatten_complete_scope(&self.info.name)
|
||||
} else {
|
||||
self.completed_bucket_observation()
|
||||
.filter(|observation| Some(observation.completed_at) == self.info.last_update && !self.has_scan_position())
|
||||
.map(|observation| observation.entry.clone())
|
||||
};
|
||||
let mut accepted = completed.as_ref().map(|entry| (entry.objects, entry.size, updated_at));
|
||||
if completed.is_none() {
|
||||
let frontier = self.validated_scan_frontier();
|
||||
let mut replicas = BTreeMap::<&str, Vec<_>>::new();
|
||||
for checkpoint in &self.info.scan_directory_work {
|
||||
if let Some((coverage, entry, measured_at)) = checkpoint.display_usage(&self.info) {
|
||||
replicas
|
||||
.entry(checkpoint.endpoint())
|
||||
.or_default()
|
||||
.push((coverage, entry, measured_at));
|
||||
}
|
||||
}
|
||||
if let Some(active) = self.info.scan_directory_source.as_deref() {
|
||||
replicas.entry(active).or_default();
|
||||
}
|
||||
for (endpoint, mut receipts) in replicas {
|
||||
// Ancestors precede descendants. An acknowledged ancestor child
|
||||
// already contains every nested contribution below that child.
|
||||
receipts.sort_by(|a, b| a.0.parent.split('/').cmp(b.0.parent.split('/')));
|
||||
let mut selected = Vec::new();
|
||||
let mut subtotal: Option<(usize, usize)> = None;
|
||||
let mut measured_at: Option<u64> = None;
|
||||
let mut known_time = true;
|
||||
for (coverage, entry, time) in &receipts {
|
||||
if selected.iter().any(|parent: &&crate::scanner_folder::DirectoryProgress| {
|
||||
parent.parent == coverage.parent || parent.covers(&coverage.parent)
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
if endpoint == self.info.scan_directory_source.as_deref().unwrap_or_default()
|
||||
&& frontier.is_some_and(|through| scan_frontier_covers_path(&coverage.parent, through))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (objects, size) = subtotal.unwrap_or_default();
|
||||
subtotal = Some((objects.checked_add(entry.objects)?, size.checked_add(entry.size)?));
|
||||
if let Some(time) = time {
|
||||
measured_at = Some(measured_at.map_or(*time, |previous| previous.min(*time)));
|
||||
} else {
|
||||
known_time = false;
|
||||
}
|
||||
selected.push(coverage);
|
||||
}
|
||||
if Some(endpoint) == self.info.scan_directory_source.as_deref()
|
||||
&& let Some(through) = frontier
|
||||
{
|
||||
// A validated receipt signs this prefix. Sum each scalar
|
||||
// once, excluding the ranges represented by compacted work.
|
||||
self.checked_flatten_complete_scope(&self.info.name)?;
|
||||
let mut contributed = false;
|
||||
for (path, entry) in &self.cache {
|
||||
if scan_frontier_covers_path(path, through) && !selected.iter().any(|proof| proof.covers(path)) {
|
||||
let (objects, size) = subtotal.unwrap_or_default();
|
||||
subtotal = Some((objects.checked_add(entry.objects)?, size.checked_add(entry.size)?));
|
||||
contributed = true;
|
||||
}
|
||||
}
|
||||
if contributed {
|
||||
if let Some(time) = self.info.scan_coverage_measured_at {
|
||||
measured_at = Some(measured_at.map_or(time, |previous| previous.min(time)));
|
||||
} else {
|
||||
known_time = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Replicas overlap. Select one sample; never sum or append them.
|
||||
// Legacy coverage without a measurement time cannot borrow a
|
||||
// newer checkpoint time. Keep the prior companion instead.
|
||||
if known_time
|
||||
&& let (Some((objects, size)), Some(time)) = (subtotal, measured_at)
|
||||
&& accepted.is_none_or(|previous| (objects, size, time) > previous)
|
||||
{
|
||||
accepted = Some((objects, size, time));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(BucketScanProgressSource {
|
||||
version: BUCKET_SCAN_PROGRESS_VERSION,
|
||||
bucket: self.info.name.clone(),
|
||||
bucket_incarnation: identity.bucket_incarnation.to_string(),
|
||||
pool_index: u64::try_from(source.pool_index).ok()?,
|
||||
set_index: u64::try_from(source.set_index).ok()?,
|
||||
set_layout: identity.set_layout.0,
|
||||
publication_epoch: identity.publication_epoch,
|
||||
movement_generation: Some(movement_generation),
|
||||
scanner_epoch: self.info.leader_epoch,
|
||||
scanner_cycle: self.info.next_cycle,
|
||||
updated_at: accepted.map_or(updated_at, |(_, _, time)| time),
|
||||
stage: if completed.is_some() {
|
||||
BucketScanStage::Completed
|
||||
} else if accepted.is_some() {
|
||||
BucketScanStage::Scanning
|
||||
} else {
|
||||
BucketScanStage::Enumerating
|
||||
},
|
||||
objects: accepted.map(|(objects, _, _)| u64::try_from(objects)).transpose().ok()?,
|
||||
size: accepted.map(|(_, size, _)| u64::try_from(size)).transpose().ok()?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn prepare_display_progress<S: ScannerObjectIO + ScannerConfigObjectDelete>(
|
||||
&self,
|
||||
store: Arc<S>,
|
||||
expected_epoch: Option<u64>,
|
||||
input: Option<Vec<Bytes>>,
|
||||
) -> Option<(String, Vec<u8>, DataUsageCacheRevision)> {
|
||||
if self.info.name.is_empty() || self.info.name == DATA_USAGE_ROOT || self.info.scan_identity.is_none() {
|
||||
return None;
|
||||
}
|
||||
let expected_epoch = expected_epoch?;
|
||||
let input = input?;
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
|
||||
let admission = scanner_publication_admission_for_epoch(store.clone(), expected_epoch).await?;
|
||||
let movement_generation = store.scanner_data_usage_movement_generation().await?;
|
||||
let sample = extract_progress(admission, DISPLAY_PROGRESS_WORKER.clone(), deadline, move |cancel| {
|
||||
let reader = ProgressInput {
|
||||
chunks: input.into(),
|
||||
cancel: cancel.clone(),
|
||||
deadline,
|
||||
};
|
||||
let cache: DataUsageCache = rmp_serde::from_read(reader).ok()?;
|
||||
if cancel.is_cancelled() || tokio::time::Instant::now() >= deadline {
|
||||
return None;
|
||||
}
|
||||
cache.display_scan_progress(movement_generation)
|
||||
})
|
||||
.await?;
|
||||
if expected_epoch != sample.publication_epoch {
|
||||
return None;
|
||||
}
|
||||
let path = bucket_scan_progress_path(&sample.bucket);
|
||||
// Read before the primary commit. An old lease owner cannot overwrite
|
||||
// a newer owner's summary after losing its cache CAS or sidecar CAS.
|
||||
let (previous, revision) = timeout(Duration::from_secs(2), read_display_progress(store, &path))
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
// A new physical executor may first enumerate its replica. Keep the
|
||||
// previous accepted sample and its original time until it has another
|
||||
// measured range. This is a whole observation, never an added delta.
|
||||
let sample = previous
|
||||
.filter(|previous| {
|
||||
sample.objects.is_none()
|
||||
&& previous.objects.is_some()
|
||||
&& previous.stage != BucketScanStage::Completed
|
||||
&& previous.matches(
|
||||
&sample.bucket,
|
||||
&sample.bucket_incarnation,
|
||||
(sample.pool_index, sample.set_index),
|
||||
movement_generation,
|
||||
)
|
||||
&& previous.set_layout == sample.set_layout
|
||||
&& (previous.scanner_epoch, previous.scanner_cycle) <= (sample.scanner_epoch, sample.scanner_cycle)
|
||||
})
|
||||
.unwrap_or(sample);
|
||||
Some((path, serde_json::to_vec(&sample).ok()?, revision))
|
||||
}
|
||||
|
||||
pub(super) async fn persist_display_progress<S: ScannerObjectIO + ScannerConfigObjectDelete>(
|
||||
store: Arc<S>,
|
||||
prepared: Option<(String, Vec<u8>, DataUsageCacheRevision)>,
|
||||
expected_epoch: Option<u64>,
|
||||
) {
|
||||
let (Some((path, data, revision)), Some(epoch)) = (prepared, expected_epoch) else {
|
||||
return;
|
||||
};
|
||||
// A diagnostic write failure must not invalidate a durable checkpoint.
|
||||
// The next admitted checkpoint retries, with no request-path S3 listing.
|
||||
let _ = timeout(
|
||||
Duration::from_secs(2),
|
||||
crate::save_config_with_publication_admission_for_epoch(store, &path, data, revision.preconditions(), epoch),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct ReleaseWorker(Option<std::sync::mpsc::Sender<()>>);
|
||||
|
||||
impl Drop for ReleaseWorker {
|
||||
fn drop(&mut self) {
|
||||
if let Some(release) = self.0.take() {
|
||||
let _ = release.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn display_progress_extraction_releases_movement_guard_before_cpu_work() {
|
||||
let movement = Arc::new(tokio::sync::RwLock::new(()));
|
||||
let admission = crate::ScannerDataUsagePublicationAdmission::fenced(movement.clone().read_owned().await, 0);
|
||||
let (started, entered) = tokio::sync::oneshot::channel();
|
||||
let (release, blocked) = std::sync::mpsc::channel();
|
||||
let release = ReleaseWorker(Some(release));
|
||||
let task = tokio::spawn(extract_progress(
|
||||
admission,
|
||||
Arc::new(Semaphore::new(1)),
|
||||
tokio::time::Instant::now() + Duration::from_secs(5),
|
||||
move |_| {
|
||||
let _ = started.send(());
|
||||
blocked
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("bounded test worker release");
|
||||
None
|
||||
},
|
||||
));
|
||||
entered.await.expect("CPU projection started");
|
||||
assert!(
|
||||
movement.try_write().is_ok(),
|
||||
"a running diagnostic projection must not hold movement admission"
|
||||
);
|
||||
drop(release);
|
||||
assert!(task.await.expect("projection task").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn display_progress_timeout_keeps_detached_cpu_work_bounded() {
|
||||
let movement = Arc::new(tokio::sync::RwLock::new(()));
|
||||
let workers = Arc::new(Semaphore::new(1));
|
||||
let (started, entered) = tokio::sync::oneshot::channel();
|
||||
let (finished, stopped) = tokio::sync::oneshot::channel();
|
||||
let (release, blocked) = std::sync::mpsc::channel();
|
||||
let release = ReleaseWorker(Some(release));
|
||||
let admission = crate::ScannerDataUsagePublicationAdmission::fenced(movement.clone().read_owned().await, 0);
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(60);
|
||||
let first = tokio::spawn(extract_progress(admission, workers.clone(), deadline, move |cancel| {
|
||||
let _ = started.send(());
|
||||
blocked
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("bounded test worker release");
|
||||
let _ = finished.send(cancel.is_cancelled());
|
||||
None
|
||||
}));
|
||||
entered.await.expect("CPU work entered");
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(61)).await;
|
||||
assert!(first.await.expect("expired waiter").is_none());
|
||||
assert!(
|
||||
movement.try_write().is_ok(),
|
||||
"expired diagnostics cannot block movement or primary publication"
|
||||
);
|
||||
assert_eq!(workers.available_permits(), 0, "the detached worker retains its resource admission");
|
||||
|
||||
let admission = crate::ScannerDataUsagePublicationAdmission::fenced(movement.clone().read_owned().await, 0);
|
||||
let next_deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
let queued = tokio::spawn(extract_progress(admission, workers.clone(), next_deadline, |_| {
|
||||
panic!("an expired waiter must not queue another CPU worker")
|
||||
}));
|
||||
tokio::time::advance(Duration::from_secs(2)).await;
|
||||
assert!(queued.await.expect("second expired waiter").is_none());
|
||||
drop(release);
|
||||
tokio::time::resume();
|
||||
assert!(stopped.await.expect("worker stopped after cancellation"));
|
||||
let permit = timeout(Duration::from_secs(5), workers.acquire_owned())
|
||||
.await
|
||||
.expect("worker releases its permit")
|
||||
.expect("worker gate remains open");
|
||||
drop(permit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_progress_cpu_work_cannot_starve_native_io_workers() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.max_blocking_threads(1)
|
||||
.build()
|
||||
.expect("runtime with one native I/O worker");
|
||||
runtime.block_on(async {
|
||||
let (started, entered) = tokio::sync::oneshot::channel();
|
||||
let (release, blocked) = std::sync::mpsc::channel();
|
||||
let release = ReleaseWorker(Some(release));
|
||||
let task = tokio::spawn(extract_progress(
|
||||
crate::ScannerDataUsagePublicationAdmission::unfenced(),
|
||||
Arc::new(Semaphore::new(1)),
|
||||
tokio::time::Instant::now() + Duration::from_secs(5),
|
||||
move |_| {
|
||||
let _ = started.send(());
|
||||
blocked
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("bounded diagnostic worker");
|
||||
None
|
||||
},
|
||||
));
|
||||
entered.await.expect("diagnostic CPU worker started");
|
||||
let native_io = timeout(Duration::from_secs(1), tokio::task::spawn_blocking(|| 7)).await;
|
||||
drop(release);
|
||||
assert!(task.await.expect("released diagnostic task").is_none());
|
||||
assert_eq!(
|
||||
native_io
|
||||
.expect("diagnostics must leave native I/O available")
|
||||
.expect("native job"),
|
||||
7
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_progress_input_honors_cancellation_and_deadline() {
|
||||
use std::io::Read;
|
||||
let cancel = CancellationToken::new();
|
||||
let mut reader = ProgressInput {
|
||||
chunks: vec![Bytes::from_static(b"a"), Bytes::new(), Bytes::from_static(b"bc")].into(),
|
||||
cancel: cancel.clone(),
|
||||
deadline: tokio::time::Instant::now() + Duration::from_secs(1),
|
||||
};
|
||||
let mut bytes = [0; 1];
|
||||
assert_eq!(reader.read(&mut bytes).expect("first shared chunk"), 1);
|
||||
assert_eq!(bytes, *b"a");
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
reader.read(&mut bytes).expect_err("cancelled decode").kind(),
|
||||
std::io::ErrorKind::TimedOut
|
||||
);
|
||||
reader.cancel = CancellationToken::new();
|
||||
reader.deadline = tokio::time::Instant::now();
|
||||
assert_eq!(reader.read(&mut bytes).expect_err("expired decode").kind(), std::io::ErrorKind::TimedOut);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_progress_decodes_shared_chunks_without_changing_usage() {
|
||||
let mut cache = checkpoint();
|
||||
cache.info.snapshot_complete = true;
|
||||
cache.replace(
|
||||
"bucket",
|
||||
"",
|
||||
DataUsageEntry {
|
||||
objects: 3,
|
||||
size: 33,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let expected = cache.display_scan_progress(0).expect("complete reference sample");
|
||||
let bytes = cache.marshal_msg().expect("encode checkpoint");
|
||||
let mut chunks = std::collections::VecDeque::new();
|
||||
for part in bytes.chunks(7) {
|
||||
chunks.push_back(Bytes::new());
|
||||
chunks.push_back(Bytes::copy_from_slice(part));
|
||||
}
|
||||
let decoded: DataUsageCache = rmp_serde::from_read(ProgressInput {
|
||||
chunks,
|
||||
cancel: CancellationToken::new(),
|
||||
deadline: tokio::time::Instant::now() + Duration::from_secs(1),
|
||||
})
|
||||
.expect("decode across fragmented and empty chunks");
|
||||
assert_eq!(decoded.display_scan_progress(0), Some(expected));
|
||||
}
|
||||
|
||||
fn checkpoint() -> DataUsageCache {
|
||||
let mut cache = DataUsageCache::default();
|
||||
cache.prepare_bucket_checkpoint(
|
||||
"bucket",
|
||||
1,
|
||||
1,
|
||||
DataUsageCacheSource::new(0, 0),
|
||||
DataUsageScanPlanDigest([2; 32]),
|
||||
DataUsageScanIdentity {
|
||||
version: 1,
|
||||
bucket_incarnation: uuid::Uuid::new_v4(),
|
||||
set_layout: DataUsageScanPlanDigest([3; 32]),
|
||||
publication_epoch: 0,
|
||||
tier_registry_generation: 0,
|
||||
scan_mode: HealScanMode::Normal,
|
||||
},
|
||||
);
|
||||
cache.info.last_update = Some(SystemTime::UNIX_EPOCH + Duration::from_secs(10));
|
||||
cache.info.scan_directory_source = Some("source".into());
|
||||
cache
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_progress_frontier_resealing_and_cold_source_handoff_preserve_time() {
|
||||
let mut cache = checkpoint();
|
||||
cache.replace("bucket", "", DataUsageEntry::default());
|
||||
cache.replace(
|
||||
"bucket/a",
|
||||
"bucket",
|
||||
DataUsageEntry {
|
||||
objects: 1,
|
||||
size: 11,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
cache.seal_scan_frontier(Some("bucket/a")).expect("seal measured frontier");
|
||||
cache.info.scan_coverage_measured_at = Some(10_000);
|
||||
cache.info.last_update = Some(SystemTime::UNIX_EPOCH + Duration::from_secs(70));
|
||||
cache.seal_scan_frontier(Some("bucket/a")).expect("reseal unchanged frontier");
|
||||
assert_eq!(cache.display_scan_progress(0).expect("unchanged observation").updated_at, 10_000);
|
||||
let endpoints = std::collections::HashSet::from(["source".to_owned(), "other".to_owned()]);
|
||||
cache.activate_directory_source("other".into(), &endpoints);
|
||||
cache.replace("bucket", "", DataUsageEntry::default());
|
||||
let bytes = cache.marshal_msg().expect("save inactive source with its measurement time");
|
||||
let mut cold = DataUsageCache::unmarshal(&bytes).expect("cold source handoff");
|
||||
cold.activate_directory_source("source".into(), &endpoints);
|
||||
let sample = cold.display_scan_progress(0).expect("restored measured frontier");
|
||||
assert_eq!((sample.objects, sample.size, sample.updated_at), (Some(1), Some(11), 10_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_progress_legacy_frontier_cannot_borrow_a_new_checkpoint_time() {
|
||||
let mut cache = checkpoint();
|
||||
cache.replace("bucket", "", DataUsageEntry::default());
|
||||
cache.replace(
|
||||
"bucket/a",
|
||||
"bucket",
|
||||
DataUsageEntry {
|
||||
objects: 1,
|
||||
size: 11,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
cache.seal_scan_frontier(Some("bucket/a")).expect("legacy coverage");
|
||||
cache.info.scan_coverage_measured_at = None;
|
||||
let sample = cache.display_scan_progress(0).expect("enumeration remains observable");
|
||||
assert_eq!((sample.objects, sample.size), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_progress_excludes_old_tail_and_uncommitted_ancestors() {
|
||||
let mut cache = checkpoint();
|
||||
let mut root = DataUsageEntry {
|
||||
objects: 99,
|
||||
size: 999,
|
||||
..Default::default()
|
||||
};
|
||||
root.add_child(&hash_path("bucket/a"));
|
||||
root.add_child(&hash_path("bucket/z"));
|
||||
cache.cache.insert("bucket".into(), root);
|
||||
cache.cache.insert(
|
||||
"bucket/a".into(),
|
||||
DataUsageEntry {
|
||||
objects: 3,
|
||||
size: 30,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
cache.cache.insert(
|
||||
"bucket/z".into(),
|
||||
DataUsageEntry {
|
||||
objects: 80,
|
||||
size: 800,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
cache.seal_scan_frontier(Some("bucket/a")).expect("seal accepted prefix");
|
||||
let sample = cache.display_scan_progress(0).expect("accepted progress");
|
||||
assert_eq!((sample.objects, sample.size), (Some(3), Some(30)));
|
||||
assert_eq!(sample.stage, BucketScanStage::Scanning);
|
||||
let encoded = rmp_serde::to_vec(&cache).expect("encode checkpoint");
|
||||
let mut restarted: DataUsageCache = rmp_serde::from_slice(&encoded).expect("cold decode checkpoint");
|
||||
restarted.info.leader_epoch += 1;
|
||||
assert_eq!(restarted.display_scan_progress(0).expect("handoff progress").objects, Some(3));
|
||||
assert_eq!(restarted.display_scan_progress(0).expect("repeated sample").size, Some(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_progress_rejects_invalid_receipt_and_preserves_enumerating_unknown() {
|
||||
let mut cache = checkpoint();
|
||||
cache.cache.insert(
|
||||
"bucket".into(),
|
||||
DataUsageEntry {
|
||||
objects: 999,
|
||||
size: 999,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let sample = cache.display_scan_progress(0).expect("enumeration state");
|
||||
assert_eq!((sample.objects, sample.size), (None, None));
|
||||
assert_eq!(sample.stage, BucketScanStage::Enumerating);
|
||||
cache.info.snapshot_complete = true;
|
||||
let complete = cache.display_scan_progress(0).expect("complete traversal");
|
||||
assert_eq!((complete.objects, complete.size), (Some(999), Some(999)));
|
||||
assert_eq!(complete.stage, BucketScanStage::Completed);
|
||||
cache.info.snapshot_complete = false;
|
||||
cache.replace(
|
||||
"bucket/a",
|
||||
"bucket",
|
||||
DataUsageEntry {
|
||||
objects: 3,
|
||||
size: 30,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
cache.seal_scan_frontier(Some("bucket/a")).expect("seal complete child");
|
||||
assert_eq!(cache.display_scan_progress(0).expect("verified prefix").objects, Some(3));
|
||||
cache.cache.get_mut("bucket/a").expect("accepted child").objects = 7;
|
||||
assert_eq!(cache.display_scan_progress(0).expect("corrupt receipt is unknown").objects, None);
|
||||
}
|
||||
}
|
||||
@@ -766,6 +766,20 @@ impl DataUsageCache {
|
||||
_ => (inline.clone(), [None, None]),
|
||||
};
|
||||
let path = path_join_buf(&[BUCKET_META_PREFIX, name]);
|
||||
let display_progress = timeout(Duration::from_secs(2), async {
|
||||
let input = if expected_epoch.is_some() && self.info.scan_identity.is_some() && self.info.name != DATA_USAGE_ROOT {
|
||||
match &encoded {
|
||||
Some(encoded) => encoded.progress_input().await,
|
||||
None => Some(vec![inline.clone()]),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.prepare_display_progress(store.clone(), expected_epoch, input).await
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
let primary_save_started = Instant::now();
|
||||
Self::save_path_with_retry(
|
||||
store.clone(),
|
||||
@@ -778,6 +792,7 @@ impl DataUsageCache {
|
||||
)
|
||||
.await?;
|
||||
|
||||
Self::persist_display_progress(store.clone(), display_progress, expected_epoch).await;
|
||||
pages::reclaim_retired(store.clone(), name, primary_retired, expected_epoch).await;
|
||||
let backup_name = format!("{name}.bkp");
|
||||
let backup_path = path_join_buf(&[BUCKET_META_PREFIX, &backup_name]);
|
||||
@@ -815,7 +830,11 @@ impl DataUsageCache {
|
||||
pages::reclaim_retired(store, &backup_name, retired, expected_epoch).await;
|
||||
Ok::<_, StorageError>(())
|
||||
};
|
||||
if let Err(e) = save_backup.await {
|
||||
let backup_result = match timeout(backup_timeout_duration, save_backup).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err(StorageError::other("scanner cache backup save timed out")),
|
||||
};
|
||||
if let Err(e) = backup_result {
|
||||
warn!(
|
||||
target: "rustfs::scanner::data_usage",
|
||||
event = EVENT_SCANNER_CACHE_SAVE_STATE,
|
||||
|
||||
@@ -221,6 +221,32 @@ impl EncodedPages {
|
||||
pub(super) fn length(&self) -> u64 {
|
||||
self.archive.length
|
||||
}
|
||||
|
||||
/// Share the original MessagePack stream without copying page payloads.
|
||||
pub(super) async fn progress_input(&self) -> Option<Vec<Bytes>> {
|
||||
let mut pending = vec![(self.root.root, self.root.level)];
|
||||
let mut chunks = Vec::new();
|
||||
let mut visits = 0_usize;
|
||||
while let Some((key, level)) = pending.pop() {
|
||||
visits += 1;
|
||||
if visits.is_multiple_of(256) {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let bytes = self.archive.blocks.get(&key)?;
|
||||
if level == 0 {
|
||||
chunks.push(bytes.clone());
|
||||
} else {
|
||||
let (children, remainder) = bytes.as_chunks::<32>();
|
||||
if !remainder.is_empty() {
|
||||
return None;
|
||||
}
|
||||
for child in children.iter().rev() {
|
||||
pending.push((*child, level - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(chunks)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn encode(cache: &DataUsageCache) -> StorageResult<EncodedPages> {
|
||||
@@ -644,3 +670,45 @@ async fn reclaim<S: ScannerObjectIO + ScannerConfigObjectDelete>(
|
||||
Err(_) => Err(Error::other("retired scanner checkpoint cleanup timed out")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod progress_input_tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn display_progress_input_reassembles_multilevel_checkpoint_pages() {
|
||||
for count in [0, 3, 16_384] {
|
||||
let mut cache = DataUsageCache::default();
|
||||
cache.info.name = "bucket".into();
|
||||
cache.replace("bucket", "", DataUsageEntry::default());
|
||||
for index in 0..count {
|
||||
let path = format!("bucket/object-{index:05}-{}", "x".repeat(512));
|
||||
cache.replace(
|
||||
&path,
|
||||
"bucket",
|
||||
DataUsageEntry {
|
||||
objects: 1,
|
||||
size: 11,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let encoded = encode(&cache).expect("encode checkpoint pages");
|
||||
if count == 16_384 {
|
||||
assert!(encoded.root.level >= 2, "the fixture must cover multiple manifest levels");
|
||||
}
|
||||
let chunks = encoded.progress_input().await.expect("borrow immutable serialized chunks");
|
||||
assert_eq!(
|
||||
chunks.iter().map(Bytes::len).sum::<usize>(),
|
||||
usize::try_from(encoded.length()).expect("fixture length")
|
||||
);
|
||||
let bytes = chunks.into_iter().flatten().collect::<Vec<_>>();
|
||||
let recovered = DataUsageCache::unmarshal(&bytes).expect("decode the original MessagePack stream");
|
||||
let totals = recovered
|
||||
.checked_flatten_complete_scope("bucket")
|
||||
.expect("connected checkpoint");
|
||||
assert_eq!((totals.objects, totals.size), (count, count * 11));
|
||||
assert_eq!(recovered.cache.len(), cache.cache.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,11 @@ use super::*;
|
||||
|
||||
/// A linked tree paused on a different physical replica. It contains only
|
||||
/// traversal fields, so dormant sources cannot recursively contain each other.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct SourceTree {
|
||||
bucket: String,
|
||||
identity: DataUsageScanIdentity,
|
||||
started_plan: DataUsageScanPlanDigest,
|
||||
#[serde(serialize_with = "ordered_entries")]
|
||||
entries: HashMap<String, DataUsageEntry>,
|
||||
resume_after: Option<String>,
|
||||
checkpoint: Option<DataUsageScanCheckpoint>,
|
||||
@@ -18,6 +17,36 @@ pub struct SourceTree {
|
||||
cursor: Option<DataUsageRawEnumerationCursor>,
|
||||
index: Option<RawEnumerationPageIndex>,
|
||||
ancestors: Vec<RawEnumerationPageIndex>,
|
||||
#[serde(default)]
|
||||
coverage_measured_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl Serialize for SourceTree {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let mut map = serializer.serialize_map(Some(10 + usize::from(self.coverage_measured_at.is_some())))?;
|
||||
map.serialize_entry("bucket", &self.bucket)?;
|
||||
map.serialize_entry("identity", &self.identity)?;
|
||||
map.serialize_entry("started_plan", &self.started_plan)?;
|
||||
map.serialize_entry("entries", &OrderedEntries(&self.entries))?;
|
||||
map.serialize_entry("resume_after", &self.resume_after)?;
|
||||
map.serialize_entry("checkpoint", &self.checkpoint)?;
|
||||
map.serialize_entry("coverage", &self.coverage)?;
|
||||
map.serialize_entry("cursor", &self.cursor)?;
|
||||
map.serialize_entry("index", &self.index)?;
|
||||
map.serialize_entry("ancestors", &self.ancestors)?;
|
||||
if let Some(measured_at) = self.coverage_measured_at {
|
||||
map.serialize_entry("coverage_measured_at", &measured_at)?;
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
}
|
||||
|
||||
struct OrderedEntries<'a>(&'a HashMap<String, DataUsageEntry>);
|
||||
|
||||
impl Serialize for OrderedEntries<'_> {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
ordered_entries(self.0, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl SourceTree {
|
||||
@@ -89,6 +118,7 @@ impl DataUsageCache {
|
||||
resume_after: self.info.scan_resume_after.take(),
|
||||
checkpoint: self.info.scan_checkpoint.take(),
|
||||
coverage: self.info.scan_coverage_receipt.take(),
|
||||
coverage_measured_at: self.info.scan_coverage_measured_at.take(),
|
||||
cursor: self.info.scan_raw_enumeration_cursor.take(),
|
||||
index: self.info.scan_raw_enumeration_page_index.take(),
|
||||
ancestors: std::mem::take(&mut self.info.scan_raw_enumeration_path_page_indexes),
|
||||
@@ -104,6 +134,7 @@ impl DataUsageCache {
|
||||
self.cache = tree.entries;
|
||||
self.info.scan_resume_after = tree.resume_after;
|
||||
self.info.scan_coverage_receipt = tree.coverage;
|
||||
self.info.scan_coverage_measured_at = tree.coverage_measured_at;
|
||||
self.info.scan_checkpoint = tree.checkpoint;
|
||||
self.info.scan_raw_enumeration_cursor = tree.cursor;
|
||||
self.info.scan_raw_enumeration_page_index = tree.index;
|
||||
@@ -122,6 +153,7 @@ impl DataUsageCache {
|
||||
self.info.scan_resume_after = None;
|
||||
self.info.scan_checkpoint = None;
|
||||
self.info.scan_coverage_receipt = None;
|
||||
self.info.scan_coverage_measured_at = None;
|
||||
self.info.scan_raw_enumeration_cursor = None;
|
||||
self.info.scan_raw_enumeration_page_index = None;
|
||||
self.info.scan_raw_enumeration_path_page_indexes.clear();
|
||||
@@ -131,3 +163,53 @@ impl DataUsageCache {
|
||||
fn directory_source_location(source: &str) -> &str {
|
||||
source.split_once('|').map_or(source, |(_, endpoint)| endpoint)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct LegacySourceTree {
|
||||
bucket: String,
|
||||
identity: DataUsageScanIdentity,
|
||||
started_plan: DataUsageScanPlanDigest,
|
||||
entries: HashMap<String, DataUsageEntry>,
|
||||
resume_after: Option<String>,
|
||||
checkpoint: Option<DataUsageScanCheckpoint>,
|
||||
coverage: Option<DataUsageScanCoverageReceipt>,
|
||||
cursor: Option<DataUsageRawEnumerationCursor>,
|
||||
index: Option<RawEnumerationPageIndex>,
|
||||
ancestors: Vec<RawEnumerationPageIndex>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_tree_measurement_metadata_preserves_legacy_codecs() {
|
||||
let tree = SourceTree {
|
||||
bucket: "bucket".into(),
|
||||
identity: DataUsageScanIdentity {
|
||||
version: DATA_USAGE_SCAN_CHECKPOINT_VERSION,
|
||||
bucket_incarnation: uuid::Uuid::from_u128(1),
|
||||
set_layout: DataUsageScanPlanDigest([2; 32]),
|
||||
publication_epoch: 0,
|
||||
tier_registry_generation: 0,
|
||||
scan_mode: HealScanMode::Normal,
|
||||
},
|
||||
started_plan: DataUsageScanPlanDigest([3; 32]),
|
||||
entries: HashMap::from([("bucket".into(), DataUsageEntry::default())]),
|
||||
resume_after: None,
|
||||
checkpoint: None,
|
||||
coverage: None,
|
||||
cursor: None,
|
||||
index: None,
|
||||
ancestors: Vec::new(),
|
||||
coverage_measured_at: Some(10_000),
|
||||
};
|
||||
let bytes = rmp_serde::to_vec(&tree).expect("encode additive named source tree");
|
||||
let old: LegacySourceTree = rmp_serde::from_slice(&bytes).expect("old reader ignores diagnostic time");
|
||||
let bytes = rmp_serde::to_vec(&old).expect("encode old positional source tree");
|
||||
let recovered: SourceTree = rmp_serde::from_slice(&bytes).expect("new reader accepts old positional source tree");
|
||||
assert_eq!(recovered.bucket, tree.bucket);
|
||||
assert_eq!(recovered.entries.len(), 1);
|
||||
assert_eq!(recovered.coverage_measured_at, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3021,7 +3021,15 @@ async fn test_checkpoint_budget_covers_retries_and_reconciliation() {
|
||||
.expect("a successful or reconciled primary must survive a best-effort backup failure");
|
||||
assert_eq!(store.put_attempts[0].load(Ordering::SeqCst), 3);
|
||||
assert_eq!(store.put_attempts[1].load(Ordering::SeqCst), 1, "backup writes must not retry");
|
||||
assert_eq!(*store.backup_reads.lock().await, 1, "backup must finish its bounded reconciliation");
|
||||
assert_eq!(
|
||||
*store.backup_reads.lock().await,
|
||||
0,
|
||||
"backup reconciliation must not outlive the total backup budget"
|
||||
);
|
||||
assert!(
|
||||
store.puts.lock().await.iter().all(|put| !put.object.ends_with(".bkp")),
|
||||
"a timed-out backup must not replace the previous fallback"
|
||||
);
|
||||
assert!(started.elapsed() < DataUsageCache::persistence_timeout());
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1026,6 +1026,12 @@ impl<T> ScannerObjectIO for T where
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait ScannerConfigObjectDelete: Send + Sync + std::fmt::Debug + 'static {
|
||||
/// Shared movement scope for diagnostic samples; absence disables progress
|
||||
/// publication without affecting checkpoint recovery.
|
||||
async fn scanner_data_usage_movement_generation(&self) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn delete_config_object(
|
||||
&self,
|
||||
bucket: &str,
|
||||
@@ -1090,6 +1096,9 @@ impl ScannerDataUsagePublicationAdmission {
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ScannerConfigObjectDelete for ECStore {
|
||||
async fn scanner_data_usage_movement_generation(&self) -> Option<u64> {
|
||||
ECStore::scanner_durable_data_movement_generation(self).await
|
||||
}
|
||||
async fn delete_config_object(
|
||||
&self,
|
||||
bucket: &str,
|
||||
@@ -1134,6 +1143,9 @@ impl ScannerConfigObjectDelete for ECStore {
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ScannerConfigObjectDelete for SetDisks {
|
||||
async fn scanner_data_usage_movement_generation(&self) -> Option<u64> {
|
||||
SetDisks::scanner_durable_data_movement_generation(self).await
|
||||
}
|
||||
async fn delete_config_object(
|
||||
&self,
|
||||
bucket: &str,
|
||||
|
||||
@@ -1058,6 +1058,7 @@ impl Drop for ScannerDefaultCycleGuard {
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct MemoryConfigStore {
|
||||
display_progress_generation: Option<u64>,
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
entry_sources: Mutex<Vec<Option<crate::storage_api::ecstore_diagnostic::ReadVersionEntrySource>>>,
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
@@ -5182,6 +5183,9 @@ async fn scanner_backup_sync_distinguishes_movement_from_missing_or_corrupt_prim
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl crate::ScannerConfigObjectDelete for MemoryConfigStore {
|
||||
async fn scanner_data_usage_movement_generation(&self) -> Option<u64> {
|
||||
self.display_progress_generation
|
||||
}
|
||||
async fn delete_config_object(&self, bucket: &str, object: &str, opts: ObjectOptions) -> EcstoreResult<ObjectInfo> {
|
||||
let key = memory_config_key(bucket, object);
|
||||
let mut objects = self.objects.lock().await;
|
||||
|
||||
@@ -3,6 +3,98 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn paged_backup_preparation_stays_inside_the_backup_budget() {
|
||||
let store = Arc::new(MemoryConfigStore::default());
|
||||
let mut cache = seeded();
|
||||
let revisions = DataUsageCache::read_revisions(store.clone(), NAME)
|
||||
.await
|
||||
.expect("initial heads");
|
||||
cache
|
||||
.save_with_revisions_for_epoch(store.clone(), NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("seed primary and backup");
|
||||
let revisions = DataUsageCache::read_revisions(store.clone(), NAME)
|
||||
.await
|
||||
.expect("committed heads");
|
||||
cache.cache.get_mut("bucket/prefix-04095").expect("last leaf").size += 17;
|
||||
let backup = memory_config_key(RUSTFS_META_BUCKET, &format!("{BUCKET_META_PREFIX}/{NAME}.bkp"));
|
||||
store.delayed_gets.lock().await.insert(backup, Duration::from_secs(60));
|
||||
let started = tokio::time::Instant::now();
|
||||
cache
|
||||
.save_with_revisions_for_epoch(store.clone(), NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("primary commit survives a slow best-effort backup");
|
||||
assert!(
|
||||
started.elapsed() <= Duration::from_secs(5),
|
||||
"backup preparation exceeded its entire budget"
|
||||
);
|
||||
let mut loaded = DataUsageCache::default();
|
||||
loaded
|
||||
.load(store, NAME)
|
||||
.await
|
||||
.expect("primary remains readable after backup cancellation");
|
||||
assert_eq!(loaded.checked_flatten("bucket").expect("primary graph").size, 4096 * 4097 / 2 + 17);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn display_progress_retained_compacted_handoff_preserves_measurement_time() {
|
||||
let store = Arc::new(MemoryConfigStore {
|
||||
display_progress_generation: Some(0),
|
||||
..Default::default()
|
||||
});
|
||||
let mut cache = empty_bucket_checkpoint();
|
||||
let plan = DataUsageScanPlanDigest([1; 32]);
|
||||
cache.info.scan_progress = Some(crate::DataUsageScanProgress {
|
||||
started_plan: plan,
|
||||
requested_plan: plan,
|
||||
});
|
||||
let first_source = format!("{}|disk-a", uuid::Uuid::from_u128(1));
|
||||
cache.info.scan_directory_source = Some(first_source);
|
||||
cache.info.last_update = Some(std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(10));
|
||||
let [receipt, _] = crate::scanner_folder::DirectoryCheckpoint::storage_fixture(&cache.info, 4, [2, 3]).await;
|
||||
cache.info.scan_directory_work = vec![receipt];
|
||||
let revisions = DataUsageCache::read_revisions(store.clone(), NAME)
|
||||
.await
|
||||
.expect("initial heads");
|
||||
cache
|
||||
.save_with_revisions_for_epoch(store.clone(), NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("save compacted measurement");
|
||||
let progress_path = memory_config_key(RUSTFS_META_BUCKET, &rustfs_data_usage::bucket_scan_progress_path("bucket"));
|
||||
let original: rustfs_data_usage::BucketScanProgressSource =
|
||||
serde_json::from_slice(&store.objects.lock().await[&progress_path]).expect("original compacted sample");
|
||||
assert_eq!(original.objects, Some(2));
|
||||
for turn in 1..=2 {
|
||||
let mut cold = DataUsageCache::default();
|
||||
let revisions = cold
|
||||
.load_with_revisions(store.clone(), NAME)
|
||||
.await
|
||||
.expect("cold shared handoff");
|
||||
cold.activate_directory_source(
|
||||
format!("{}|disk-b", uuid::Uuid::from_u128(2)),
|
||||
&HashSet::from(["disk-a".into(), "disk-b".into()]),
|
||||
);
|
||||
cold.replace("bucket", "", DataUsageEntry::default());
|
||||
cold.info.leader_epoch += 1;
|
||||
cold.info.last_update = Some(std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(10 + turn * 60));
|
||||
assert!(
|
||||
!cold.info.scan_directory_work.is_empty(),
|
||||
"handoff must retain the previous compacted receipt"
|
||||
);
|
||||
cold.save_with_revisions_for_epoch(store.clone(), NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("save enumerating executor");
|
||||
let sample: rustfs_data_usage::BucketScanProgressSource =
|
||||
serde_json::from_slice(&store.objects.lock().await[&progress_path]).expect("retained compacted sample");
|
||||
assert_eq!((sample.objects, sample.size), (original.objects, original.size));
|
||||
assert_eq!(
|
||||
sample.updated_at, original.updated_at,
|
||||
"checkpoint saves cannot refresh retained measurements"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn indefinite_partial_checkpoints_keep_unreachable_bytes_bounded() {
|
||||
let store = Arc::new(MemoryConfigStore::default());
|
||||
|
||||
@@ -3842,15 +3842,7 @@ pub(crate) async fn scan_data_folder_scoped(
|
||||
if cache.info.scan_progress.is_some() && cache.info.scan_identity.is_some() {
|
||||
use crate::storage_api::owner::EcstoreDiskAPI;
|
||||
let endpoint = local_disk.endpoint().to_string();
|
||||
let source = match wait_for_scanner_io(&ctx, directory_cursor::physical_source(&local_disk)).await {
|
||||
Ok(source) => source?,
|
||||
Err(_) if local_stop.as_ref().is_some_and(|stop| stop.reason().is_some()) => {
|
||||
// The drive can retire before the first directory is read. Keep the
|
||||
// checkpoint so the coordinator can retry against the current drive.
|
||||
return Err(ScannerError::PartialCache(Box::new(cache)));
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let source = wait_for_scanner_io(&ctx, directory_cursor::physical_source(&local_disk)).await??;
|
||||
let mut endpoints: HashSet<_> = disks.iter().map(|disk| disk.endpoint().to_string()).collect();
|
||||
endpoints.insert(endpoint);
|
||||
cache.activate_directory_source(source, &endpoints);
|
||||
@@ -4059,6 +4051,7 @@ pub(crate) async fn scan_data_folder_scoped(
|
||||
new_cache.info.scan_directory_source = None;
|
||||
new_cache.info.scan_source_trees.clear();
|
||||
new_cache.info.scan_coverage_receipt = None;
|
||||
new_cache.info.scan_coverage_measured_at = None;
|
||||
if had_scan_checkpoint {
|
||||
global_metrics().record_scanner_checkpoint_cleared();
|
||||
}
|
||||
@@ -4119,6 +4112,7 @@ pub(crate) async fn scan_data_folder_scoped(
|
||||
new_cache.info.scan_checkpoint = None;
|
||||
new_cache.info.scan_resume_after = None;
|
||||
new_cache.info.scan_coverage_receipt = None;
|
||||
new_cache.info.scan_coverage_measured_at = None;
|
||||
}
|
||||
if raw_enumeration_page_index.is_some() {
|
||||
new_cache.info.scan_raw_enumeration_page_index = raw_enumeration_page_index;
|
||||
@@ -4126,6 +4120,7 @@ pub(crate) async fn scan_data_folder_scoped(
|
||||
new_cache.info.scan_checkpoint = None;
|
||||
new_cache.info.scan_resume_after = None;
|
||||
new_cache.info.scan_coverage_receipt = None;
|
||||
new_cache.info.scan_coverage_measured_at = None;
|
||||
}
|
||||
if partial_cache_is_useful(&root, pending_heals_changed)
|
||||
|| !new_cache.info.scan_directory_work.is_empty()
|
||||
|
||||
@@ -195,6 +195,7 @@ pub(super) struct DirectoryWork {
|
||||
// The final compaction threshold caps how many paths this list can hold.
|
||||
pub(super) linked: Vec<String>,
|
||||
pub(super) compacted_total: super::DataUsageEntry,
|
||||
pub(super) measured_at: Option<u64>,
|
||||
pub(super) gap: bool,
|
||||
compacted: bool,
|
||||
recorder: Option<Recorder>,
|
||||
@@ -225,6 +226,9 @@ impl DirectoryWork {
|
||||
pub(super) fn acknowledge(&mut self, name: &str, linked: bool, compacted: bool) {
|
||||
if self.names.acknowledge() {
|
||||
self.compacted = compacted;
|
||||
if compacted {
|
||||
self.measured_at = crate::data_usage_define::scan_measurement_time_millis(std::time::SystemTime::now());
|
||||
}
|
||||
if linked && !compacted {
|
||||
self.linked.push(name.to_owned());
|
||||
}
|
||||
@@ -236,6 +240,7 @@ impl DirectoryWork {
|
||||
self.names.rewind();
|
||||
self.linked.clear();
|
||||
self.compacted_total = super::DataUsageEntry::default();
|
||||
self.measured_at = None;
|
||||
self.gap = false;
|
||||
}
|
||||
}
|
||||
@@ -467,6 +472,7 @@ impl ScannerDirectory {
|
||||
if let Some(aggregate) = &saved.aggregate {
|
||||
work.compacted = true;
|
||||
work.compacted_total = aggregate.value.clone();
|
||||
work.measured_at = saved.measured_at;
|
||||
}
|
||||
let physical_path: Arc<Path> = Arc::from(Path::new(path));
|
||||
if let Some(part) = &saved.part {
|
||||
|
||||
@@ -9,6 +9,7 @@ use super::{DirectoryScope, DirectoryStamp, DirectoryWork, FolderScanMode, nativ
|
||||
use crate::data_usage_define::{
|
||||
DataUsageCacheInfo, DataUsageCacheSource, DataUsageEntry, DataUsageScanIdentity, DataUsageScanProgress,
|
||||
};
|
||||
use serde::ser::{SerializeMap, SerializeStruct};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
@@ -109,7 +110,7 @@ pub(super) struct Aggregate {
|
||||
|
||||
/// Immutable directory membership and the last fully counted compacted child.
|
||||
/// The active child's provisional contribution is never part of this receipt.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct DirectoryCheckpoint {
|
||||
version: u8,
|
||||
pub(super) parent: String,
|
||||
@@ -124,6 +125,53 @@ pub struct DirectoryCheckpoint {
|
||||
pub(super) aggregate: Option<Aggregate>,
|
||||
endpoint: String,
|
||||
digest: [u8; 32],
|
||||
/// Diagnostic time of the last acknowledged aggregate, never a save time.
|
||||
#[serde(default)]
|
||||
pub(super) measured_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl Serialize for DirectoryCheckpoint {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
if self.measured_at.is_none() {
|
||||
// Enumeration-only receipts retain the compact version-one bytes
|
||||
// so optional diagnostics do not enlarge each name-budget quantum.
|
||||
let mut state = serializer.serialize_struct("DirectoryCheckpoint", 13)?;
|
||||
state.serialize_field("version", &self.version)?;
|
||||
state.serialize_field("parent", &self.parent)?;
|
||||
state.serialize_field("scope", &self.scope)?;
|
||||
state.serialize_field("physical", &self.physical)?;
|
||||
state.serialize_field("pages", &self.pages)?;
|
||||
state.serialize_field("anchor", &self.anchor)?;
|
||||
state.serialize_field("entries_read", &self.entries_read)?;
|
||||
state.serialize_field("sealed", &self.sealed)?;
|
||||
state.serialize_field("part", &self.part)?;
|
||||
state.serialize_field("metadata", &self.metadata)?;
|
||||
state.serialize_field("aggregate", &self.aggregate)?;
|
||||
state.serialize_field("endpoint", &self.endpoint)?;
|
||||
state.serialize_field("digest", &self.digest)?;
|
||||
return state.end();
|
||||
}
|
||||
// Version-one readers accept named fields and ignore this additive
|
||||
// diagnostic field. Keep the existing coverage checksum unchanged.
|
||||
let mut map = serializer.serialize_map(Some(13 + usize::from(self.measured_at.is_some())))?;
|
||||
map.serialize_entry("version", &self.version)?;
|
||||
map.serialize_entry("parent", &self.parent)?;
|
||||
map.serialize_entry("scope", &self.scope)?;
|
||||
map.serialize_entry("physical", &self.physical)?;
|
||||
map.serialize_entry("pages", &self.pages)?;
|
||||
map.serialize_entry("anchor", &self.anchor)?;
|
||||
map.serialize_entry("entries_read", &self.entries_read)?;
|
||||
map.serialize_entry("sealed", &self.sealed)?;
|
||||
map.serialize_entry("part", &self.part)?;
|
||||
map.serialize_entry("metadata", &self.metadata)?;
|
||||
map.serialize_entry("aggregate", &self.aggregate)?;
|
||||
map.serialize_entry("endpoint", &self.endpoint)?;
|
||||
map.serialize_entry("digest", &self.digest)?;
|
||||
if let Some(measured_at) = self.measured_at {
|
||||
map.serialize_entry("measured_at", &measured_at)?;
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical progress orders only callbacks from the same directory generation.
|
||||
@@ -251,6 +299,10 @@ impl DirectoryCheckpoint {
|
||||
through: done.through.clone(),
|
||||
})
|
||||
}
|
||||
/// A display contribution contains only acknowledged compacted children.
|
||||
pub(crate) fn display_usage(&self, info: &DataUsageCacheInfo) -> Option<(DirectoryProgress, &DataUsageEntry, Option<u64>)> {
|
||||
Some((self.progress(info)?, &self.aggregate.as_ref()?.value, self.measured_at))
|
||||
}
|
||||
pub(crate) fn endpoint(&self) -> &str {
|
||||
&self.endpoint
|
||||
}
|
||||
@@ -348,6 +400,7 @@ impl Recorder {
|
||||
aggregate,
|
||||
endpoint: self.endpoint.clone(),
|
||||
digest: [0; 32],
|
||||
measured_at: work.measured_at,
|
||||
};
|
||||
checkpoint.checksum().map(|digest| {
|
||||
checkpoint.digest = digest;
|
||||
|
||||
@@ -5,6 +5,10 @@ use super::*;
|
||||
|
||||
impl DirectoryCheckpoint {
|
||||
pub(crate) async fn wide_storage_fixture(info: &DataUsageCacheInfo) -> [Self; 2] {
|
||||
Self::storage_fixture(info, 300_000, [121_034, 121_035]).await
|
||||
}
|
||||
|
||||
pub(crate) async fn storage_fixture(info: &DataUsageCacheInfo, width: usize, completed: [usize; 2]) -> [Self; 2] {
|
||||
let scope = Scope {
|
||||
bucket: info.name.clone(),
|
||||
source: info.source.expect("fixture source"),
|
||||
@@ -24,20 +28,23 @@ impl DirectoryCheckpoint {
|
||||
modified: SystemTime::UNIX_EPOCH,
|
||||
};
|
||||
let mut recorder = Recorder::new(slot.clone(), &info.name, scope, endpoint, Some(physical), None);
|
||||
recorder.entries_read = 300_000;
|
||||
recorder.entries_read = u64::try_from(width).expect("fixture width");
|
||||
let mut work = DirectoryWork {
|
||||
compacted: true,
|
||||
..Default::default()
|
||||
};
|
||||
for i in 0..300_000 {
|
||||
for i in 0..width {
|
||||
work.names.add(format!("obj-{i:06}"));
|
||||
work.names.flush_full().await.expect("record real immutable name page");
|
||||
}
|
||||
work.names.finish();
|
||||
[121_034, 121_035].map(|objects| {
|
||||
completed.map(|objects| {
|
||||
work.names.seek_after(Some(&format!("obj-{:06}", objects - 1)));
|
||||
work.compacted_total.objects = objects;
|
||||
work.compacted_total.size = objects * 1024;
|
||||
work.measured_at = info
|
||||
.last_update
|
||||
.and_then(crate::data_usage_define::scan_measurement_time_millis);
|
||||
recorder.save(&work);
|
||||
slot.lock()
|
||||
.expect("fixture slot")
|
||||
@@ -46,3 +53,60 @@ impl DirectoryCheckpoint {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct LegacyCheckpoint {
|
||||
version: u8,
|
||||
parent: String,
|
||||
scope: Scope,
|
||||
physical: Option<Physical>,
|
||||
pages: Vec<NamePage>,
|
||||
anchor: Option<native_io::DirectoryAnchor>,
|
||||
entries_read: u64,
|
||||
sealed: bool,
|
||||
part: Option<String>,
|
||||
metadata: bool,
|
||||
aggregate: Option<Aggregate>,
|
||||
endpoint: String,
|
||||
digest: [u8; 32],
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
|
||||
let plan = crate::DataUsageScanPlanDigest([1; 32]);
|
||||
let info = DataUsageCacheInfo {
|
||||
name: "bucket".into(),
|
||||
source: Some(DataUsageCacheSource::new(0, 0)),
|
||||
scan_identity: Some(DataUsageScanIdentity {
|
||||
version: crate::data_usage_define::DATA_USAGE_SCAN_CHECKPOINT_VERSION,
|
||||
bucket_incarnation: uuid::Uuid::from_u128(1),
|
||||
set_layout: crate::DataUsageScanPlanDigest([7; 32]),
|
||||
publication_epoch: 0,
|
||||
tier_registry_generation: 1,
|
||||
scan_mode: rustfs_heal_contracts::heal_channel::HealScanMode::Normal,
|
||||
}),
|
||||
scan_progress: Some(DataUsageScanProgress {
|
||||
started_plan: plan,
|
||||
requested_plan: plan,
|
||||
}),
|
||||
scan_directory_source: Some("disk-a".into()),
|
||||
last_update: Some(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(10)),
|
||||
..Default::default()
|
||||
};
|
||||
let [checkpoint, _] = DirectoryCheckpoint::storage_fixture(&info, 4, [2, 3]).await;
|
||||
assert_eq!(checkpoint.measured_at, Some(10_000));
|
||||
let bytes = rmp_serde::to_vec(&checkpoint).expect("encode additive named checkpoint");
|
||||
let legacy: LegacyCheckpoint = rmp_serde::from_slice(&bytes).expect("version-one reader ignores measurement metadata");
|
||||
let old_bytes = rmp_serde::to_vec(&legacy).expect("encode legacy positional checkpoint");
|
||||
let recovered: DirectoryCheckpoint = rmp_serde::from_slice(&old_bytes).expect("new reader accepts legacy receipt");
|
||||
assert_eq!(recovered.measured_at, None);
|
||||
assert_eq!(
|
||||
rmp_serde::to_vec(&recovered).expect("encode receipt without measurement metadata"),
|
||||
old_bytes,
|
||||
"receipts without diagnostic metadata keep the compact legacy encoding"
|
||||
);
|
||||
assert!(
|
||||
recovered.is_bound_to(&info),
|
||||
"diagnostic metadata must not change the version-one coverage checksum"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ fn scan_options(scan_mode: HealScanMode) -> ScannerDiskScanOptions {
|
||||
|
||||
/// Real cache persistence codec and CAS calls, backed by two bounded local files.
|
||||
#[derive(Debug)]
|
||||
struct FixtureStore {
|
||||
pub(super) struct FixtureStore {
|
||||
root: std::path::PathBuf,
|
||||
_owned_root: Option<tempfile::TempDir>,
|
||||
reject_save: AtomicBool,
|
||||
@@ -62,7 +62,7 @@ impl FixtureStore {
|
||||
})
|
||||
}
|
||||
|
||||
fn reopen(root: std::path::PathBuf) -> Arc<Self> {
|
||||
pub(super) fn reopen(root: std::path::PathBuf) -> Arc<Self> {
|
||||
assert!(root.is_dir(), "reopen only an existing checkpoint fixture directory");
|
||||
Arc::new(Self {
|
||||
root,
|
||||
@@ -72,6 +72,9 @@ impl FixtureStore {
|
||||
}
|
||||
|
||||
fn path(&self, object: &str) -> std::path::PathBuf {
|
||||
if object == rustfs_data_usage::bucket_scan_progress_path("bucket") {
|
||||
return self.root.join("progress");
|
||||
}
|
||||
assert!(object.ends_with(CACHE_NAME) || object.ends_with(&format!("{CACHE_NAME}.bkp")));
|
||||
self.root.join(if object.ends_with(".bkp") { "backup" } else { "main" })
|
||||
}
|
||||
@@ -153,6 +156,9 @@ impl ObjectIO for FixtureStore {
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl crate::ScannerConfigObjectDelete for FixtureStore {
|
||||
async fn scanner_data_usage_movement_generation(&self) -> Option<u64> {
|
||||
Some(0)
|
||||
}
|
||||
async fn delete_config_object(
|
||||
&self,
|
||||
_bucket: &str,
|
||||
@@ -293,6 +299,129 @@ fn bound_checkpoint() -> (DataUsageCache, crate::DataUsageScanIdentity) {
|
||||
(cache, identity)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn display_progress_only_advances_after_a_durable_primary_commit() {
|
||||
let directory = tempfile::tempdir().expect("owned checkpoint storage");
|
||||
let writer = FixtureStore::reopen(directory.path().to_owned());
|
||||
let (mut cache, _) = bound_checkpoint();
|
||||
cache.info.last_update = Some(SystemTime::now());
|
||||
cache.info.scan_directory_source = Some("fixture".into());
|
||||
let revisions = DataUsageCache::default()
|
||||
.load_with_revisions(writer.clone(), CACHE_NAME)
|
||||
.await
|
||||
.expect("missing primary revisions");
|
||||
cache
|
||||
.save_with_revisions_for_epoch(writer.clone(), CACHE_NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("commit primary and display sample");
|
||||
let before = tokio::fs::read(directory.path().join("progress"))
|
||||
.await
|
||||
.expect("saved progress");
|
||||
let revisions = DataUsageCache::default()
|
||||
.load_with_revisions(writer.clone(), CACHE_NAME)
|
||||
.await
|
||||
.expect("committed revisions");
|
||||
cache.info.leader_epoch += 1;
|
||||
cache.info.last_update = Some(SystemTime::now());
|
||||
writer.reject_save.store(true, Ordering::SeqCst);
|
||||
assert!(
|
||||
cache
|
||||
.save_with_revisions_for_epoch(writer.clone(), CACHE_NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
tokio::fs::read(directory.path().join("progress"))
|
||||
.await
|
||||
.expect("unchanged progress"),
|
||||
before
|
||||
);
|
||||
drop(writer);
|
||||
let cold_reader = FixtureStore::reopen(directory.path().to_owned());
|
||||
let mut loaded = DataUsageCache::default();
|
||||
loaded
|
||||
.load(cold_reader.clone(), CACHE_NAME)
|
||||
.await
|
||||
.expect("cold primary reload");
|
||||
let sample: rustfs_data_usage::BucketScanProgressSource = serde_json::from_slice(
|
||||
&tokio::fs::read(cold_reader.root.join("progress"))
|
||||
.await
|
||||
.expect("cold display reload"),
|
||||
)
|
||||
.expect("valid cold display sample");
|
||||
assert_eq!(loaded.display_scan_progress(0), Some(sample));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn display_progress_keeps_reference_during_executor_enumeration_then_replaces_it_on_completion() {
|
||||
let directory = tempfile::tempdir().expect("owned checkpoint storage");
|
||||
let writer = FixtureStore::reopen(directory.path().to_owned());
|
||||
let (mut cache, _) = bound_checkpoint();
|
||||
let original_time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
|
||||
cache.info.last_update = Some(original_time);
|
||||
cache.info.scan_coverage_measured_at = Some(10_000);
|
||||
cache.info.scan_directory_source = Some("first-executor".into());
|
||||
let mut revisions = DataUsageCache::default()
|
||||
.load_with_revisions(writer.clone(), CACHE_NAME)
|
||||
.await
|
||||
.expect("initial revision");
|
||||
cache
|
||||
.save_with_revisions_for_epoch(writer.clone(), CACHE_NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("save accepted prefix");
|
||||
revisions = DataUsageCache::read_revisions(writer.clone(), CACHE_NAME)
|
||||
.await
|
||||
.expect("accepted revision");
|
||||
cache.cache.clear();
|
||||
cache.replace("bucket", "", DataUsageEntry::default());
|
||||
cache.info.scan_resume_after = None;
|
||||
cache.info.scan_checkpoint = None;
|
||||
cache.info.scan_coverage_receipt = None;
|
||||
cache.info.scan_directory_source = Some("next-executor".into());
|
||||
cache.info.leader_epoch += 1;
|
||||
cache.info.last_update = Some(original_time + Duration::from_secs(10));
|
||||
assert_eq!(cache.display_scan_progress(0).expect("enumeration sample").objects, None);
|
||||
for _ in 0..2 {
|
||||
cache
|
||||
.save_with_revisions_for_epoch(writer.clone(), CACHE_NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("save reenumeration");
|
||||
revisions = DataUsageCache::read_revisions(writer.clone(), CACHE_NAME)
|
||||
.await
|
||||
.expect("enumeration revision");
|
||||
let bytes = tokio::fs::read(directory.path().join("progress"))
|
||||
.await
|
||||
.expect("shared reference sample");
|
||||
let sample: rustfs_data_usage::BucketScanProgressSource = serde_json::from_slice(&bytes).expect("reference progress");
|
||||
assert_eq!(sample.objects, Some(3));
|
||||
assert_eq!(sample.updated_at, 10_000, "carrying an observation never refreshes its measurement time");
|
||||
}
|
||||
cache.info.snapshot_complete = true;
|
||||
cache.replace(
|
||||
"bucket",
|
||||
"",
|
||||
DataUsageEntry {
|
||||
objects: 1,
|
||||
size: 11,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
cache
|
||||
.save_with_revisions_for_epoch(writer, CACHE_NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("save completed smaller measurement");
|
||||
let bytes = tokio::fs::read(directory.path().join("progress"))
|
||||
.await
|
||||
.expect("completed sample");
|
||||
let sample: rustfs_data_usage::BucketScanProgressSource = serde_json::from_slice(&bytes).expect("completed progress");
|
||||
assert_eq!(
|
||||
(sample.objects, sample.size),
|
||||
(Some(1), Some(11)),
|
||||
"completion replaces old samples even after deletions"
|
||||
);
|
||||
assert_eq!(sample.stage, rustfs_data_usage::BucketScanStage::Completed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkpoint_fixture_roundtrip_retains_verified_scope_but_old_reader_rebuilds() {
|
||||
let (cache, identity) = bound_checkpoint();
|
||||
|
||||
@@ -36,7 +36,16 @@ async fn scan(
|
||||
(outcome, budget)
|
||||
}
|
||||
|
||||
async fn read_display_progress(store: &FixtureStore) -> Option<rustfs_data_usage::BucketScanProgressSource> {
|
||||
match tokio::fs::read(store.root.join("progress")).await {
|
||||
Ok(bytes) => Some(serde_json::from_slice(&bytes).expect("decode independent display progress")),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(error) => panic!("read durable display progress: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn save_reload(store: &Arc<FixtureStore>, cache: &DataUsageCache) -> DataUsageCache {
|
||||
let previous = read_display_progress(store).await;
|
||||
let revisions = DataUsageCache::default()
|
||||
.load_with_revisions(store.clone(), CACHE_NAME)
|
||||
.await
|
||||
@@ -46,6 +55,13 @@ async fn save_reload(store: &Arc<FixtureStore>, cache: &DataUsageCache) -> DataU
|
||||
.await
|
||||
.expect("save compacted checkpoint through real codec and revision checks");
|
||||
let loaded = store.strict_load().await;
|
||||
let restarted_store = FixtureStore::reopen(store.root.clone());
|
||||
let progress = read_display_progress(&restarted_store).await;
|
||||
if let Some(expected) = loaded.display_scan_progress(0) {
|
||||
assert_eq!(progress, Some(expected), "accepted progress survives a cold store reopen");
|
||||
} else {
|
||||
assert_eq!(progress, previous, "unverified legacy coverage must not publish a new sample");
|
||||
}
|
||||
assert_eq!(loaded.info.snapshot_complete, cache.info.snapshot_complete);
|
||||
assert_eq!(loaded.info.scan_checkpoint, cache.info.scan_checkpoint);
|
||||
assert_eq!(loaded.info.scan_identity, cache.info.scan_identity);
|
||||
|
||||
@@ -404,6 +404,14 @@ async fn cold_compacted_replicas_finish_within_their_independent_object_budgets(
|
||||
);
|
||||
}
|
||||
cache = step.outcome;
|
||||
let sample = cache.display_scan_progress(0).expect("durable cross-executor display sample");
|
||||
if let (Some(objects), Some(size)) = (sample.objects, sample.size) {
|
||||
assert!(objects <= 40, "physical replicas cannot inflate logical progress");
|
||||
assert_eq!(size, objects);
|
||||
}
|
||||
let encoded = cache.marshal_msg().expect("persist cross-executor display source");
|
||||
let cold = DataUsageCache::unmarshal(&encoded).expect("cold cross-executor display source");
|
||||
assert_eq!(cold.display_scan_progress(0), Some(sample));
|
||||
if step.finished {
|
||||
assert!(round > 1);
|
||||
assert!(cache.info.snapshot_complete);
|
||||
@@ -417,6 +425,168 @@ async fn cold_compacted_replicas_finish_within_their_independent_object_budgets(
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Each turn runs in another OS process and alternates the physical executor.
|
||||
/// Only the committed checkpoint and compact display object cross turns.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn display_progress_survives_process_restarts_leader_changes_and_repeated_reads() {
|
||||
use super::checkpoint_fixture::FixtureStore;
|
||||
const CHILD_ROOT: &str = "RUSTFS_TEST_SCAN_PROGRESS_CHILD_ROOT";
|
||||
const CHILD_ROUND: &str = "RUSTFS_TEST_SCAN_PROGRESS_CHILD_ROUND";
|
||||
const CACHE_NAME: &str = "bucket/checkpoint-fixture.bin";
|
||||
if let Some(root) = std::env::var_os(CHILD_ROOT) {
|
||||
let root = std::path::PathBuf::from(root);
|
||||
assert!(
|
||||
root.file_name()
|
||||
.expect("owned temporary root")
|
||||
.to_string_lossy()
|
||||
.starts_with("rustfs-progress-restart-")
|
||||
);
|
||||
let round: u64 = std::env::var(CHILD_ROUND)
|
||||
.expect("explicit child round")
|
||||
.parse()
|
||||
.expect("numeric round");
|
||||
let store = FixtureStore::reopen(root.join("cache"));
|
||||
let mut cache = DataUsageCache::default();
|
||||
let revisions = cache
|
||||
.load_with_revisions(store.clone(), CACHE_NAME)
|
||||
.await
|
||||
.expect("cold shared checkpoint load");
|
||||
let identity = cache.info.scan_identity.expect("durable bucket identity");
|
||||
let prepared = cache.prepare_bucket_checkpoint(
|
||||
"bucket",
|
||||
round + 2,
|
||||
round + 1,
|
||||
crate::DataUsageCacheSource::new(0, 0),
|
||||
crate::DataUsageScanPlanDigest([31; 32]),
|
||||
identity,
|
||||
);
|
||||
if round > 0 {
|
||||
assert_eq!(prepared, crate::data_usage_define::DataUsageCachePrepareOutcome::Reused);
|
||||
}
|
||||
// Synthetic disks have no healing metadata. Reapply the fixture's
|
||||
// scan options after prepare, which may reset the initial empty cache.
|
||||
cache.info.skip_healing = true;
|
||||
SCANNER_SLEEPER.disable_disk_io_budget_for_tests();
|
||||
let (active, peer) = if round.is_multiple_of(2) {
|
||||
(root.join("a"), root.join("b"))
|
||||
} else {
|
||||
(root.join("b"), root.join("a"))
|
||||
};
|
||||
let step = super::super::TEST_FORCE_COMPACTION_WIDTH
|
||||
.scope(
|
||||
16,
|
||||
scan_one_replica_round(
|
||||
&active,
|
||||
Some(&peer),
|
||||
cache,
|
||||
ScannerCycleBudgetConfig {
|
||||
max_objects: Some(6),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
)
|
||||
.await;
|
||||
step.outcome
|
||||
.save_with_revisions_for_epoch(store, CACHE_NAME, &revisions, 0, CancellationToken::new())
|
||||
.await
|
||||
.expect("commit checkpoint and display progress");
|
||||
let bytes = tokio::fs::read(root.join("cache/progress"))
|
||||
.await
|
||||
.expect("durable progress after primary commit");
|
||||
let sample: rustfs_data_usage::BucketScanProgressSource =
|
||||
serde_json::from_slice(&bytes).expect("decode durable display sample");
|
||||
if let Some(objects) = sample.objects {
|
||||
assert!(objects <= 40, "physical replicas cannot double count objects");
|
||||
assert_eq!(sample.size, Some(objects));
|
||||
}
|
||||
let repeated: rustfs_data_usage::BucketScanProgressSource = serde_json::from_slice(
|
||||
&tokio::fs::read(root.join("cache/progress"))
|
||||
.await
|
||||
.expect("repeat independent progress read"),
|
||||
)
|
||||
.expect("decode repeated sample");
|
||||
assert_eq!(sample, repeated);
|
||||
if step.finished {
|
||||
assert_eq!((sample.objects, sample.size), (Some(40), Some(40)));
|
||||
assert_eq!(sample.stage, rustfs_data_usage::BucketScanStage::Completed);
|
||||
}
|
||||
tokio::fs::write(
|
||||
root.join("result.json"),
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"pid": std::process::id(), "finished": step.finished, "sample": sample,
|
||||
}))
|
||||
.expect("encode child result"),
|
||||
)
|
||||
.await
|
||||
.expect("commit child result");
|
||||
return;
|
||||
}
|
||||
let temp = tempfile::Builder::new()
|
||||
.prefix("rustfs-progress-restart-")
|
||||
.tempdir()
|
||||
.expect("owned restart fixture");
|
||||
let root = temp.path();
|
||||
let mut initial = seed_flat_bucket(&root.join("a"), 40).await;
|
||||
seed_flat_bucket(&root.join("b"), 40).await;
|
||||
let mut identity = initial.info.scan_identity.expect("initial identity");
|
||||
identity.publication_epoch = 0;
|
||||
identity.tier_registry_generation = crate::runtime_tier_registry_for_cycle(1, 0).await.generation;
|
||||
initial.prepare_bucket_checkpoint(
|
||||
"bucket",
|
||||
1,
|
||||
0,
|
||||
crate::DataUsageCacheSource::new(0, 0),
|
||||
crate::DataUsageScanPlanDigest([31; 32]),
|
||||
identity,
|
||||
);
|
||||
initial.replace("bucket", "", DataUsageEntry::default());
|
||||
tokio::fs::create_dir(root.join("cache"))
|
||||
.await
|
||||
.expect("fresh checkpoint storage");
|
||||
tokio::fs::write(root.join("cache/main"), initial.marshal_msg().expect("initial checkpoint encoding"))
|
||||
.await
|
||||
.expect("persist initial checkpoint");
|
||||
let name = format!(
|
||||
"{}::display_progress_survives_process_restarts_leader_changes_and_repeated_reads",
|
||||
module_path!().split_once("::").expect("crate-qualified module").1
|
||||
);
|
||||
let mut pids = std::collections::HashSet::new();
|
||||
for round in 0..20 {
|
||||
let mut command = tokio::process::Command::new(std::env::current_exe().expect("current libtest binary"));
|
||||
command
|
||||
.arg("--exact")
|
||||
.arg(&name)
|
||||
.arg("--nocapture")
|
||||
.env(CHILD_ROOT, root)
|
||||
.env(CHILD_ROUND, round.to_string())
|
||||
.kill_on_drop(true);
|
||||
let output = tokio::time::timeout(Duration::from_secs(30), command.output())
|
||||
.await
|
||||
.expect("bounded child scan turn")
|
||||
.expect("launch child process");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"child round {round}: {} {}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let result: serde_json::Value =
|
||||
serde_json::from_slice(&tokio::fs::read(root.join("result.json")).await.expect("child result exists"))
|
||||
.expect("decode child result");
|
||||
let pid = result["pid"].as_u64().expect("child process id");
|
||||
assert_ne!(pid, u64::from(std::process::id()));
|
||||
assert!(pids.insert(pid), "every turn must run after the previous executor exits");
|
||||
if result["finished"] == true {
|
||||
assert!(round > 1, "the fixed six-object budget must require multiple process restarts");
|
||||
assert_eq!(result["sample"]["objects"], 40);
|
||||
assert_eq!(result["sample"]["size"], 40);
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("cold alternating executors must finish within their fixed per-turn budgets");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn cold_compacted_identical_names_do_not_mix_replica_version_sizes() {
|
||||
|
||||
@@ -32,8 +32,10 @@ async fn retire(probe: &Probe, disk: &Arc<Disk>) {
|
||||
)
|
||||
.await
|
||||
.expect("replacement wrapper");
|
||||
let identity = disk.get_disk_id().await.expect("read old identity").expect("formatted drive");
|
||||
assert_eq!(next.get_disk_id().await.expect("read replacement identity"), Some(identity));
|
||||
assert_eq!(
|
||||
next.get_disk_id().await.expect("replacement identity"),
|
||||
disk.get_disk_id().await.expect("old identity")
|
||||
);
|
||||
Some(next)
|
||||
} else {
|
||||
None
|
||||
@@ -87,8 +89,8 @@ impl Drop for RegisteredProbe {
|
||||
}
|
||||
}
|
||||
|
||||
async fn recovery_fixture(bucket: &str, before: bool, replace: bool, faulty: bool, eof: bool) -> Option<(usize, DataUsageEntry)> {
|
||||
let (dir, store) = setup_local_scanner_store(1, 1).await;
|
||||
async fn recovery_fixture(bucket: &str, before: bool, replace: bool, faulty: bool, eof: bool) {
|
||||
let (_dir, store) = setup_local_scanner_store(1, 1).await;
|
||||
clear_dirty_usage_buckets_for_tests();
|
||||
for name in [bucket, "unaffected-bucket"] {
|
||||
store
|
||||
@@ -118,12 +120,15 @@ async fn recovery_fixture(bucket: &str, before: bool, replace: bool, faulty: boo
|
||||
.lock()
|
||||
.expect("probe registry")
|
||||
.insert(bucket.to_string(), probe.clone());
|
||||
let registered = RegisteredProbe(bucket.to_string());
|
||||
let _registered = RegisteredProbe(bucket.to_string());
|
||||
let status = run_full_cycle(&store, 1).await;
|
||||
let attempts = probe.attempts.load(Ordering::SeqCst);
|
||||
let recovered = if replace || faulty {
|
||||
if replace || faulty {
|
||||
assert_eq!(status, ScannerCycleStatus::Complete);
|
||||
assert_eq!(attempts, 2, "one recovery attempt including zero-progress interruption");
|
||||
assert_eq!(
|
||||
probe.attempts.load(Ordering::SeqCst),
|
||||
2,
|
||||
"one recovery attempt including zero-progress interruption"
|
||||
);
|
||||
let mut cache = DataUsageCache::default();
|
||||
cache
|
||||
.load(set, &path_join_buf(&[bucket, DATA_USAGE_CACHE_NAME]))
|
||||
@@ -133,65 +138,41 @@ async fn recovery_fixture(bucket: &str, before: bool, replace: bool, faulty: boo
|
||||
let total = cache.checked_flatten(bucket).expect("complete recovered statistics");
|
||||
assert_eq!(total.objects, 3);
|
||||
assert_eq!(total.size, 21);
|
||||
Some((attempts, total))
|
||||
} else {
|
||||
assert_ne!(status, ScannerCycleStatus::Complete, "retired drive cannot certify completion");
|
||||
assert_eq!(attempts, 1, "no repeated scans on a retired wrapper");
|
||||
None
|
||||
};
|
||||
assert_eq!(probe.attempts.load(Ordering::SeqCst), 1, "no repeated scans on a retired wrapper");
|
||||
}
|
||||
clear_dirty_usage_buckets_for_tests();
|
||||
drop(registered);
|
||||
drop(probe);
|
||||
drop(store);
|
||||
dir.close().expect("remove recovery fixture");
|
||||
recovered
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn issue_9469_recovers_retired_wrapper_before_first_object() {
|
||||
let (attempts, total) = recovery_fixture("recovery-first", true, true, false, false)
|
||||
.await
|
||||
.expect("retired wrapper recovered");
|
||||
println!(
|
||||
"usage_assertion: {}",
|
||||
serde_json::json!({
|
||||
"case_id": "USAGE-21",
|
||||
"assertion_id": "USAGE-21-A01",
|
||||
"status": "PASS",
|
||||
"evidence": {
|
||||
"same_format_identity": true,
|
||||
"attempts": attempts,
|
||||
"durable_objects": total.objects,
|
||||
"durable_bytes": total.size,
|
||||
}
|
||||
})
|
||||
);
|
||||
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-21", "status": "PASS"}));
|
||||
recovery_fixture("recovery-first", true, true, false, false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn issue_9469_recovers_retired_wrapper_in_deep_subtree() {
|
||||
let _ = recovery_fixture("recovery-deep", false, true, false, false).await;
|
||||
recovery_fixture("recovery-deep", false, true, false, false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn issue_9469_persistent_retirement_is_bounded() {
|
||||
let _ = recovery_fixture("recovery-offline", true, false, false, false).await;
|
||||
recovery_fixture("recovery-offline", true, false, false, false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn issue_9469_faulty_metadata_stops_and_retries_without_losing_object() {
|
||||
let _ = recovery_fixture("recovery-faulty", false, false, true, false).await;
|
||||
recovery_fixture("recovery-faulty", false, false, true, false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn issue_9469_retirement_at_eof_cannot_certify_old_handle() {
|
||||
let _ = recovery_fixture("recovery-eof", false, true, false, true).await;
|
||||
recovery_fixture("recovery-eof", false, true, false, true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -21,7 +21,6 @@ async fn put_fixture_object(store: &Arc<ECStore>, bucket: &str, object: &str) {
|
||||
|
||||
struct CycleHooks {
|
||||
resolved_scope_observer: Option<tokio::sync::oneshot::Sender<ScannerBucketScanScope>>,
|
||||
post_walk_hook: Option<Box<dyn FnOnce() + Send>>,
|
||||
post_walk_gate: Option<tokio::sync::oneshot::Receiver<()>>,
|
||||
peer_observations: Option<super::super::io_cycle::ScannerCyclePeerObservations>,
|
||||
}
|
||||
@@ -55,7 +54,7 @@ async fn run_cycle(
|
||||
requires_full_scan,
|
||||
service_cohort: None,
|
||||
resolved_scope_observer: hooks.resolved_scope_observer,
|
||||
post_walk_hook: hooks.post_walk_hook,
|
||||
post_walk_hook: None,
|
||||
post_walk_gate: hooks.post_walk_gate,
|
||||
peer_observations: hooks.peer_observations,
|
||||
},
|
||||
@@ -68,7 +67,7 @@ async fn run_cycle(
|
||||
assert_eq!(
|
||||
result.status,
|
||||
ScannerCycleStatus::Complete,
|
||||
"cycle {cycle} must certify cold buckets: {result:?}"
|
||||
"one remote hot bucket cannot supersede certified cold buckets"
|
||||
);
|
||||
}
|
||||
let snapshot = receiver.recv().await.expect("cycle should publish a snapshot");
|
||||
@@ -103,7 +102,6 @@ async fn write_during_walk_leaves_only_that_bucket_pending_and_scopes_the_next_c
|
||||
true,
|
||||
CycleHooks {
|
||||
resolved_scope_observer: None,
|
||||
post_walk_hook: None,
|
||||
post_walk_gate: None,
|
||||
peer_observations: None,
|
||||
},
|
||||
@@ -142,7 +140,6 @@ async fn write_during_walk_leaves_only_that_bucket_pending_and_scopes_the_next_c
|
||||
false,
|
||||
CycleHooks {
|
||||
resolved_scope_observer: Some(observer),
|
||||
post_walk_hook: None,
|
||||
post_walk_gate: Some(gate),
|
||||
peer_observations: None,
|
||||
},
|
||||
@@ -191,7 +188,6 @@ async fn write_during_walk_leaves_only_that_bucket_pending_and_scopes_the_next_c
|
||||
false,
|
||||
CycleHooks {
|
||||
resolved_scope_observer: Some(observer),
|
||||
post_walk_hook: None,
|
||||
post_walk_gate: None,
|
||||
peer_observations: None,
|
||||
},
|
||||
@@ -244,7 +240,6 @@ async fn pending_put_tail_across_the_walk_no_longer_vetoes_the_cycle() {
|
||||
true,
|
||||
CycleHooks {
|
||||
resolved_scope_observer: None,
|
||||
post_walk_hook: None,
|
||||
post_walk_gate: None,
|
||||
peer_observations: None,
|
||||
},
|
||||
@@ -305,7 +300,6 @@ async fn guardrail_veto_still_supersedes_the_cycle_onto_the_observed_route() {
|
||||
true,
|
||||
CycleHooks {
|
||||
resolved_scope_observer: Some(observer),
|
||||
post_walk_hook: None,
|
||||
post_walk_gate: Some(gate),
|
||||
peer_observations: None,
|
||||
},
|
||||
@@ -413,7 +407,6 @@ async fn run_remote_certification_cycle(empty_ack: bool) {
|
||||
true,
|
||||
CycleHooks {
|
||||
resolved_scope_observer: None,
|
||||
post_walk_hook: None,
|
||||
post_walk_gate: None,
|
||||
peer_observations: Some(observations.clone()),
|
||||
},
|
||||
@@ -447,11 +440,9 @@ async fn run_remote_certification_cycle(empty_ack: bool) {
|
||||
let writer_store = Arc::clone(&store);
|
||||
let writer_peers = Arc::clone(&peers);
|
||||
let hot_incarnation = incarnations["hot-bucket"];
|
||||
let (walk_finished, walked) = tokio::sync::oneshot::channel();
|
||||
let writer = tokio::spawn(async move {
|
||||
// Exercise the certification window after the walk has produced its candidate.
|
||||
walked.await.expect("real cycle finished walking");
|
||||
put_fixture_object(&writer_store, "hot-bucket", "before-certification").await;
|
||||
let scope = resolved_scope.await.expect("real cycle resolved its scope");
|
||||
put_fixture_object(&writer_store, "hot-bucket", "during-walk").await;
|
||||
{
|
||||
let mut locked = writer_peers.lock().expect("peer fixture lock");
|
||||
let peer = locked.get_mut("peer-a:9000").expect("remote producer exists");
|
||||
@@ -467,6 +458,7 @@ async fn run_remote_certification_cycle(empty_ack: bool) {
|
||||
}
|
||||
wait_for_namespace_commit_tails(writer_store.as_ref()).await;
|
||||
release.send(()).expect("cycle awaits its actual post-walk proof");
|
||||
scope
|
||||
});
|
||||
let (result, published) = run_cycle(
|
||||
&store,
|
||||
@@ -475,14 +467,12 @@ async fn run_remote_certification_cycle(empty_ack: bool) {
|
||||
false,
|
||||
CycleHooks {
|
||||
resolved_scope_observer: Some(observer),
|
||||
post_walk_hook: Some(Box::new(move || walk_finished.send(()).expect("writer awaits the completed walk"))),
|
||||
post_walk_gate: Some(gate),
|
||||
peer_observations: Some(observations.clone()),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
writer.await.expect("writer completed");
|
||||
let scope = resolved_scope.await.expect("real cycle resolved its scope");
|
||||
let scope = writer.await.expect("writer completed");
|
||||
if empty_ack {
|
||||
assert!(scope.is_default(), "this case exercises the full-scope generation fallback");
|
||||
} else {
|
||||
@@ -546,7 +536,6 @@ async fn run_remote_certification_cycle(empty_ack: bool) {
|
||||
false,
|
||||
CycleHooks {
|
||||
resolved_scope_observer: Some(observer),
|
||||
post_walk_hook: None,
|
||||
post_walk_gate: None,
|
||||
peer_observations: Some(observations),
|
||||
},
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
# SSE Crate Instructions
|
||||
|
||||
Applies to `crates/sse/`.
|
||||
|
||||
## Boundary
|
||||
|
||||
- This crate sits between the S3 layer and the storage engine and depends on neither. Its `rustfs-*` dependencies are pinned by `scripts/check_architecture_migration_rules.sh` to `rustfs-config`, `rustfs-kms`, `rustfs-policy`, `rustfs-s3-types`, and `rustfs-utils`; see [crate boundaries](../../docs/architecture/crate-boundaries.md).
|
||||
- Anything the crate needs from the running server arrives through `SseHost` (`src/host.rs`), passed as the first argument of every entry point that consults the server. Do not add a global that stands in for the host: a caller must not be able to reach key selection without naming the server it speaks for.
|
||||
- Translation to and from storage-engine types (`ObjectEncryptionResolver`, `WriteEncryption`, `MultipartCompletionAuthorization`) and request types belongs in `rustfs/src/storage/sse.rs`, not here.
|
||||
- Report failures as `SseError`, classified with the S3 error code the caller answers with. A failure that did not originate from the request goes through `SseError::internal`, which keeps its detail out of the response.
|
||||
|
||||
## Layout
|
||||
|
||||
- `src/startup.rs` settles the state that is fixed for the lifetime of the process and reports it. Nothing that follows the KMS service state belongs there: the service follows configuration and can be started, restarted, or stopped from the admin API, so every choice that depends on it is made per request.
|
||||
- `src/core/` holds the entry points (`write.rs`, `read.rs`, `rewrap.rs`) and the request principal (`request.rs`). An entry point only orders the steps; the decisions live in the two layers below it.
|
||||
- `src/core/s3/` is what S3 defines: the SSE headers of a request and a response, the scheme a write or a stored object resolves to, the SSE-C checks, and the authorization of a KMS key.
|
||||
- `src/core/keying/` is how RustFS forms, seals, and records an object's key. `direct.rs` and `object.rs` are the two modes, and each owns both directions of its stored record: the code that writes a key's metadata sits next to the code that reads it back. `mod.rs` is the only place that says which mode a build writes; `stored.rs` holds the order in which a read recognizes the modes and picks the provider that unwraps the data key; `metadata.rs` records the scheme and lists every stored key name.
|
||||
- `src/kms/` holds the data-key providers: they wrap and unwrap a data key and decide nothing about schemes. The write and rewrap entry points, `core/keying/stored.rs`, and the startup check of the local master key call them; `core/s3/` never does.
|
||||
|
||||
Rules that keep the layers apart:
|
||||
|
||||
- `core/keying/` never imports from `core/s3/`. `core/s3/` reads stored metadata only through `core/keying/metadata.rs`. Anything else that needs both layers is joined in an entry point.
|
||||
- `#[cfg(feature = "rio-v2")]` appears only under `core/keying/` and `kms/`. An entry point or `core/s3/` that needs a build-dependent answer asks `core/keying/` for it.
|
||||
- A new stored format, including a MinIO-compatible one, is added under `core/keying/` (and `kms/` when it brings its own wrapping) without changes under `core/s3/`: a mode file with its record and read functions, one entry in the recognition order of `stored.rs`, and its key names in the lists of `metadata.rs`.
|
||||
- A read decides from what the object recorded. The scheme a request advertises and whether a KMS is running now are write policy and runtime state; neither says how an existing object was keyed.
|
||||
|
||||
## Security
|
||||
|
||||
- Never log plaintext customer keys, decrypted key material, data-key envelopes, nonces, or SSE request payloads, including through error strings and `Debug` output.
|
||||
- KMS audit tags may carry only the fields documented on `KmsRequestAuditState`.
|
||||
- The `test-util` feature exposes authorization overrides and DEK-provider injection. It is a dev-dependency feature only; never enable it from a normal dependency.
|
||||
|
||||
## Change Coordination
|
||||
|
||||
When changing key resolution, metadata, or error classification, verify compatibility with:
|
||||
|
||||
- `rustfs/src/storage/sse.rs` (the host implementation and the engine-boundary adapters)
|
||||
- `crates/kms/`
|
||||
- `crates/utils/src/http/object_encryption_keys.rs` (the stored-metadata key vocabulary)
|
||||
- `rustfs/src/kms_rekey.rs` and `rustfs/src/admin/handlers/kms*.rs`
|
||||
|
||||
## Testing
|
||||
|
||||
Run both builds; the `rio-v2` feature swaps the object-key scheme and compiles different code paths:
|
||||
|
||||
```bash
|
||||
cargo nextest run -p rustfs-sse --no-tests fail
|
||||
cargo nextest run -p rustfs-sse --features rio-v2 --no-tests fail
|
||||
```
|
||||
|
||||
The adapter tests live with the adapter:
|
||||
|
||||
```bash
|
||||
cargo nextest run -p rustfs --no-tests fail -E 'test(/^storage::sse::/)'
|
||||
```
|
||||
|
||||
A change that should leave client-visible behavior or the stored form untouched (a refactor, a move between layers) is checked against a real server: run `scripts/test/sse_blackbox/` on the binary before and after the change, compare the two runs, and cross-read their data directories. Its README has the commands.
|
||||
@@ -1,70 +0,0 @@
|
||||
# Copyright 2024 RustFS Team
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
[package]
|
||||
name = "rustfs-sse"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
version.workspace = true
|
||||
homepage.workspace = true
|
||||
description = "S3 server-side encryption (SSE-S3, SSE-KMS, SSE-C) key resolution and metadata for RustFS."
|
||||
keywords = ["sse", "encryption", "s3", "kms", "rustfs"]
|
||||
categories = ["cryptography"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# MinIO-compatible sealed object keys (DARE). Mirrors the `rio-v2` feature of
|
||||
# the server binary, which enables both together.
|
||||
rio-v2 = ["dep:chacha20poly1305", "dep:hmac", "dep:sha2"]
|
||||
# Test seams for dependents: per-principal authorization overrides, DEK
|
||||
# provider injection and metadata fixtures. Never enable in a release build.
|
||||
test-util = []
|
||||
|
||||
[dependencies]
|
||||
# The only RustFS crates this one may reach. It sits between the S3 layer and
|
||||
# the storage engine and must not depend on either: what it needs from the
|
||||
# running server arrives through `SseHost`.
|
||||
rustfs-config = { workspace = true }
|
||||
rustfs-kms = { workspace = true }
|
||||
rustfs-policy = { workspace = true }
|
||||
rustfs-s3-types = { workspace = true }
|
||||
rustfs-utils = { workspace = true, features = ["http", "path"] }
|
||||
|
||||
aes-gcm = { workspace = true, features = ["rand_core", "zeroize"] }
|
||||
async-trait = { workspace = true }
|
||||
base64-simd = { workspace = true }
|
||||
chacha20poly1305 = { workspace = true, optional = true }
|
||||
hmac = { workspace = true, optional = true }
|
||||
http = { workspace = true }
|
||||
md-5 = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { workspace = true, optional = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# The fake AWS KMS endpoint the backend-selection tests talk to.
|
||||
axum = { workspace = true }
|
||||
temp-env = { workspace = true, features = ["async_closure"] }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "sync", "time"] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
@@ -1,292 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Per-request summary of data-plane KMS use, attached to the request's audit entry.
|
||||
|
||||
use crate::core::request::SseKmsPrincipal;
|
||||
use crate::error::SseError;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use rustfs_kms::is_data_key_envelope;
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use rustfs_utils::http::object_encryption_keys::{INTERNAL_ENCRYPTION_KEY_HEADER, SSEType, normalize_managed_metadata};
|
||||
use serde_json::Value;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::sync::{Arc, LazyLock, Mutex, Weak};
|
||||
|
||||
/// Tag keys carrying the KMS summary on an S3 audit entry.
|
||||
///
|
||||
/// Audit consumers key off these strings, so they are a wire contract: append
|
||||
/// new keys rather than renaming existing ones.
|
||||
const KMS_AUDIT_TAG_SSE_TYPE: &str = "sseType";
|
||||
|
||||
const KMS_AUDIT_TAG_KEY_ID: &str = "kmsKeyId";
|
||||
|
||||
const KMS_AUDIT_TAG_KEY_VERSION: &str = "kmsKeyVersion";
|
||||
|
||||
const KMS_AUDIT_TAG_OUTCOME: &str = "kmsOutcome";
|
||||
|
||||
const KMS_AUDIT_TAG_ERROR_CLASS: &str = "kmsErrorClass";
|
||||
|
||||
/// Separator for the rare request that touched more than one key or scheme.
|
||||
const KMS_AUDIT_VALUE_SEPARATOR: &str = ",";
|
||||
|
||||
/// What the data path did with KMS while serving one S3 request.
|
||||
///
|
||||
/// This rides on the request's existing S3 audit entry instead of becoming its
|
||||
/// own event: the entry already carries the principal, request ID and API, so
|
||||
/// attaching the KMS outcome costs no extra event volume and needs no second
|
||||
/// correlation key.
|
||||
///
|
||||
/// # Redaction
|
||||
///
|
||||
/// Only the fields below may ever be recorded. The S3 audit entry fans out to
|
||||
/// every configured target, several of which sit outside the KMS trust
|
||||
/// boundary, so nothing derived from a data key — plaintext, ciphertext,
|
||||
/// envelope, nonce — nor any caller-supplied encryption-context value belongs
|
||||
/// here. Key identifiers and scheme names are configuration, not secrets.
|
||||
#[derive(Debug, Default)]
|
||||
struct KmsRequestAuditState {
|
||||
sse_types: BTreeSet<&'static str>,
|
||||
key_ids: BTreeSet<String>,
|
||||
key_versions: BTreeSet<u32>,
|
||||
/// Set by the first failure. A request that failed any KMS interaction is
|
||||
/// reported as failed even if others succeeded: a partially completed
|
||||
/// envelope operation is not a success for an audit reader.
|
||||
error_class: Option<&'static str>,
|
||||
recorded: bool,
|
||||
}
|
||||
|
||||
/// Shared accumulator for one request's KMS summary.
|
||||
///
|
||||
/// Written by the managed-SSE code paths through the request's principal, read
|
||||
/// once through [`KmsRequestAuditScope::audit_tags`] by whoever owns the
|
||||
/// request's audit entry.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct KmsRequestAudit(Mutex<KmsRequestAuditState>);
|
||||
|
||||
impl KmsRequestAudit {
|
||||
pub(crate) fn record(
|
||||
&self,
|
||||
sse_type: SSEType,
|
||||
key_id: Option<&str>,
|
||||
key_version: Option<u32>,
|
||||
error_class: Option<&'static str>,
|
||||
) {
|
||||
// A poisoned lock costs the audit entry its KMS tags; it must never cost
|
||||
// the request its result.
|
||||
let Ok(mut state) = self.0.lock() else {
|
||||
return;
|
||||
};
|
||||
|
||||
state.recorded = true;
|
||||
state.sse_types.insert(sse_type.audit_label());
|
||||
if let Some(key_id) = key_id.filter(|value| !value.is_empty()) {
|
||||
state.key_ids.insert(key_id.to_string());
|
||||
}
|
||||
if let Some(key_version) = key_version {
|
||||
state.key_versions.insert(key_version);
|
||||
}
|
||||
if state.error_class.is_none() {
|
||||
state.error_class = error_class;
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the summary as audit tags, or nothing when the request performed
|
||||
/// no KMS work at all (SSE-C and unencrypted objects never reach KMS).
|
||||
pub fn audit_tags(&self) -> Vec<(&'static str, Value)> {
|
||||
let Ok(state) = self.0.lock() else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !state.recorded {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut tags = Vec::with_capacity(5);
|
||||
tags.push((KMS_AUDIT_TAG_SSE_TYPE, join_audit_values(state.sse_types.iter().copied())));
|
||||
if !state.key_ids.is_empty() {
|
||||
tags.push((KMS_AUDIT_TAG_KEY_ID, join_audit_values(state.key_ids.iter().map(String::as_str))));
|
||||
}
|
||||
if !state.key_versions.is_empty() {
|
||||
tags.push((
|
||||
KMS_AUDIT_TAG_KEY_VERSION,
|
||||
join_audit_values(state.key_versions.iter().map(u32::to_string)),
|
||||
));
|
||||
}
|
||||
let outcome = if state.error_class.is_some() { "failure" } else { "success" };
|
||||
tags.push((KMS_AUDIT_TAG_OUTCOME, Value::String(outcome.to_string())));
|
||||
if let Some(error_class) = state.error_class {
|
||||
tags.push((KMS_AUDIT_TAG_ERROR_CLASS, Value::String(error_class.to_string())));
|
||||
}
|
||||
|
||||
tags
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a set of values as one tag value.
|
||||
///
|
||||
/// Always a string, including for the single-value case: a consumer that would
|
||||
/// have to branch on the JSON type of a tag is a consumer that will get it
|
||||
/// wrong for the request that happens to touch two keys.
|
||||
fn join_audit_values(values: impl Iterator<Item = impl AsRef<str>>) -> Value {
|
||||
let joined = values.map(|value| value.as_ref().to_string()).collect::<Vec<_>>();
|
||||
Value::String(joined.join(KMS_AUDIT_VALUE_SEPARATOR))
|
||||
}
|
||||
|
||||
/// Slots of the requests currently being audited, keyed by canonical request ID.
|
||||
///
|
||||
/// Only a weak reference is held: the owning [`KmsRequestAuditScope`] decides the
|
||||
/// lifetime, so a scope that is somehow not dropped cannot keep a slot alive.
|
||||
static KMS_REQUEST_AUDITS: LazyLock<Mutex<HashMap<String, Weak<KmsRequestAudit>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Registration of one request's KMS audit slot, dropped with the request's
|
||||
/// audit entry.
|
||||
pub struct KmsRequestAuditScope {
|
||||
request_id: String,
|
||||
audit: Arc<KmsRequestAudit>,
|
||||
}
|
||||
|
||||
impl KmsRequestAuditScope {
|
||||
/// Open a slot for `request_id`, so managed-SSE operations served under it can
|
||||
/// be summarised onto its audit entry.
|
||||
pub fn register(request_id: &str) -> Self {
|
||||
let audit = Arc::new(KmsRequestAudit::default());
|
||||
if let Ok(mut registry) = KMS_REQUEST_AUDITS.lock() {
|
||||
registry.insert(request_id.to_string(), Arc::downgrade(&audit));
|
||||
}
|
||||
|
||||
Self {
|
||||
request_id: request_id.to_string(),
|
||||
audit,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tags describing the KMS work recorded under this request.
|
||||
pub fn audit_tags(&self) -> Vec<(&'static str, Value)> {
|
||||
self.audit.audit_tags()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for KmsRequestAuditScope {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(mut registry) = KMS_REQUEST_AUDITS.lock() {
|
||||
registry.remove(&self.request_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the audit slot opened for `request_id`, if the request is being audited.
|
||||
pub(crate) fn kms_request_audit(request_id: &str) -> Option<Arc<KmsRequestAudit>> {
|
||||
KMS_REQUEST_AUDITS.lock().ok()?.get(request_id)?.upgrade()
|
||||
}
|
||||
|
||||
/// Failure classes for data-path failures that never reached a KMS backend.
|
||||
///
|
||||
/// Backend failures carry the classification defined by the KMS audit contract;
|
||||
/// everything else is classified at the S3 boundary it surfaced through.
|
||||
pub(crate) fn kms_data_plane_error_class(error: &SseError) -> &'static str {
|
||||
if let Some(failure) = error
|
||||
.source
|
||||
.as_ref()
|
||||
.and_then(|source| source.downcast_ref::<KmsDataPlaneFailure>())
|
||||
{
|
||||
return failure.class;
|
||||
}
|
||||
|
||||
match error.code {
|
||||
S3ErrorCode::AccessDenied => "access_denied",
|
||||
S3ErrorCode::InvalidArgument | S3ErrorCode::InvalidRequest => "invalid_argument",
|
||||
_ => "sse_internal",
|
||||
}
|
||||
}
|
||||
|
||||
/// Carries a KMS failure class across the conversion to an S3-facing error.
|
||||
///
|
||||
/// The class is decided while the `KmsError` is still typed; re-deriving it from
|
||||
/// a rendered message downstream would be guesswork.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct KmsDataPlaneFailure {
|
||||
pub(crate) class: &'static str,
|
||||
pub(crate) source: Option<Box<dyn std::error::Error + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for KmsDataPlaneFailure {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self.source {
|
||||
Some(source) => source.fmt(formatter),
|
||||
None => formatter.write_str(self.class),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for KmsDataPlaneFailure {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
self.source
|
||||
.as_ref()
|
||||
.map(|source| source.as_ref() as &(dyn std::error::Error + 'static))
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the outcome of one managed-SSE operation on the request's audit entry.
|
||||
///
|
||||
/// A `None` principal marks an internal caller — replication, lifecycle, heal —
|
||||
/// which has no S3 audit entry to attach to. `key_version` is a closure for
|
||||
/// exactly that caller: extracting the version means base64-decoding and
|
||||
/// parsing the stored envelope, work that must not run on the internal hot
|
||||
/// paths that discard it.
|
||||
pub(crate) fn record_managed_kms_outcome(
|
||||
principal: Option<&SseKmsPrincipal>,
|
||||
sse_type: SSEType,
|
||||
key_id: Option<&str>,
|
||||
key_version: impl FnOnce() -> Option<u32>,
|
||||
result: Result<(), &SseError>,
|
||||
) {
|
||||
let Some(audit) = principal.and_then(|principal| principal.request_audit.as_ref()) else {
|
||||
return;
|
||||
};
|
||||
|
||||
audit.record(sse_type, key_id, key_version(), result.err().map(kms_data_plane_error_class));
|
||||
}
|
||||
|
||||
/// Master-key version recorded in a managed-SSE data-key envelope, if the
|
||||
/// wrapping backend recorded one.
|
||||
///
|
||||
/// `None` is the honest answer for every other shape: Transit and AWS keep
|
||||
/// the version inside their own opaque ciphertext, Local records no version,
|
||||
/// and pre-versioning envelopes never carried the field. The single field is
|
||||
/// read through `serde_json::Value` rather than a full `DataKeyEnvelope`
|
||||
/// parse, so the audit path cannot double-count the envelope's unknown-field
|
||||
/// observability and touches nothing else in the envelope.
|
||||
pub(crate) fn envelope_master_key_version(envelope_bytes: &[u8]) -> Option<u32> {
|
||||
if !is_data_key_envelope(envelope_bytes) {
|
||||
return None;
|
||||
}
|
||||
u32::try_from(
|
||||
serde_json::from_slice::<Value>(envelope_bytes)
|
||||
.ok()?
|
||||
.get("master_key_version")?
|
||||
.as_u64()?,
|
||||
)
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Master-key version of the envelope stored on an object, for the audit
|
||||
/// summary of a read against that object.
|
||||
pub(crate) fn stored_envelope_master_key_version(metadata: &HashMap<String, String>) -> Option<u32> {
|
||||
// No context recoder: the recode only ever inserts the context key, which
|
||||
// this lookup never reads, so the normalized result is identical without it.
|
||||
let encoded = normalize_managed_metadata(metadata, None);
|
||||
let encoded = encoded.get(INTERNAL_ENCRYPTION_KEY_HEADER)?;
|
||||
let envelope = BASE64_STANDARD.decode_to_vec(encoded).ok()?;
|
||||
envelope_master_key_version(&envelope)
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The encryption context a data key is bound to.
|
||||
|
||||
use crate::error::SseError;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use rustfs_kms::types::ObjectEncryptionContext;
|
||||
use rustfs_utils::http::object_encryption_keys::MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER;
|
||||
use rustfs_utils::path::path_join_buf;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(crate) fn canonical_kms_bucket_path(bucket: &str, key: &str) -> String {
|
||||
path_join_buf(&[bucket, key])
|
||||
}
|
||||
|
||||
pub(crate) fn build_kms_request_context(
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
provided_context: Option<&HashMap<String, String>>,
|
||||
) -> HashMap<String, String> {
|
||||
let mut context = provided_context.cloned().unwrap_or_default();
|
||||
context
|
||||
.entry(bucket.to_string())
|
||||
.or_insert_with(|| canonical_kms_bucket_path(bucket, key));
|
||||
context
|
||||
}
|
||||
|
||||
pub(crate) fn build_object_encryption_context(
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
provided_context: Option<&HashMap<String, String>>,
|
||||
) -> ObjectEncryptionContext {
|
||||
let mut context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string());
|
||||
for (ctx_key, ctx_value) in build_kms_request_context(bucket, key, provided_context) {
|
||||
context = context.with_encryption_context(ctx_key, ctx_value);
|
||||
}
|
||||
context
|
||||
}
|
||||
|
||||
pub(crate) fn encode_minio_kms_context(context: &HashMap<String, String>) -> Result<String, SseError> {
|
||||
let encoded = serde_json::to_vec(context).map_err(|e| SseError::internal(format!("Failed to serialize KMS context: {e}")))?;
|
||||
Ok(BASE64_STANDARD.encode_to_string(encoded))
|
||||
}
|
||||
|
||||
pub(crate) fn decode_minio_kms_context(metadata: &HashMap<String, String>) -> Result<Option<HashMap<String, String>>, SseError> {
|
||||
let Some(encoded) = metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let decoded = BASE64_STANDARD
|
||||
.decode_to_vec(encoded)
|
||||
.map_err(|e| SseError::internal(format!("Failed to decode MinIO KMS context: {e}")))?;
|
||||
serde_json::from_slice(&decoded)
|
||||
.map(Some)
|
||||
.map_err(|e| SseError::internal(format!("Failed to parse MinIO KMS context: {e}")))
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! 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::keying::{StoredDataKey, StoredKeyMode};
|
||||
use crate::error::SseError;
|
||||
use crate::host::SseHost;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use md5::{Digest as Md5Digest, Md5};
|
||||
#[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_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// SSE-C: record the base nonce the object is encrypted under.
|
||||
///
|
||||
/// The nonce is random, so decrypt reads it back instead of recomputing a
|
||||
/// deterministic value. It is written under both the RustFS and the MinIO key per
|
||||
/// repo convention. This covers a single PUT and a multipart session alike:
|
||||
/// CreateMultipartUpload builds the session metadata through the same call.
|
||||
pub(crate) fn record_customer_key_nonce(metadata: &mut HashMap<String, String>, base_nonce: [u8; 12]) {
|
||||
metadata.insert(INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string(base_nonce));
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(),
|
||||
BASE64_STANDARD.encode_to_string(base_nonce),
|
||||
);
|
||||
}
|
||||
|
||||
/// Managed SSE: record the wrapped data key, the nonce issued with it, and the cipher.
|
||||
pub(crate) fn record_wrapped_data_key(
|
||||
metadata: &mut HashMap<String, String>,
|
||||
wrapped_data_key: &[u8],
|
||||
base_nonce: [u8; 12],
|
||||
algorithm: &str,
|
||||
) {
|
||||
metadata.insert(
|
||||
INTERNAL_ENCRYPTION_KEY_HEADER.to_string(),
|
||||
BASE64_STANDARD.encode_to_string(wrapped_data_key),
|
||||
);
|
||||
metadata.insert(INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string(base_nonce));
|
||||
metadata.insert(INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), algorithm.to_string());
|
||||
}
|
||||
|
||||
/// Managed SSE: read back what [`record_wrapped_data_key`] stored.
|
||||
///
|
||||
/// `normalized_metadata` is the object's metadata with the managed keys normalized.
|
||||
pub(crate) async fn read_wrapped_data_key(
|
||||
host: &dyn SseHost,
|
||||
normalized_metadata: &HashMap<String, String>,
|
||||
) -> Result<StoredDataKey, SseError> {
|
||||
let (wrapped, iv, algorithm) = if let Some(service) = host.encryption_service().await {
|
||||
// Production mode: use service for metadata parsing
|
||||
let parsed = service
|
||||
.headers_to_metadata(normalized_metadata)
|
||||
.map_err(|e| SseError::internal(format!("Failed to parse encryption metadata: {e}")))?;
|
||||
|
||||
(parsed.encrypted_data_key, parsed.iv, parsed.algorithm)
|
||||
} else {
|
||||
// Test mode: parse metadata manually
|
||||
let encrypted_key_b64 = normalized_metadata
|
||||
.get(INTERNAL_ENCRYPTION_KEY_HEADER)
|
||||
.ok_or_else(|| SseError::internal("Missing encrypted key in metadata"))?;
|
||||
let encrypted_data_key = BASE64_STANDARD
|
||||
.decode_to_vec(encrypted_key_b64)
|
||||
.map_err(|e| SseError::internal(format!("Failed to decode encrypted key: {e}")))?;
|
||||
|
||||
let iv_b64 = normalized_metadata
|
||||
.get(INTERNAL_ENCRYPTION_IV_HEADER)
|
||||
.ok_or_else(|| SseError::internal("Missing IV in metadata"))?;
|
||||
let iv = BASE64_STANDARD
|
||||
.decode_to_vec(iv_b64)
|
||||
.map_err(|e| SseError::internal(format!("Failed to decode IV: {e}")))?;
|
||||
|
||||
let algorithm = normalized_metadata
|
||||
.get(INTERNAL_ENCRYPTION_ALGORITHM_HEADER)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "AES256".to_string());
|
||||
|
||||
(encrypted_data_key, iv, algorithm)
|
||||
};
|
||||
|
||||
let base_nonce = <[u8; 12]>::try_from(iv.as_slice())
|
||||
.map_err(|_| SseError::internal("Invalid encryption nonce length; expected 12 bytes"))?;
|
||||
|
||||
Ok(StoredDataKey {
|
||||
wrapped,
|
||||
algorithm,
|
||||
mode: StoredKeyMode::Direct { base_nonce },
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve the SSE-C Direct base nonce for decryption.
|
||||
///
|
||||
/// New objects persist a random nonce at encryption time (see
|
||||
/// [`record_customer_key_nonce`]) under `INTERNAL_ENCRYPTION_IV_HEADER` (preferred) or,
|
||||
/// for MinIO interop, `MINIO_INTERNAL_ENCRYPTION_IV_HEADER`. Legacy objects written before
|
||||
/// random nonces were persisted carry no stored IV; for those we fall back to the
|
||||
/// deterministic `generate_ssec_nonce(bucket, key)` value they were originally encrypted
|
||||
/// with, so previously stored objects still decrypt correctly.
|
||||
pub(crate) fn read_stored_ssec_nonce(metadata: &HashMap<String, String>, bucket: &str, key: &str) -> [u8; 12] {
|
||||
metadata
|
||||
.get(INTERNAL_ENCRYPTION_IV_HEADER)
|
||||
.or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER))
|
||||
.and_then(|encoded| BASE64_STANDARD.decode_to_vec(encoded).ok())
|
||||
.and_then(|bytes| <[u8; 12]>::try_from(bytes.as_slice()).ok())
|
||||
.unwrap_or_else(|| generate_ssec_nonce(bucket, key))
|
||||
}
|
||||
|
||||
/// Generate deterministic nonce for SSE-C encryption
|
||||
///
|
||||
/// The nonce is derived from the bucket and key to ensure:
|
||||
/// 1. Same object always gets the same nonce (required for SSE-C)
|
||||
/// 2. Different objects get different nonces
|
||||
pub(crate) fn generate_ssec_nonce(bucket: &str, key: &str) -> [u8; 12] {
|
||||
let nonce_source = format!("{bucket}-{key}");
|
||||
let nonce_hash: [u8; 16] = Md5::digest(nonce_source.as_bytes()).into();
|
||||
let mut nonce = [0u8; 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 [`record_customer_key_nonce`]) 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<NewObjectKey, SseError> {
|
||||
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
|
||||
/// [`record_customer_key_nonce`]). 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<NewObjectKey, SseError> {
|
||||
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<NewObjectKey, SseError> {
|
||||
Ok(NewObjectKey {
|
||||
key_bytes: data_key.plaintext_key,
|
||||
base_nonce: data_key.nonce,
|
||||
key_kind: EncryptionKeyKind::Direct,
|
||||
sealed_key: None,
|
||||
})
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The key material an encrypted write or read runs on.
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
use crate::core::keying::object::{SEALED_KEY_IV_SIZE, SEALED_KEY_SIZE};
|
||||
use rustfs_utils::http::object_encryption_keys::SSEType;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Encryption material returned by [`sse_encryption`] / [`sse_prepare_encryption`].
|
||||
pub struct EncryptionMaterial {
|
||||
#[allow(unused)]
|
||||
pub sse_type: SSEType,
|
||||
pub server_side_encryption: String,
|
||||
pub kms_key_id: Option<String>,
|
||||
|
||||
#[allow(unused)]
|
||||
pub algorithm: String,
|
||||
|
||||
/// Encryption key bytes
|
||||
pub key_bytes: [u8; 32],
|
||||
/// Base nonce/IV used by rio to derive block/part nonces.
|
||||
pub base_nonce: [u8; 12],
|
||||
/// Encrypted DEK for managed SSE. Absent for SSE-C.
|
||||
pub encrypted_data_key: Option<Vec<u8>>,
|
||||
/// SSE-C key MD5 if customer-managed encryption is in use.
|
||||
pub customer_key_md5: Option<String>,
|
||||
/// Original plaintext size when it should be persisted alongside metadata.
|
||||
pub original_size: Option<i64>,
|
||||
/// Indicates whether `key_bytes` is a direct stream key or a MinIO-style object key.
|
||||
pub key_kind: EncryptionKeyKind,
|
||||
/// Original client-provided SSE-KMS context, stored in MinIO-compatible metadata.
|
||||
pub managed_kms_context: Option<HashMap<String, String>>,
|
||||
/// MinIO-compatible sealed object-key metadata for managed SSE object-key mode.
|
||||
#[cfg_attr(not(feature = "rio-v2"), allow(dead_code))]
|
||||
pub managed_sealed_key: Option<ManagedSealedKey>,
|
||||
}
|
||||
|
||||
/// Decryption material returned by [`sse_decryption`].
|
||||
pub struct DecryptionMaterial {
|
||||
#[allow(unused)]
|
||||
pub sse_type: SSEType,
|
||||
pub server_side_encryption: String,
|
||||
pub kms_key_id: Option<String>,
|
||||
#[allow(unused)]
|
||||
pub algorithm: String,
|
||||
pub customer_key_md5: Option<String>, // if use SSE-C, check key md5
|
||||
|
||||
/// Decryption key bytes
|
||||
pub key_bytes: [u8; 32],
|
||||
/// Base nonce/IV used by rio to derive block/part nonces.
|
||||
pub base_nonce: [u8; 12],
|
||||
/// Indicates whether `key_bytes` is a direct stream key or a MinIO-style object key.
|
||||
pub key_kind: EncryptionKeyKind,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EncryptionMaterial {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EncryptionMaterial")
|
||||
.field("sse_type", &self.sse_type)
|
||||
.field("server_side_encryption", &self.server_side_encryption)
|
||||
.field("original_size", &self.original_size)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DecryptionMaterial {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DecryptionMaterial")
|
||||
.field("sse_type", &self.sse_type)
|
||||
.field("server_side_encryption", &self.server_side_encryption)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EncryptionKeyKind {
|
||||
Direct,
|
||||
Object,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ManagedSealedKey {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
pub iv: [u8; SEALED_KEY_IV_SIZE],
|
||||
#[cfg(feature = "rio-v2")]
|
||||
pub sealed_key: [u8; SEALED_KEY_SIZE],
|
||||
}
|
||||
|
||||
impl EncryptionMaterial {
|
||||
/// The KMS key id a write response may advertise.
|
||||
///
|
||||
/// `kms_key_id` is always set for managed SSE because SSE-S3 also wraps
|
||||
/// its data key under the service default key, but that key is an
|
||||
/// internal detail of an `AES256` object: only an `aws:kms` object names
|
||||
/// a key the caller can act on, and `x-amz-server-side-encryption-aws-kms-key-id`
|
||||
/// is defined only for that scheme.
|
||||
pub fn response_kms_key_id(&self) -> Option<String> {
|
||||
matches!(self.sse_type, SSEType::SseKms)
|
||||
.then(|| self.kms_key_id.clone())
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Encryption metadata as it is stored with the object.
|
||||
|
||||
use crate::core::keying::context::encode_minio_kms_context;
|
||||
use crate::core::keying::direct::{record_customer_key_nonce, record_wrapped_data_key};
|
||||
use crate::core::keying::material::{EncryptionKeyKind, EncryptionMaterial};
|
||||
#[cfg(feature = "rio-v2")]
|
||||
use crate::core::keying::object::{record_data_key_in_minio_slots, record_sealed_customer_key};
|
||||
use crate::error::SseError;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use rustfs_utils::http::object_encryption_keys::{
|
||||
INTERNAL_ENCRYPTION_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_CONTEXT_HEADER, INTERNAL_ENCRYPTION_IV_HEADER,
|
||||
INTERNAL_ENCRYPTION_KEY_HEADER, INTERNAL_ENCRYPTION_KEY_ID_HEADER, INTERNAL_ENCRYPTION_ORIGINAL_SIZE_HEADER,
|
||||
INTERNAL_ENCRYPTION_TAG_HEADER, MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER, MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER, MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER, SSEC_ORIGINAL_SIZE_HEADER, SSEType,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Two spellings of one encryption metadata key carry different values.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ConflictingEncryptionMetadata {
|
||||
/// The canonical key whose case-variants disagree.
|
||||
pub key: &'static str,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ConflictingEncryptionMetadata {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(formatter, "conflicting object encryption metadata for {}", self.key)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ConflictingEncryptionMetadata {}
|
||||
|
||||
/// Fold case-variant spellings of the encryption metadata keys onto their canonical names.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When two spellings of the same key hold different values: picking either
|
||||
/// would decrypt with material the object may not have been written under.
|
||||
pub fn normalize_encryption_metadata_case(
|
||||
metadata: &HashMap<String, String>,
|
||||
) -> Result<Cow<'_, HashMap<String, String>>, ConflictingEncryptionMetadata> {
|
||||
const CANONICAL_KEYS: &[&str] = &[
|
||||
"x-amz-server-side-encryption",
|
||||
"x-amz-server-side-encryption-aws-kms-key-id",
|
||||
"x-amz-server-side-encryption-customer-algorithm",
|
||||
"x-amz-server-side-encryption-customer-key-md5",
|
||||
SSEC_ORIGINAL_SIZE_HEADER,
|
||||
INTERNAL_ENCRYPTION_KEY_ID_HEADER,
|
||||
INTERNAL_ENCRYPTION_KEY_HEADER,
|
||||
INTERNAL_ENCRYPTION_ALGORITHM_HEADER,
|
||||
INTERNAL_ENCRYPTION_IV_HEADER,
|
||||
INTERNAL_ENCRYPTION_CONTEXT_HEADER,
|
||||
INTERNAL_ENCRYPTION_TAG_HEADER,
|
||||
INTERNAL_ENCRYPTION_ORIGINAL_SIZE_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER,
|
||||
];
|
||||
|
||||
let needs_normalization = metadata.keys().any(|key| {
|
||||
CANONICAL_KEYS
|
||||
.iter()
|
||||
.any(|canonical| key != canonical && key.eq_ignore_ascii_case(canonical))
|
||||
});
|
||||
if !needs_normalization {
|
||||
return Ok(Cow::Borrowed(metadata));
|
||||
}
|
||||
|
||||
let mut normalized = metadata.clone();
|
||||
for canonical in CANONICAL_KEYS {
|
||||
let mut matching_values = metadata
|
||||
.iter()
|
||||
.filter_map(|(key, value)| key.eq_ignore_ascii_case(canonical).then_some(value));
|
||||
let Some(value) = matching_values.next() else {
|
||||
continue;
|
||||
};
|
||||
if matching_values.any(|candidate| candidate != value) {
|
||||
return Err(ConflictingEncryptionMetadata { key: canonical });
|
||||
}
|
||||
if !normalized.contains_key(*canonical) {
|
||||
normalized.insert((*canonical).to_string(), value.clone());
|
||||
}
|
||||
}
|
||||
Ok(Cow::Owned(normalized))
|
||||
}
|
||||
|
||||
/// Turn the material of an encrypted write into the metadata stored with the object.
|
||||
///
|
||||
/// The scheme is recorded here. How the key itself is recorded belongs to the mode
|
||||
/// that formed it, in `direct.rs` and `object.rs`, next to the code that reads it back.
|
||||
pub fn encryption_material_to_metadata(material: &EncryptionMaterial) -> Result<HashMap<String, String>, SseError> {
|
||||
let mut metadata = HashMap::new();
|
||||
|
||||
match material.sse_type {
|
||||
SSEType::SseC => {
|
||||
record_ssec_scheme(&mut metadata, material);
|
||||
|
||||
// A `rio-v2` build seals an object key instead, so a Direct key there is a
|
||||
// multipart session created without its customer key.
|
||||
if material.key_kind == EncryptionKeyKind::Direct {
|
||||
record_customer_key_nonce(&mut metadata, material.base_nonce);
|
||||
}
|
||||
#[cfg(feature = "rio-v2")]
|
||||
if let Some(sealed) = &material.managed_sealed_key {
|
||||
record_sealed_customer_key(&mut metadata, sealed);
|
||||
}
|
||||
}
|
||||
SSEType::SseS3 | SSEType::SseKms => {
|
||||
let wrapped_data_key = material
|
||||
.encrypted_data_key
|
||||
.as_deref()
|
||||
.ok_or_else(|| SseError::internal("managed SSE materials must carry an encrypted data key"))?;
|
||||
record_managed_scheme(&mut metadata, material);
|
||||
|
||||
if material.key_kind == EncryptionKeyKind::Direct {
|
||||
record_wrapped_data_key(&mut metadata, wrapped_data_key, material.base_nonce, material.algorithm.as_str());
|
||||
}
|
||||
#[cfg(feature = "rio-v2")]
|
||||
record_data_key_in_minio_slots(&mut metadata, material, wrapped_data_key);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// SSE-C: the scheme, the fingerprint of the customer key, and the plaintext size.
|
||||
fn record_ssec_scheme(metadata: &mut HashMap<String, String>, material: &EncryptionMaterial) {
|
||||
metadata.insert(
|
||||
"x-amz-server-side-encryption".to_string(),
|
||||
material.server_side_encryption.as_str().to_string(),
|
||||
);
|
||||
metadata.insert(
|
||||
"x-amz-server-side-encryption-customer-algorithm".to_string(),
|
||||
material.algorithm.as_str().to_string(),
|
||||
);
|
||||
if let Some(customer_key_md5) = &material.customer_key_md5 {
|
||||
metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), customer_key_md5.to_string());
|
||||
}
|
||||
if let Some(original_size) = material.original_size {
|
||||
metadata.insert(SSEC_ORIGINAL_SIZE_HEADER.to_string(), original_size.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Managed SSE: the scheme, the key the data key is wrapped under, the plaintext
|
||||
/// size, and the encryption context of the request.
|
||||
fn record_managed_scheme(metadata: &mut HashMap<String, String>, material: &EncryptionMaterial) {
|
||||
metadata.insert(
|
||||
"x-amz-server-side-encryption".to_string(),
|
||||
material.server_side_encryption.as_str().to_string(),
|
||||
);
|
||||
|
||||
let internal_key_id = material.kms_key_id.clone().unwrap_or_else(|| "default".to_string());
|
||||
metadata.insert(INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), internal_key_id.clone());
|
||||
|
||||
if matches!(material.sse_type, SSEType::SseKms) {
|
||||
metadata.insert("x-amz-server-side-encryption-aws-kms-key-id".to_string(), internal_key_id);
|
||||
}
|
||||
|
||||
if let Some(original_size) = material.original_size {
|
||||
metadata.insert(INTERNAL_ENCRYPTION_ORIGINAL_SIZE_HEADER.to_string(), original_size.to_string());
|
||||
}
|
||||
|
||||
if let Some(kms_context) = &material.managed_kms_context
|
||||
&& !kms_context.is_empty()
|
||||
{
|
||||
if let Ok(serialized) = serde_json::to_string(kms_context) {
|
||||
metadata.insert(INTERNAL_ENCRYPTION_CONTEXT_HEADER.to_string(), serialized);
|
||||
}
|
||||
if matches!(material.sse_type, SSEType::SseKms)
|
||||
&& let Ok(encoded) = encode_minio_kms_context(kms_context)
|
||||
{
|
||||
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), encoded);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip source encryption metadata before constructing metadata for a copy destination.
|
||||
///
|
||||
/// Encryption metadata describes the physical source representation and must never be
|
||||
/// inherited by a plaintext destination or by a destination using a different key.
|
||||
pub fn strip_managed_encryption_metadata(metadata: &mut HashMap<String, String>) {
|
||||
const KEYS: [&str; 21] = [
|
||||
"x-amz-server-side-encryption",
|
||||
"x-amz-server-side-encryption-aws-kms-key-id",
|
||||
"x-amz-server-side-encryption-customer-algorithm",
|
||||
"x-amz-server-side-encryption-customer-key-md5",
|
||||
SSEC_ORIGINAL_SIZE_HEADER,
|
||||
INTERNAL_ENCRYPTION_KEY_ID_HEADER,
|
||||
INTERNAL_ENCRYPTION_ALGORITHM_HEADER,
|
||||
INTERNAL_ENCRYPTION_IV_HEADER,
|
||||
INTERNAL_ENCRYPTION_TAG_HEADER,
|
||||
INTERNAL_ENCRYPTION_KEY_HEADER,
|
||||
INTERNAL_ENCRYPTION_CONTEXT_HEADER,
|
||||
INTERNAL_ENCRYPTION_ORIGINAL_SIZE_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER,
|
||||
];
|
||||
|
||||
for key in KEYS.iter() {
|
||||
metadata.remove(*key);
|
||||
}
|
||||
rustfs_utils::http::metadata_compat::remove_str(metadata, rustfs_utils::http::SUFFIX_OPAQUE_ENCRYPTED_ETAG);
|
||||
}
|
||||
|
||||
pub fn mark_encrypted_multipart_metadata(metadata: &mut HashMap<String, String>) {
|
||||
metadata.insert(MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER.to_string(), String::new());
|
||||
}
|
||||
|
||||
/// True when the stored metadata marks the object as SSE-C protected.
|
||||
///
|
||||
/// RustFS persists the public `x-amz-server-side-encryption-customer-algorithm`
|
||||
/// key on SSE-C writes. MinIO persists only its internal sealed-key slot and
|
||||
/// synthesizes the public header onto responses (backlog#1638), so the slot is
|
||||
/// the only durable evidence on a MinIO-written object. That shape is readable
|
||||
/// solely through the rio-v2 sealed-object-key path, so it participates in
|
||||
/// detection only in builds that can actually read it — default builds keep
|
||||
/// the resolver's fail-closed diagnosis instead of demanding customer keys
|
||||
/// they could not use.
|
||||
pub fn stored_ssec_metadata(metadata: &HashMap<String, String>) -> bool {
|
||||
metadata.contains_key("x-amz-server-side-encryption-customer-algorithm") || minio_sealed_ssec_metadata(metadata)
|
||||
}
|
||||
|
||||
/// True when the object carries MinIO's SSE-C sealed-key slot — the shape that
|
||||
/// stores no customer-key MD5 and proves the key through the AEAD unseal
|
||||
/// instead.
|
||||
pub(crate) fn minio_sealed_ssec_metadata(metadata: &HashMap<String, String>) -> bool {
|
||||
cfg!(feature = "rio-v2") && metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)
|
||||
}
|
||||
|
||||
/// Recodes a stored MinIO KMS context value (base64-wrapped JSON) into the
|
||||
/// plain-JSON form RustFS stores under [`INTERNAL_ENCRYPTION_CONTEXT_HEADER`].
|
||||
///
|
||||
/// Injected into the shared [`normalize_managed_metadata`] because the shared
|
||||
/// crate carries no JSON codec; any decode failure returns `None`, which skips
|
||||
/// the context mapping exactly like the historical inline `if let Ok` chain.
|
||||
pub(crate) fn recode_minio_kms_context(value: &str) -> Option<String> {
|
||||
let decoded = BASE64_STANDARD.decode_to_vec(value).ok()?;
|
||||
let context = serde_json::from_slice::<HashMap<String, String>>(&decoded).ok()?;
|
||||
serde_json::to_string(&context).ok()
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The internal keying modes: how an object's key is formed and how it is stored.
|
||||
|
||||
pub(crate) mod context;
|
||||
pub(crate) mod direct;
|
||||
pub(crate) mod material;
|
||||
pub(crate) mod metadata;
|
||||
#[cfg(feature = "rio-v2")]
|
||||
pub(crate) mod object;
|
||||
pub(crate) mod stored;
|
||||
|
||||
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<ManagedSealedKey>,
|
||||
}
|
||||
|
||||
/// A managed-SSE data key as a stored object recorded it, still wrapped.
|
||||
pub(crate) struct StoredDataKey {
|
||||
/// The data key, wrapped by the provider that issued it.
|
||||
pub(crate) wrapped: Vec<u8>,
|
||||
/// The cipher the object recorded.
|
||||
pub(crate) algorithm: String,
|
||||
/// What the data key is to the object once it is unwrapped.
|
||||
pub(crate) mode: StoredKeyMode,
|
||||
}
|
||||
|
||||
/// The mode a stored key was recorded in.
|
||||
pub(crate) enum StoredKeyMode {
|
||||
/// The data key is the object's key, under the nonce stored beside it.
|
||||
Direct { base_nonce: [u8; 12] },
|
||||
/// The data key unseals the object's key.
|
||||
#[cfg(feature = "rio-v2")]
|
||||
Object { sealed_key: ManagedSealedKey },
|
||||
}
|
||||
|
||||
// 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,
|
||||
};
|
||||
@@ -1,436 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Object keying: a derived object key, sealed in the MinIO-compatible format.
|
||||
|
||||
use crate::core::keying::material::{EncryptionKeyKind, EncryptionMaterial, ManagedSealedKey};
|
||||
use crate::core::keying::{NewObjectKey, StoredDataKey, StoredKeyMode};
|
||||
use crate::error::SseError;
|
||||
use aes_gcm::aead::{Aead, KeyInit, Payload};
|
||||
use aes_gcm::{Aes256Gcm, Nonce};
|
||||
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_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER, MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER, SSEType,
|
||||
};
|
||||
use sha2::Sha256;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(crate) const MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM: &str = "DAREv2-HMAC-SHA256";
|
||||
|
||||
const DARE_VERSION_20: u8 = 0x20;
|
||||
|
||||
pub(crate) const DARE_CIPHER_AES_256_GCM: u8 = 0x00;
|
||||
|
||||
pub(crate) const DARE_CIPHER_CHACHA20_POLY1305: u8 = 0x01;
|
||||
|
||||
const DARE_HEADER_SIZE: usize = 16;
|
||||
|
||||
const DARE_TAG_SIZE: usize = 16;
|
||||
|
||||
pub(crate) const SEALED_KEY_IV_SIZE: usize = 32;
|
||||
|
||||
pub(crate) const SEALED_KEY_SIZE: usize = DARE_HEADER_SIZE + 32 + DARE_TAG_SIZE;
|
||||
|
||||
const OBJECT_KEY_DERIVATION_CONTEXT: &[u8] = b"object-encryption-key generation";
|
||||
|
||||
pub(crate) type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
fn managed_sse_domain(sse_type: SSEType) -> &'static str {
|
||||
match sse_type {
|
||||
SSEType::SseS3 => "SSE-S3",
|
||||
SSEType::SseKms => "SSE-KMS",
|
||||
SSEType::SseC => "SSE-C",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_supported_sealed_object_key_cipher(cipher: u8) -> bool {
|
||||
matches!(cipher, DARE_CIPHER_AES_256_GCM | DARE_CIPHER_CHACHA20_POLY1305)
|
||||
}
|
||||
|
||||
fn decrypt_sealed_object_key_payload(sealing_key: [u8; 32], header: &[u8], sealed_key: &[u8]) -> Result<Vec<u8>, SseError> {
|
||||
let nonce = &header[4..16];
|
||||
let ciphertext = &sealed_key[DARE_HEADER_SIZE..];
|
||||
let aad = &header[..4];
|
||||
match header[1] {
|
||||
DARE_CIPHER_AES_256_GCM => {
|
||||
let cipher = Aes256Gcm::new_from_slice(&sealing_key)
|
||||
.map_err(|err| SseError::internal(format!("Invalid AES-GCM sealing key: {err}")))?;
|
||||
let nonce = Nonce::try_from(nonce).map_err(|_| SseError::internal("Invalid sealed object-key package nonce"))?;
|
||||
cipher.decrypt(&nonce, Payload { msg: ciphertext, aad })
|
||||
}
|
||||
DARE_CIPHER_CHACHA20_POLY1305 => {
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(&sealing_key)
|
||||
.map_err(|err| SseError::internal(format!("Invalid ChaCha20-Poly1305 sealing key: {err}")))?;
|
||||
let nonce = chacha20poly1305::Nonce::try_from(nonce)
|
||||
.map_err(|_| SseError::internal("Invalid sealed object-key package nonce"))?;
|
||||
cipher.decrypt(&nonce, Payload { msg: ciphertext, aad })
|
||||
}
|
||||
_ => return Err(SseError::internal("Unsupported sealed object-key DARE header")),
|
||||
}
|
||||
.map_err(|err| SseError::internal(format!("Failed to unseal object key: {err}")))
|
||||
}
|
||||
|
||||
fn canonical_sse_path(bucket: &str, object: &str) -> String {
|
||||
let bucket = bucket.trim_matches('/');
|
||||
let object = object.trim_matches('/');
|
||||
if object.is_empty() {
|
||||
bucket.to_string()
|
||||
} else if bucket.is_empty() {
|
||||
object.to_string()
|
||||
} else {
|
||||
format!("{bucket}/{object}")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn derive_object_key(external_key: [u8; 32]) -> Result<[u8; 32], SseError> {
|
||||
let mut random = [0u8; 32];
|
||||
rand::rng().fill(&mut random);
|
||||
|
||||
let mut mac = HmacSha256::new_from_slice(&external_key)
|
||||
.map_err(|err| SseError::internal(format!("Invalid HMAC key for object-key derivation: {err}")))?;
|
||||
mac.update(OBJECT_KEY_DERIVATION_CONTEXT);
|
||||
mac.update(&random);
|
||||
|
||||
let mut object_key = [0u8; 32];
|
||||
object_key.copy_from_slice(mac.finalize().into_bytes().as_slice());
|
||||
Ok(object_key)
|
||||
}
|
||||
|
||||
fn derive_sealing_key(
|
||||
external_key: [u8; 32],
|
||||
iv: [u8; SEALED_KEY_IV_SIZE],
|
||||
domain: &str,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
let mut mac = HmacSha256::new_from_slice(&external_key)
|
||||
.map_err(|err| SseError::internal(format!("Invalid HMAC key for sealing-key derivation: {err}")))?;
|
||||
mac.update(&iv);
|
||||
mac.update(domain.as_bytes());
|
||||
mac.update(MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.as_bytes());
|
||||
mac.update(canonical_sse_path(bucket, object).as_bytes());
|
||||
|
||||
let mut sealing_key = [0u8; 32];
|
||||
sealing_key.copy_from_slice(mac.finalize().into_bytes().as_slice());
|
||||
Ok(sealing_key)
|
||||
}
|
||||
|
||||
pub(crate) fn seal_object_key(
|
||||
object_key: [u8; 32],
|
||||
external_key: [u8; 32],
|
||||
sse_type: SSEType,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
) -> Result<ManagedSealedKey, SseError> {
|
||||
let mut iv = [0u8; SEALED_KEY_IV_SIZE];
|
||||
rand::rng().fill(&mut iv);
|
||||
let sealing_key = derive_sealing_key(external_key, iv, managed_sse_domain(sse_type), bucket, object)?;
|
||||
|
||||
let mut header = [0u8; DARE_HEADER_SIZE];
|
||||
header[0] = DARE_VERSION_20;
|
||||
header[1] = DARE_CIPHER_AES_256_GCM;
|
||||
header[2..4].copy_from_slice(&(31u16).to_le_bytes());
|
||||
let mut stream_nonce = [0u8; 12];
|
||||
rand::rng().fill(&mut stream_nonce);
|
||||
stream_nonce[0] |= 0x80;
|
||||
header[4..16].copy_from_slice(&stream_nonce);
|
||||
|
||||
let cipher =
|
||||
Aes256Gcm::new_from_slice(&sealing_key).map_err(|err| SseError::internal(format!("Invalid sealing key: {err}")))?;
|
||||
let nonce =
|
||||
Nonce::try_from(stream_nonce.as_slice()).map_err(|_| SseError::internal("Invalid sealed object-key stream nonce"))?;
|
||||
let ciphertext = cipher
|
||||
.encrypt(
|
||||
&nonce,
|
||||
aes_gcm::aead::Payload {
|
||||
msg: &object_key,
|
||||
aad: &header[..4],
|
||||
},
|
||||
)
|
||||
.map_err(|err| SseError::internal(format!("Failed to seal object key: {err}")))?;
|
||||
|
||||
let mut sealed_key = [0u8; SEALED_KEY_SIZE];
|
||||
sealed_key[..DARE_HEADER_SIZE].copy_from_slice(&header);
|
||||
sealed_key[DARE_HEADER_SIZE..].copy_from_slice(&ciphertext);
|
||||
|
||||
Ok(ManagedSealedKey { iv, sealed_key })
|
||||
}
|
||||
|
||||
pub(crate) fn unseal_object_key(
|
||||
sealed: &ManagedSealedKey,
|
||||
external_key: [u8; 32],
|
||||
sse_type: SSEType,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
let header = &sealed.sealed_key[..DARE_HEADER_SIZE];
|
||||
if header[0] != DARE_VERSION_20 || !is_supported_sealed_object_key_cipher(header[1]) {
|
||||
return Err(SseError::internal("Unsupported sealed object-key DARE header"));
|
||||
}
|
||||
if u16::from_le_bytes([header[2], header[3]]) != 31 || header[4] & 0x80 == 0 {
|
||||
return Err(SseError::internal("Invalid sealed object-key payload header"));
|
||||
}
|
||||
|
||||
let sealing_key = derive_sealing_key(external_key, sealed.iv, managed_sse_domain(sse_type), bucket, object)?;
|
||||
let plaintext = decrypt_sealed_object_key_payload(sealing_key, header, &sealed.sealed_key)?;
|
||||
|
||||
let object_key: [u8; 32] = plaintext
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| SseError::internal("Sealed object key must decrypt to 32 bytes"))?;
|
||||
Ok(object_key)
|
||||
}
|
||||
|
||||
fn try_decode_minio_sealed_key(bytes: &str) -> Result<Option<[u8; SEALED_KEY_SIZE]>, SseError> {
|
||||
let decoded = BASE64_STANDARD
|
||||
.decode_to_vec(bytes)
|
||||
.map_err(|e| SseError::internal(format!("Failed to decode sealed object key: {e}")))?;
|
||||
match decoded.as_slice().try_into() {
|
||||
Ok(sealed_key) => Ok(Some(sealed_key)),
|
||||
Err(_) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_decode_minio_sealing_iv(bytes: &str) -> Result<Option<[u8; SEALED_KEY_IV_SIZE]>, SseError> {
|
||||
let decoded = BASE64_STANDARD
|
||||
.decode_to_vec(bytes)
|
||||
.map_err(|e| SseError::internal(format!("Failed to decode sealing IV: {e}")))?;
|
||||
match decoded.as_slice().try_into() {
|
||||
Ok(iv) => Ok(Some(iv)),
|
||||
Err(_) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_legacy_rustfs_managed_metadata(metadata: &HashMap<String, String>) -> bool {
|
||||
metadata.contains_key(INTERNAL_ENCRYPTION_KEY_HEADER)
|
||||
&& metadata.contains_key(INTERNAL_ENCRYPTION_IV_HEADER)
|
||||
&& !metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER)
|
||||
&& !metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER)
|
||||
}
|
||||
|
||||
/// Infer the managed SSE scheme from the MinIO sealed-key slot that is present.
|
||||
///
|
||||
/// Returns `None` when no managed MinIO slot is present, which keeps callers on
|
||||
/// their fail-closed path. SSE-C is not a managed scheme and is handled by the
|
||||
/// SSE-C read path, so its slot is not considered here.
|
||||
pub(crate) fn infer_minio_managed_sse_type(metadata: &HashMap<String, String>) -> Option<SSEType> {
|
||||
if metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER) {
|
||||
Some(SSEType::SseS3)
|
||||
} else if metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER) {
|
||||
Some(SSEType::SseKms)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_minio_managed_sealed_key(
|
||||
metadata: &HashMap<String, String>,
|
||||
sse_type: SSEType,
|
||||
) -> Result<Option<ManagedSealedKey>, SseError> {
|
||||
let algorithm = match metadata.get(MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER) {
|
||||
Some(algorithm) => algorithm,
|
||||
None => return Ok(None),
|
||||
};
|
||||
if algorithm != MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let iv = match metadata.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER) {
|
||||
Some(iv) => match try_decode_minio_sealing_iv(iv)? {
|
||||
Some(iv) => iv,
|
||||
None => return Ok(None),
|
||||
},
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
let header_key = match sse_type {
|
||||
SSEType::SseS3 => MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
|
||||
SSEType::SseKms => MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
|
||||
SSEType::SseC => MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER,
|
||||
};
|
||||
let sealed_key = match metadata.get(header_key) {
|
||||
Some(value) => match try_decode_minio_sealed_key(value)? {
|
||||
Some(sealed_key) => sealed_key,
|
||||
None => return Ok(None),
|
||||
},
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
Ok(Some(ManagedSealedKey { iv, sealed_key }))
|
||||
}
|
||||
|
||||
/// SSE-C: record the object key sealed under the customer key.
|
||||
pub(crate) fn record_sealed_customer_key(metadata: &mut HashMap<String, String>, sealed: &ManagedSealedKey) {
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(),
|
||||
BASE64_STANDARD.encode_to_string(sealed.iv),
|
||||
);
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(),
|
||||
MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.to_string(),
|
||||
);
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER.to_string(),
|
||||
BASE64_STANDARD.encode_to_string(sealed.sealed_key),
|
||||
);
|
||||
}
|
||||
|
||||
/// Managed SSE: record the wrapped data key in MinIO's slots.
|
||||
///
|
||||
/// With a sealed object key the slots hold what MinIO itself writes. Without one
|
||||
/// the key was formed in Direct mode, and the slots mirror its wrapped data key and
|
||||
/// nonce: [`parse_minio_managed_sealed_key`] turns that shape down by its length, so
|
||||
/// the object is read back in Direct mode.
|
||||
pub(crate) fn record_data_key_in_minio_slots(
|
||||
metadata: &mut HashMap<String, String>,
|
||||
material: &EncryptionMaterial,
|
||||
wrapped_data_key: &[u8],
|
||||
) {
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(),
|
||||
MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.to_string(),
|
||||
);
|
||||
if let Some(kms_key_id) = &material.kms_key_id {
|
||||
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_string(), kms_key_id.to_string());
|
||||
}
|
||||
|
||||
let encoded_data_key = BASE64_STANDARD.encode_to_string(wrapped_data_key);
|
||||
match &material.managed_sealed_key {
|
||||
Some(sealed) => {
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(),
|
||||
BASE64_STANDARD.encode_to_string(sealed.iv),
|
||||
);
|
||||
match material.sse_type {
|
||||
SSEType::SseS3 => {
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(),
|
||||
BASE64_STANDARD.encode_to_string(sealed.sealed_key),
|
||||
);
|
||||
}
|
||||
SSEType::SseKms => {
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(),
|
||||
BASE64_STANDARD.encode_to_string(sealed.sealed_key),
|
||||
);
|
||||
}
|
||||
SSEType::SseC => {}
|
||||
}
|
||||
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), encoded_data_key);
|
||||
}
|
||||
None => {
|
||||
metadata.insert(
|
||||
MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(),
|
||||
BASE64_STANDARD.encode_to_string(material.base_nonce),
|
||||
);
|
||||
match material.sse_type {
|
||||
SSEType::SseS3 => {
|
||||
metadata.insert(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(), encoded_data_key);
|
||||
}
|
||||
SSEType::SseKms => {
|
||||
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), encoded_data_key.clone());
|
||||
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), encoded_data_key);
|
||||
}
|
||||
SSEType::SseC => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Managed SSE: read back the wrapped data key that seals `sealed_key`.
|
||||
///
|
||||
/// `normalized_metadata` is `metadata` with the managed keys normalized.
|
||||
pub(crate) fn read_sealed_data_key(
|
||||
metadata: &HashMap<String, String>,
|
||||
normalized_metadata: &HashMap<String, String>,
|
||||
sealed_key: ManagedSealedKey,
|
||||
) -> Result<StoredDataKey, SseError> {
|
||||
let encrypted_key_b64 = normalized_metadata
|
||||
.get(INTERNAL_ENCRYPTION_KEY_HEADER)
|
||||
.or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER))
|
||||
.ok_or_else(|| SseError::internal("Missing encrypted key in metadata"))?;
|
||||
let wrapped = BASE64_STANDARD
|
||||
.decode_to_vec(encrypted_key_b64)
|
||||
.map_err(|e| SseError::internal(format!("Failed to decode encrypted key: {e}")))?;
|
||||
|
||||
Ok(StoredDataKey {
|
||||
wrapped,
|
||||
algorithm: normalized_metadata
|
||||
.get(INTERNAL_ENCRYPTION_ALGORITHM_HEADER)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "AES256".to_string()),
|
||||
mode: StoredKeyMode::Object { 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<NewObjectKey, SseError> {
|
||||
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<NewObjectKey, SseError> {
|
||||
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<NewObjectKey, SseError> {
|
||||
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<NewObjectKey, SseError> {
|
||||
new_sealed_object_key(data_key.plaintext_key, sse_type, bucket, key)
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Reading: recognize how a stored object was keyed, and recover its key.
|
||||
//!
|
||||
//! What an object recorded is the only source of truth here. The scheme a request
|
||||
//! advertises and whether a KMS is running now are write policy and runtime state;
|
||||
//! neither says how an object written earlier was keyed.
|
||||
|
||||
use crate::core::keying::context::{build_object_encryption_context, decode_minio_kms_context};
|
||||
use crate::core::keying::direct::{read_stored_ssec_nonce, read_wrapped_data_key};
|
||||
use crate::core::keying::material::EncryptionKeyKind;
|
||||
use crate::core::keying::metadata::recode_minio_kms_context;
|
||||
#[cfg(feature = "rio-v2")]
|
||||
use crate::core::keying::object::{
|
||||
infer_minio_managed_sse_type, is_legacy_rustfs_managed_metadata, parse_minio_managed_sealed_key, read_sealed_data_key,
|
||||
unseal_object_key,
|
||||
};
|
||||
use crate::core::keying::{StoredDataKey, StoredKeyMode};
|
||||
use crate::error::SseError;
|
||||
use crate::host::SseHost;
|
||||
use crate::kms::local::is_local_sse_dek;
|
||||
#[cfg(feature = "rio-v2")]
|
||||
use crate::kms::local::is_rustfs_managed_data_key;
|
||||
#[cfg(feature = "rio-v2")]
|
||||
use crate::kms::provider::decrypt_unenveloped_sealed_dek;
|
||||
use crate::kms::provider::{SseDekProvider, bare_data_key_kms_provider, get_local_sse_dek_provider, kms_sse_dek_provider};
|
||||
use rustfs_kms::is_data_key_envelope;
|
||||
use rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS;
|
||||
use rustfs_utils::http::object_encryption_keys::{
|
||||
INTERNAL_ENCRYPTION_KEY_ID_HEADER, SSEType, contains_managed_encryption_metadata, normalize_managed_metadata,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The key a stored object is decrypted with, recovered from what the object recorded.
|
||||
pub(crate) struct OpenedObjectKey {
|
||||
/// 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 the object was written in.
|
||||
pub(crate) key_kind: EncryptionKeyKind,
|
||||
}
|
||||
|
||||
/// The managed scheme a stored object was written under, or `None` when this build
|
||||
/// cannot establish it.
|
||||
fn stored_managed_sse_type(metadata: &HashMap<String, String>) -> Option<SSEType> {
|
||||
match metadata.get("x-amz-server-side-encryption").map(String::as_str) {
|
||||
Some(AMZ_ENCRYPTION_KMS) => Some(SSEType::SseKms),
|
||||
Some(_) => Some(SSEType::SseS3),
|
||||
// MinIO never persists the public scheme header: `crypto.S3.CreateMetadata`
|
||||
// writes only the `X-Minio-Internal-*` family and the public header is
|
||||
// synthesized onto the response by `DecryptObjectInfo`. Requiring it here
|
||||
// is what made every MinIO-encrypted object unreadable (backlog#1638).
|
||||
//
|
||||
// Inferring from the sealed-key slot is self-consistent by construction:
|
||||
// the slot decides which header the unseal reads AND which domain string
|
||||
// the sealing key is derived under, so a scheme that disagrees with the
|
||||
// slot cannot silently derive a wrong key — it finds no key at all.
|
||||
// Inferring from the KMS key id would NOT be safe: MinIO writes
|
||||
// `-S3-Kms-Key-Id` on SSE-S3 objects too.
|
||||
//
|
||||
// An object whose scheme cannot be established stays fail-closed, and
|
||||
// deliberately not through an error raised here: the read plan independently
|
||||
// classifies the object as encrypted from its markers and refuses to serve
|
||||
// it without material, so it never degrades into a plaintext read.
|
||||
#[cfg(feature = "rio-v2")]
|
||||
None => infer_minio_managed_sse_type(metadata),
|
||||
// Without the rio-v2 reader there is no MinIO-format read path to serve
|
||||
// such an object with, so it stays on the fail-closed branch.
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// SSE-C: recover the object's key from the customer key.
|
||||
///
|
||||
/// A sealed object key recorded in MinIO's slot is unsealed under the customer key;
|
||||
/// otherwise the customer key is the object's key, under the nonce the object recorded.
|
||||
pub(crate) fn open_under_customer_key(
|
||||
metadata: &HashMap<String, String>,
|
||||
customer_key: [u8; 32],
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
) -> Result<OpenedObjectKey, SseError> {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
if let Some(sealed_key) = parse_minio_managed_sealed_key(metadata, SSEType::SseC)? {
|
||||
return Ok(OpenedObjectKey {
|
||||
key_bytes: unseal_object_key(&sealed_key, customer_key, SSEType::SseC, bucket, key)?,
|
||||
base_nonce: [0; 12],
|
||||
key_kind: EncryptionKeyKind::Object,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(OpenedObjectKey {
|
||||
key_bytes: customer_key,
|
||||
base_nonce: read_stored_ssec_nonce(metadata, bucket, key),
|
||||
key_kind: EncryptionKeyKind::Direct,
|
||||
})
|
||||
}
|
||||
|
||||
/// A stored managed-SSE object, as recognized from its metadata alone.
|
||||
pub(crate) struct StoredManagedKey<'a> {
|
||||
/// The object's metadata as stored.
|
||||
metadata: &'a HashMap<String, String>,
|
||||
/// The same metadata with the managed keys normalized.
|
||||
normalized_metadata: HashMap<String, String>,
|
||||
/// The scheme the object was written under.
|
||||
pub(crate) sse_type: SSEType,
|
||||
/// The KMS key id the object recorded, if it recorded one.
|
||||
pub(crate) recorded_kms_key_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Recognize a stored managed-SSE object.
|
||||
///
|
||||
/// `None` means the object carries no managed-SSE metadata, or carries some whose
|
||||
/// scheme this build cannot establish.
|
||||
pub(crate) fn recognize_stored_managed_key(metadata: &HashMap<String, String>) -> Option<StoredManagedKey<'_>> {
|
||||
if !contains_managed_encryption_metadata(metadata) {
|
||||
return None;
|
||||
}
|
||||
let sse_type = stored_managed_sse_type(metadata)?;
|
||||
|
||||
let normalized_metadata = normalize_managed_metadata(metadata, Some(recode_minio_kms_context));
|
||||
let recorded_kms_key_id = normalized_metadata
|
||||
.get(INTERNAL_ENCRYPTION_KEY_ID_HEADER)
|
||||
.or_else(|| metadata.get("x-amz-server-side-encryption-aws-kms-key-id"))
|
||||
.cloned();
|
||||
|
||||
Some(StoredManagedKey {
|
||||
metadata,
|
||||
normalized_metadata,
|
||||
sse_type,
|
||||
recorded_kms_key_id,
|
||||
})
|
||||
}
|
||||
|
||||
/// Managed SSE: unwrap the stored data key and recover the object's key from it.
|
||||
///
|
||||
/// `kms_key_id` is the key the read was authorized against. Returns the object's key
|
||||
/// together with the algorithm the object recorded.
|
||||
pub(crate) async fn open_under_stored_data_key(
|
||||
host: &dyn SseHost,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
stored: &StoredManagedKey<'_>,
|
||||
kms_key_id: &str,
|
||||
) -> Result<(OpenedObjectKey, String), SseError> {
|
||||
let record = read_stored_data_key(host, stored).await?;
|
||||
let data_key = unwrap_stored_data_key(host, bucket, key, stored, &record, kms_key_id).await?;
|
||||
|
||||
let opened = match record.mode {
|
||||
StoredKeyMode::Direct { base_nonce } => OpenedObjectKey {
|
||||
key_bytes: data_key,
|
||||
base_nonce,
|
||||
key_kind: EncryptionKeyKind::Direct,
|
||||
},
|
||||
#[cfg(feature = "rio-v2")]
|
||||
StoredKeyMode::Object { sealed_key } => OpenedObjectKey {
|
||||
key_bytes: unseal_object_key(&sealed_key, data_key, stored.sse_type, bucket, key)?,
|
||||
base_nonce: [0u8; 12],
|
||||
key_kind: EncryptionKeyKind::Object,
|
||||
},
|
||||
};
|
||||
|
||||
Ok((opened, record.algorithm))
|
||||
}
|
||||
|
||||
/// Read the stored data key in the mode the object recorded.
|
||||
///
|
||||
/// This is the recognition order: a mode listed earlier claims the object first, and
|
||||
/// Direct takes whatever no other mode recognizes. A mode this build cannot read is
|
||||
/// not listed, so its objects fail in the Direct reader instead of being misread.
|
||||
async fn read_stored_data_key(host: &dyn SseHost, stored: &StoredManagedKey<'_>) -> Result<StoredDataKey, SseError> {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
if let Some(sealed_key) = parse_minio_managed_sealed_key(stored.metadata, stored.sse_type)? {
|
||||
return read_sealed_data_key(stored.metadata, &stored.normalized_metadata, sealed_key);
|
||||
}
|
||||
|
||||
read_wrapped_data_key(host, &stored.normalized_metadata).await
|
||||
}
|
||||
|
||||
/// Unwrap the stored data key with the provider its own bytes identify.
|
||||
async fn unwrap_stored_data_key(
|
||||
host: &dyn SseHost,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
stored: &StoredManagedKey<'_>,
|
||||
record: &StoredDataKey,
|
||||
kms_key_id: &str,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
let kms_context = if matches!(stored.sse_type, SSEType::SseKms) {
|
||||
decode_minio_kms_context(stored.metadata)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let object_context = build_object_encryption_context(bucket, key, kms_context.as_ref());
|
||||
let wrapped = record.wrapped.as_slice();
|
||||
|
||||
// Persisted wrapping format is the read-side source of truth. The
|
||||
// advertised SSE scheme and current KMS availability are write policy
|
||||
// and runtime state, neither of which identifies the historical provider.
|
||||
//
|
||||
// The one shape that cannot name its provider is a backend-native blob
|
||||
// stored without an envelope. It is offered to the KMS only when the
|
||||
// local provider could not have written those bytes and the active
|
||||
// backend is one whose released versions persisted them that way.
|
||||
let bare_kms = if is_data_key_envelope(wrapped) || is_local_sse_dek(wrapped) {
|
||||
None
|
||||
} else {
|
||||
bare_data_key_kms_provider(host).await
|
||||
};
|
||||
|
||||
// A MinIO sealed key alone does not mean MinIO wrote the object: RustFS's own
|
||||
// writer fills MinIO's metadata slots too, while still storing a RustFS
|
||||
// envelope in them, so neither the slot nor the header name distinguishes the
|
||||
// two. The data key's own shape does. RustFS envelopes are strictly-parsed
|
||||
// JSON; MinIO's builtin-KMS ciphertext is opaque bytes that match neither, so
|
||||
// recognizing RustFS positively — and treating only the remainder as MinIO —
|
||||
// keeps a RustFS envelope from ever reaching MinIO's decoder.
|
||||
#[cfg(feature = "rio-v2")]
|
||||
if matches!(record.mode, StoredKeyMode::Object { .. }) && !is_rustfs_managed_data_key(wrapped) {
|
||||
return decrypt_unenveloped_sealed_dek(bare_kms, get_local_sse_dek_provider(), wrapped, kms_key_id, &object_context)
|
||||
.await;
|
||||
}
|
||||
|
||||
let provider: Arc<dyn SseDekProvider> = if is_data_key_envelope(wrapped) {
|
||||
kms_sse_dek_provider(host).await?
|
||||
} else if let Some(kms_provider) = bare_kms {
|
||||
kms_provider
|
||||
} else {
|
||||
get_local_sse_dek_provider()?
|
||||
};
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
if is_legacy_rustfs_managed_metadata(&stored.normalized_metadata) {
|
||||
return provider.decrypt_legacy_sse_dek(wrapped, kms_key_id, &object_context).await;
|
||||
}
|
||||
|
||||
provider.decrypt_sse_dek(wrapped, kms_key_id, &object_context).await
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! SSE key resolution: the S3-defined schemes, the internal keying modes, and the entry points that join them.
|
||||
|
||||
pub(crate) mod audit;
|
||||
pub(crate) mod keying;
|
||||
pub(crate) mod read;
|
||||
pub(crate) mod request;
|
||||
pub(crate) mod rewrap;
|
||||
pub(crate) mod s3;
|
||||
pub(crate) mod write;
|
||||
@@ -1,303 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Read entry points: resolve the decryption material, or the response headers, for a stored object.
|
||||
|
||||
use crate::core::audit::{record_managed_kms_outcome, stored_envelope_master_key_version};
|
||||
use crate::core::keying::material::DecryptionMaterial;
|
||||
use crate::core::keying::metadata::stored_ssec_metadata;
|
||||
use crate::core::keying::stored::{
|
||||
StoredManagedKey, open_under_customer_key, open_under_stored_data_key, recognize_stored_managed_key,
|
||||
};
|
||||
use crate::core::request::SseKmsPrincipal;
|
||||
use crate::core::s3::authorization::authorize_sse_kms_key;
|
||||
use crate::core::s3::headers::{SseReadResponseHeaders, managed_sse_public_header};
|
||||
use crate::core::s3::scheme::resolve_stored_kms_key_id;
|
||||
use crate::core::s3::ssec::{SsecParams, require_matching_ssec_key, stored_ssec_algorithm, validate_ssec_params};
|
||||
use crate::error::SseError;
|
||||
use crate::host::SseHost;
|
||||
use rustfs_policy::policy::action::KmsAction;
|
||||
use rustfs_utils::http::headers::AMZ_ENCRYPTION_AES;
|
||||
use rustfs_utils::http::object_encryption_keys::{SSEType, contains_managed_encryption_metadata, stored_managed_encryption_key};
|
||||
use std::collections::HashMap;
|
||||
|
||||
impl std::fmt::Debug for DecryptionRequest<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DecryptionRequest").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Request parameters for unified decryption
|
||||
pub struct DecryptionRequest<'a> {
|
||||
/// Bucket name
|
||||
pub bucket: &'a str,
|
||||
/// Object key
|
||||
pub key: &'a str,
|
||||
/// Object metadata containing encryption headers
|
||||
pub metadata: &'a HashMap<String, String>,
|
||||
/// SSE-C key (Base64-encoded) - required if object was encrypted with SSE-C
|
||||
pub sse_customer_key: Option<&'a String>,
|
||||
/// SSE-C key MD5 (Base64-encoded) - required if object was encrypted with SSE-C
|
||||
pub sse_customer_key_md5: Option<&'a String>,
|
||||
/// Caller the SSE-KMS key usage is authorized as. `None` marks an internal caller.
|
||||
pub principal: Option<&'a SseKmsPrincipal>,
|
||||
}
|
||||
|
||||
/// **Core API**: Apply decryption based on stored metadata
|
||||
///
|
||||
/// This function automatically detects the encryption type from metadata:
|
||||
/// - SSE-C if customer key is provided
|
||||
/// - SSE-S3/SSE-KMS if managed encryption metadata is found
|
||||
/// - None if object is not encrypted
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `request` - Decryption request with metadata and optional customer key
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(Some(material))` - Decryption should be applied with the returned material
|
||||
/// * `Ok(None)` - Object is not encrypted
|
||||
/// * `Err` - Decryption configuration error or key mismatch
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust,ignore
|
||||
/// let request = DecryptionRequest {
|
||||
/// bucket: &bucket,
|
||||
/// key: &key,
|
||||
/// metadata: &metadata,
|
||||
/// sse_customer_key: sse_customer_key.as_deref(),
|
||||
/// sse_customer_key_md5: sse_customer_key_md5.as_deref(),
|
||||
/// };
|
||||
///
|
||||
/// if let Some(material) = sse_decryption(host, request).await? {
|
||||
/// content_size = material.original_size.unwrap_or(actual_size);
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn sse_decryption(host: &dyn SseHost, request: DecryptionRequest<'_>) -> Result<Option<DecryptionMaterial>, SseError> {
|
||||
// Check for SSE-C encryption
|
||||
if stored_ssec_metadata(request.metadata) {
|
||||
let (key, key_md5) = require_matching_ssec_key(request.metadata, request.sse_customer_key, request.sse_customer_key_md5)?;
|
||||
|
||||
let mut material = apply_ssec_decryption_material(request.bucket, request.key, request.metadata, key, key_md5).await?;
|
||||
material.customer_key_md5 = Some(key_md5.clone());
|
||||
return Ok(Some(material));
|
||||
}
|
||||
|
||||
// Check for managed SSE encryption
|
||||
if contains_managed_encryption_metadata(request.metadata) {
|
||||
return apply_managed_decryption_material(host, request.bucket, request.key, request.metadata, request.principal).await;
|
||||
}
|
||||
|
||||
// No encryption detected
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Read-side response classification for an object whose payload the object
|
||||
/// layer's encryption resolver already decrypted.
|
||||
///
|
||||
/// [`sse_decryption`] both unwraps the data key and derives the response
|
||||
/// headers. The GET path only needs the latter — its stream comes out of the
|
||||
/// object layer decrypted (see [`SseObjectEncryptionResolver`]) — so calling
|
||||
/// [`sse_decryption`] there performed a second KMS `Decrypt` per request whose
|
||||
/// key bytes were discarded. This function reproduces that call's header,
|
||||
/// validation, authorization and audit behavior from stored metadata alone.
|
||||
///
|
||||
/// Contract, mirrored from [`sse_decryption`] item by item:
|
||||
/// - SSE-C: missing request key/MD5 and stored/request MD5 mismatch fail with
|
||||
/// the same errors and precedence, and the provided key is fully validated.
|
||||
/// - Managed SSE: per-key `kms:Decrypt` authorization runs ahead of every other
|
||||
/// failure mode, and the request's KMS audit summary records the same
|
||||
/// scheme/key/version/outcome fields the unwrap-based path recorded. The
|
||||
/// success outcome is honest because a failed unwrap aborts the read in the
|
||||
/// object layer before response classification is ever reached.
|
||||
/// - Objects without SSE metadata — and managed metadata whose scheme cannot
|
||||
/// be established in this build — classify as `None`, exactly where
|
||||
/// [`sse_decryption`] returned `None`.
|
||||
pub async fn classify_sse_read_response(
|
||||
host: &dyn SseHost,
|
||||
request: DecryptionRequest<'_>,
|
||||
) -> Result<Option<SseReadResponseHeaders>, SseError> {
|
||||
if stored_ssec_metadata(request.metadata) {
|
||||
let (key, key_md5) = require_matching_ssec_key(request.metadata, request.sse_customer_key, request.sse_customer_key_md5)?;
|
||||
|
||||
let algorithm = stored_ssec_algorithm(request.metadata);
|
||||
validate_ssec_params(SsecParams {
|
||||
algorithm: algorithm.to_string(),
|
||||
key: key.to_string(),
|
||||
key_md5: key_md5.to_string(),
|
||||
})?;
|
||||
|
||||
return Ok(Some(SseReadResponseHeaders {
|
||||
server_side_encryption: String::from(AMZ_ENCRYPTION_AES),
|
||||
sse_customer_algorithm: Some(String::from(algorithm)),
|
||||
sse_customer_key_md5: Some(key_md5.clone()),
|
||||
ssekms_key_id: None,
|
||||
}));
|
||||
}
|
||||
|
||||
// Same scheme and key resolution as the unwrap path, so authorization and the
|
||||
// response header name the same key.
|
||||
let Some((stored, kms_key_id)) = resolve_stored_managed_key(host, request.metadata).await else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// Ahead of every other failure mode, so a denied caller learns nothing
|
||||
// about the key beyond "not yours".
|
||||
if let Err(error) =
|
||||
authorize_sse_kms_key(host, request.principal, stored.sse_type, KmsAction::DecryptAction, &kms_key_id).await
|
||||
{
|
||||
if let Some((sse_type, key_id)) = stored_managed_encryption_key(request.metadata) {
|
||||
record_managed_kms_outcome(
|
||||
request.principal,
|
||||
sse_type,
|
||||
Some(&key_id),
|
||||
|| stored_envelope_master_key_version(request.metadata),
|
||||
Err(&error),
|
||||
);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
record_managed_kms_outcome(
|
||||
request.principal,
|
||||
stored.sse_type,
|
||||
Some(&kms_key_id),
|
||||
|| stored_envelope_master_key_version(request.metadata),
|
||||
Ok(()),
|
||||
);
|
||||
|
||||
Ok(Some(SseReadResponseHeaders {
|
||||
server_side_encryption: managed_sse_public_header(stored.sse_type).to_string(),
|
||||
sse_customer_algorithm: None,
|
||||
sse_customer_key_md5: None,
|
||||
// The key id was needed above to authorize the read, but an AES256
|
||||
// object's wrapping key is internal: only aws:kms objects advertise it.
|
||||
ssekms_key_id: matches!(stored.sse_type, SSEType::SseKms).then_some(kms_key_id),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Recognize a stored managed-SSE object and name the key it is read under.
|
||||
///
|
||||
/// One resolution for every read: authorization, the response headers and the
|
||||
/// unwrap all name the key this returns. `None` means the object carries no
|
||||
/// managed-SSE metadata, or carries some whose scheme this build cannot establish.
|
||||
async fn resolve_stored_managed_key<'m>(
|
||||
host: &dyn SseHost,
|
||||
metadata: &'m HashMap<String, String>,
|
||||
) -> Option<(StoredManagedKey<'m>, String)> {
|
||||
let stored = recognize_stored_managed_key(metadata)?;
|
||||
let kms_key_id = resolve_stored_kms_key_id(host, stored.recorded_kms_key_id.clone()).await;
|
||||
Some((stored, kms_key_id))
|
||||
}
|
||||
|
||||
pub(crate) async fn apply_ssec_decryption_material(
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
metadata: &HashMap<String, String>,
|
||||
sse_key: &str,
|
||||
sse_key_md5: &str,
|
||||
) -> Result<DecryptionMaterial, SseError> {
|
||||
// Validate provided key
|
||||
let algorithm = stored_ssec_algorithm(metadata);
|
||||
|
||||
let params = SsecParams {
|
||||
algorithm: algorithm.to_string(),
|
||||
key: sse_key.to_string(),
|
||||
key_md5: sse_key_md5.to_string(),
|
||||
};
|
||||
|
||||
let validated = validate_ssec_params(params)?;
|
||||
let opened = open_under_customer_key(metadata, validated.key_bytes, bucket, key)?;
|
||||
|
||||
Ok(DecryptionMaterial {
|
||||
sse_type: SSEType::SseC,
|
||||
server_side_encryption: String::from(AMZ_ENCRYPTION_AES), // const
|
||||
kms_key_id: None,
|
||||
algorithm: String::from(algorithm),
|
||||
|
||||
customer_key_md5: None,
|
||||
key_bytes: opened.key_bytes,
|
||||
base_nonce: opened.base_nonce,
|
||||
key_kind: opened.key_kind,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn apply_managed_decryption_material(
|
||||
host: &dyn SseHost,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
metadata: &HashMap<String, String>,
|
||||
principal: Option<&SseKmsPrincipal>,
|
||||
) -> Result<Option<DecryptionMaterial>, SseError> {
|
||||
let result = apply_managed_decryption_material_inner(host, bucket, key, metadata, principal).await;
|
||||
|
||||
match &result {
|
||||
// `None` means the object carries no managed-SSE metadata — SSE-C and
|
||||
// plaintext objects never reach KMS and must not appear in the summary.
|
||||
Ok(None) => {}
|
||||
Ok(Some(material)) => record_managed_kms_outcome(
|
||||
principal,
|
||||
material.sse_type,
|
||||
material.kms_key_id.as_deref(),
|
||||
|| stored_envelope_master_key_version(metadata),
|
||||
Ok(()),
|
||||
),
|
||||
Err(error) => {
|
||||
if let Some((sse_type, key_id)) = stored_managed_encryption_key(metadata) {
|
||||
record_managed_kms_outcome(
|
||||
principal,
|
||||
sse_type,
|
||||
Some(&key_id),
|
||||
|| stored_envelope_master_key_version(metadata),
|
||||
Err(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn apply_managed_decryption_material_inner(
|
||||
host: &dyn SseHost,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
metadata: &HashMap<String, String>,
|
||||
principal: Option<&SseKmsPrincipal>,
|
||||
) -> Result<Option<DecryptionMaterial>, SseError> {
|
||||
let Some((stored, kms_key_id)) = resolve_stored_managed_key(host, metadata).await else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// Ahead of every other failure mode below, so a denied caller learns nothing about the
|
||||
// key beyond "not yours" — not whether it is disabled, pending deletion, or unreadable.
|
||||
authorize_sse_kms_key(host, principal, stored.sse_type, KmsAction::DecryptAction, &kms_key_id).await?;
|
||||
|
||||
let (opened, algorithm) = open_under_stored_data_key(host, bucket, key, &stored, &kms_key_id).await?;
|
||||
|
||||
Ok(Some(DecryptionMaterial {
|
||||
sse_type: stored.sse_type,
|
||||
// Synthesized from the resolved scheme rather than read back from
|
||||
// metadata: a MinIO-written object has no stored scheme header, which is
|
||||
// exactly why the scheme had to be inferred. MinIO synthesizes the same
|
||||
// header onto its own responses.
|
||||
server_side_encryption: managed_sse_public_header(stored.sse_type).to_string(),
|
||||
kms_key_id: Some(kms_key_id),
|
||||
algorithm,
|
||||
customer_key_md5: None,
|
||||
|
||||
key_bytes: opened.key_bytes,
|
||||
base_nonce: opened.base_nonce,
|
||||
key_kind: opened.key_kind,
|
||||
}))
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The caller an SSE operation is authorized as.
|
||||
|
||||
use crate::core::audit::{KmsRequestAudit, kms_request_audit};
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
use crate::host::KmsKeyAuthorizer;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Identity a data-path KMS key operation is attributed to.
|
||||
///
|
||||
/// Only requests that crossed the S3 authorization boundary carry one. Internal
|
||||
/// callers — replication, lifecycle transition, heal, scanner — enter the object
|
||||
/// layer directly and run with server credentials, so they never build a principal
|
||||
/// and are exempt by construction; `None` therefore means "system principal".
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SseKmsPrincipal {
|
||||
pub(crate) account: String,
|
||||
groups: Option<Vec<String>>,
|
||||
is_owner: bool,
|
||||
claims: HashMap<String, Value>,
|
||||
conditions: HashMap<String, Vec<String>>,
|
||||
/// Audit slot of the S3 request this principal was built for, when the request
|
||||
/// is being audited. The principal is the only request-derived value that reaches
|
||||
/// the managed-SSE code paths, so it doubles as the carrier for the slot.
|
||||
pub(crate) request_audit: Option<Arc<KmsRequestAudit>>,
|
||||
/// Test-only decision overrides. Carried per principal rather than in a global slot so
|
||||
/// concurrent tests cannot observe each other's injection.
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub(crate) test_hooks: Option<TestAuthorizationHooks>,
|
||||
}
|
||||
|
||||
impl SseKmsPrincipal {
|
||||
/// Build the principal of a request that crossed the S3 authorization boundary.
|
||||
///
|
||||
/// Anonymous requests use an empty account, matching the bucket-policy authorization
|
||||
/// path. This keeps every request that crossed the S3 boundary distinct from trusted
|
||||
/// internal callers, which are represented by `None`.
|
||||
pub fn new(
|
||||
account: String,
|
||||
groups: Option<Vec<String>>,
|
||||
is_owner: bool,
|
||||
claims: HashMap<String, Value>,
|
||||
conditions: HashMap<String, Vec<String>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
account,
|
||||
groups,
|
||||
is_owner,
|
||||
claims,
|
||||
conditions,
|
||||
request_audit: None,
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
test_hooks: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The access key the request authenticated with; empty for an anonymous request.
|
||||
pub fn account(&self) -> &str {
|
||||
&self.account
|
||||
}
|
||||
|
||||
pub fn groups(&self) -> &Option<Vec<String>> {
|
||||
&self.groups
|
||||
}
|
||||
|
||||
pub fn is_owner(&self) -> bool {
|
||||
self.is_owner
|
||||
}
|
||||
|
||||
pub fn claims(&self) -> &HashMap<String, Value> {
|
||||
&self.claims
|
||||
}
|
||||
|
||||
/// Policy condition values of the request that do not depend on the resource.
|
||||
pub fn conditions(&self) -> &HashMap<String, Vec<String>> {
|
||||
&self.conditions
|
||||
}
|
||||
|
||||
/// Attach the audit slot opened for `request_id`, if that request is being audited
|
||||
/// (see [`KmsRequestAuditScope::register`]).
|
||||
#[must_use]
|
||||
pub fn with_request_id(mut self, request_id: &str) -> Self {
|
||||
self.request_audit = kms_request_audit(request_id);
|
||||
self
|
||||
}
|
||||
|
||||
/// Override the enforcement switch and the authorizer for this principal only.
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
#[must_use]
|
||||
pub fn with_test_hooks(mut self, hooks: Option<TestAuthorizationHooks>) -> Self {
|
||||
self.test_hooks = hooks;
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn for_test(account: &str, enforced: bool, authorizer: Arc<dyn KmsKeyAuthorizer>) -> Self {
|
||||
Self {
|
||||
account: account.to_string(),
|
||||
groups: None,
|
||||
is_owner: false,
|
||||
claims: HashMap::new(),
|
||||
conditions: HashMap::new(),
|
||||
request_audit: None,
|
||||
test_hooks: Some(TestAuthorizationHooks { enforced, authorizer }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind this principal to `audit` so managed-SSE operations performed for it are
|
||||
/// summarised onto the request's S3 audit entry.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_request_audit(mut self, audit: Arc<KmsRequestAudit>) -> Self {
|
||||
self.request_audit = Some(audit);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-principal override of SSE-KMS key authorization, for tests.
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
#[derive(Clone)]
|
||||
pub struct TestAuthorizationHooks {
|
||||
pub enforced: bool,
|
||||
pub authorizer: Arc<dyn KmsKeyAuthorizer>,
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
impl std::fmt::Debug for TestAuthorizationHooks {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("TestAuthorizationHooks")
|
||||
.field("enforced", &self.enforced)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Re-wrap a stored data key onto its master key's current version.
|
||||
|
||||
use crate::core::keying::context::{build_object_encryption_context, decode_minio_kms_context};
|
||||
use crate::core::keying::metadata::recode_minio_kms_context;
|
||||
use crate::error::SseError;
|
||||
use crate::host::SseHost;
|
||||
use crate::kms::provider::kms_sse_dek_provider;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use rustfs_kms::is_data_key_envelope;
|
||||
use rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS;
|
||||
use rustfs_utils::http::object_encryption_keys::{
|
||||
INTERNAL_ENCRYPTION_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER, SSEType,
|
||||
contains_managed_encryption_metadata, normalize_managed_metadata,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Outcome of a single object's DEK rewrap attempt.
|
||||
// Consumed by the bulk rekey sweep in the follow-up PR; tests exercise it now.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum ObjectDekRewrapOutcome {
|
||||
/// The object carries no KMS-wrapped RustFS data-key envelope this build
|
||||
/// can rewrap: plaintext, SSE-C, or a MinIO-sealed data key.
|
||||
NotApplicable,
|
||||
/// The envelope is already on the current master key version and format;
|
||||
/// the caller must persist nothing, so a sweep re-run converges.
|
||||
AlreadyCurrent,
|
||||
/// The envelope was rewrapped. `metadata` holds the overrides to merge
|
||||
/// into the object's user-defined metadata — every stored copy of the old
|
||||
/// envelope, replaced — via `ObjectLayer::put_object_metadata`.
|
||||
Rewrapped { metadata: HashMap<String, String> },
|
||||
}
|
||||
|
||||
/// Rewrap the KMS-wrapped data key in an object's stored metadata onto its
|
||||
/// master key's current version (and current envelope format), without
|
||||
/// touching the object's data or its plaintext DEK.
|
||||
///
|
||||
/// Mirrors the managed decrypt path byte for byte where it matters: the
|
||||
/// envelope is located through the same normalized-header resolution, and the
|
||||
/// encryption context is rebuilt with the same helpers, so an envelope the
|
||||
/// read path can open is exactly an envelope this can rewrap. The KMS backend
|
||||
/// owns the format and the no-op decision.
|
||||
///
|
||||
/// The returned overrides replace every stored copy of the old envelope
|
||||
/// (RustFS's internal header and the MinIO-compatible slots that the writer
|
||||
/// fills with the same bytes). A copy left behind would win a read-path
|
||||
/// fallback and resurrect the old wrapping, so finding no replaceable copy is
|
||||
/// an error, never a silent success.
|
||||
pub async fn rewrap_object_encryption_metadata(
|
||||
host: &dyn SseHost,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
metadata: &HashMap<String, String>,
|
||||
) -> Result<ObjectDekRewrapOutcome, SseError> {
|
||||
if !contains_managed_encryption_metadata(metadata) {
|
||||
return Ok(ObjectDekRewrapOutcome::NotApplicable);
|
||||
}
|
||||
|
||||
let encryption_type = match metadata.get("x-amz-server-side-encryption").map(String::as_str) {
|
||||
Some(AMZ_ENCRYPTION_KMS) => SSEType::SseKms,
|
||||
Some(_) => SSEType::SseS3,
|
||||
// MinIO-written objects synthesize the public header on read; their
|
||||
// sealed data keys are not RustFS envelopes and fall out below.
|
||||
None => SSEType::SseS3,
|
||||
};
|
||||
|
||||
let normalized_metadata = normalize_managed_metadata(metadata, Some(recode_minio_kms_context));
|
||||
let Some(envelope_b64) = normalized_metadata
|
||||
.get(INTERNAL_ENCRYPTION_KEY_HEADER)
|
||||
.or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER))
|
||||
else {
|
||||
return Ok(ObjectDekRewrapOutcome::NotApplicable);
|
||||
};
|
||||
let encrypted_data_key = BASE64_STANDARD
|
||||
.decode_to_vec(envelope_b64)
|
||||
.map_err(|e| SseError::internal(format!("Failed to decode encrypted key: {e}")))?;
|
||||
// Only RustFS envelopes are rewrappable here; MinIO's builtin-KMS
|
||||
// ciphertext is opaque bytes owned by a different root of trust.
|
||||
if !is_data_key_envelope(&encrypted_data_key) {
|
||||
return Ok(ObjectDekRewrapOutcome::NotApplicable);
|
||||
}
|
||||
|
||||
let kms_context = if matches!(encryption_type, SSEType::SseKms) {
|
||||
decode_minio_kms_context(metadata)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let object_context = build_object_encryption_context(bucket, key, kms_context.as_ref());
|
||||
|
||||
// The same provider selection as the managed decrypt path.
|
||||
let provider = kms_sse_dek_provider(host).await?;
|
||||
let response = provider.rewrap_sse_dek(&encrypted_data_key, &object_context).await?;
|
||||
if !response.rewrapped {
|
||||
return Ok(ObjectDekRewrapOutcome::AlreadyCurrent);
|
||||
}
|
||||
|
||||
// Replace every stored copy of the old envelope, keyed by value and
|
||||
// matched case-insensitively: metadata key casing drifts through the
|
||||
// storage layer, and an override inserted under a differently-cased name
|
||||
// would sit beside the old copy instead of replacing it. The MinIO
|
||||
// sealed-key slots can instead hold a sealed *object* key (rio-v2 writer);
|
||||
// those bytes differ from the envelope and are untouched — the data key
|
||||
// they seal is unchanged by a rewrap.
|
||||
const REWRAP_ENVELOPE_HEADERS: [&str; 4] = [
|
||||
INTERNAL_ENCRYPTION_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
|
||||
];
|
||||
let old_envelope_b64 = envelope_b64.clone();
|
||||
let new_envelope_b64 = BASE64_STANDARD.encode_to_string(&response.ciphertext);
|
||||
let mut overrides = HashMap::new();
|
||||
for (stored_name, stored_value) in metadata {
|
||||
let is_envelope_slot = REWRAP_ENVELOPE_HEADERS
|
||||
.iter()
|
||||
.any(|header| stored_name.eq_ignore_ascii_case(header));
|
||||
if is_envelope_slot && *stored_value == old_envelope_b64 {
|
||||
overrides.insert(stored_name.clone(), new_envelope_b64.clone());
|
||||
}
|
||||
}
|
||||
if overrides.is_empty() {
|
||||
return Err(SseError::internal(
|
||||
"rewrapped a data-key envelope but found no stored metadata copy to replace; refusing a write that would \
|
||||
leave the old wrapping live",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(ObjectDekRewrapOutcome::Rewrapped { metadata: overrides })
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Per-key KMS authorization on the SSE-KMS data path.
|
||||
|
||||
use crate::core::audit::{record_managed_kms_outcome, stored_envelope_master_key_version};
|
||||
use crate::core::request::SseKmsPrincipal;
|
||||
use crate::error::SseError;
|
||||
use crate::host::SseHost;
|
||||
use crate::{LOG_COMPONENT_STORAGE, LOG_SUBSYSTEM_SSE};
|
||||
use rustfs_config::ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY;
|
||||
use rustfs_policy::policy::action::KmsAction;
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use rustfs_utils::http::object_encryption_keys::{SSEType, stored_managed_encryption_key};
|
||||
use std::collections::HashMap;
|
||||
use tracing::debug;
|
||||
|
||||
/// Ask the authorizer that decides for `principal`: the host's, unless a test overrode it.
|
||||
async fn is_kms_key_allowed(
|
||||
host: &dyn SseHost,
|
||||
principal: &SseKmsPrincipal,
|
||||
action: KmsAction,
|
||||
key_id: &str,
|
||||
) -> Result<bool, SseError> {
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
if let Some(hooks) = principal.test_hooks.as_ref() {
|
||||
return hooks.authorizer.is_allowed(principal, action, key_id).await;
|
||||
}
|
||||
|
||||
host.kms_key_authorizer().is_allowed(principal, action, key_id).await
|
||||
}
|
||||
|
||||
/// Whether per-key KMS authorization is enforced on the SSE-KMS data path.
|
||||
fn sse_kms_key_policy_enforced(principal: Option<&SseKmsPrincipal>) -> bool {
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
if let Some(hooks) = principal.and_then(|candidate| candidate.test_hooks.as_ref()) {
|
||||
return hooks.enforced;
|
||||
}
|
||||
#[cfg(not(any(test, feature = "test-util")))]
|
||||
let _ = principal;
|
||||
|
||||
crate::startup::key_policy_enforced()
|
||||
}
|
||||
|
||||
/// The principal whose KMS key permissions this operation must satisfy, if any.
|
||||
///
|
||||
/// Scoping is limited to SSE-KMS, matching AWS: SSE-S3 wraps its data key with a
|
||||
/// server-owned key the caller never names, and SSE-C never reaches KMS at all.
|
||||
pub(crate) fn kms_authorization_subject(
|
||||
enforced: bool,
|
||||
principal: Option<&SseKmsPrincipal>,
|
||||
sse_type: SSEType,
|
||||
) -> Option<&SseKmsPrincipal> {
|
||||
if !enforced || !matches!(sse_type, SSEType::SseKms) {
|
||||
return None;
|
||||
}
|
||||
|
||||
principal
|
||||
}
|
||||
|
||||
/// Authorize `action` against `key_id` for the caller behind this SSE operation.
|
||||
///
|
||||
/// Runs before the key is used, so a denied request cannot distinguish an unauthorized
|
||||
/// key from a disabled or pending-deletion one.
|
||||
pub(crate) async fn authorize_sse_kms_key(
|
||||
host: &dyn SseHost,
|
||||
principal: Option<&SseKmsPrincipal>,
|
||||
sse_type: SSEType,
|
||||
action: KmsAction,
|
||||
key_id: &str,
|
||||
) -> Result<(), SseError> {
|
||||
let Some(principal) = kms_authorization_subject(sse_kms_key_policy_enforced(principal), principal, sse_type) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if is_kms_key_allowed(host, principal, action, key_id).await? {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
debug!(
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
event = "sse_kms_key_authorization_denied",
|
||||
account = %principal.account,
|
||||
action = ?action,
|
||||
"Principal is not authorized for the KMS key resolved for this request"
|
||||
);
|
||||
|
||||
// One warn per process, not per request: anonymous denials are driven by
|
||||
// unauthenticated traffic, so a per-request warn would let anyone flood the
|
||||
// log. Per-request detail stays on the audit entry and the debug event above.
|
||||
if principal.account.is_empty() {
|
||||
static ANONYMOUS_DENIAL_WARNED: std::sync::Once = std::sync::Once::new();
|
||||
ANONYMOUS_DENIAL_WARNED.call_once(|| {
|
||||
tracing::warn!(
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
event = "sse_kms_anonymous_key_authorization_denied",
|
||||
action = ?action,
|
||||
"Anonymous requests are being denied by SSE-KMS per-key authorization: anonymous \
|
||||
callers hold no kms grants, so a public bucket serving SSE-KMS objects is \
|
||||
incompatible with {ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY}=true. Reported once per \
|
||||
process; per-request denials are on audit entries and at debug level."
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Err(SseError {
|
||||
code: S3ErrorCode::AccessDenied,
|
||||
message: "Access Denied".to_string(),
|
||||
source: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Authorize `kms:Decrypt` for an object whose stored encryption material is unwrapped
|
||||
/// outside [`sse_decryption`].
|
||||
///
|
||||
/// The copy-source read resolves its material inside the object layer, which has no
|
||||
/// request identity, so the S3 layer has to run the check itself.
|
||||
pub async fn authorize_sse_kms_object_read(
|
||||
host: &dyn SseHost,
|
||||
principal: Option<&SseKmsPrincipal>,
|
||||
metadata: &HashMap<String, String>,
|
||||
) -> Result<(), SseError> {
|
||||
let Some((sse_type, key_id)) = stored_managed_encryption_key(metadata) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let result = authorize_sse_kms_key(host, principal, sse_type, KmsAction::DecryptAction, &key_id).await;
|
||||
// Only a denial is recorded here: an allowed read goes on to unwrap the key,
|
||||
// and that operation reports its own outcome.
|
||||
if let Err(error) = &result {
|
||||
record_managed_kms_outcome(
|
||||
principal,
|
||||
sse_type,
|
||||
Some(&key_id),
|
||||
|| stored_envelope_master_key_version(metadata),
|
||||
Err(error),
|
||||
);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Authorize the current request to write under the upload's stored KMS key.
|
||||
/// Upload IDs do not confer the creator's KMS permissions on another caller.
|
||||
pub async fn authorize_sse_kms_multipart_write(
|
||||
host: &dyn SseHost,
|
||||
principal: Option<&SseKmsPrincipal>,
|
||||
metadata: &HashMap<String, String>,
|
||||
) -> Result<(), SseError> {
|
||||
let Some((sse_type, key_id)) = stored_managed_encryption_key(metadata) else {
|
||||
return Ok(());
|
||||
};
|
||||
let result = authorize_sse_kms_key(host, principal, sse_type, KmsAction::GenerateDataKeyAction, &key_id).await;
|
||||
if let Err(error) = &result {
|
||||
record_managed_kms_outcome(
|
||||
principal,
|
||||
sse_type,
|
||||
Some(&key_id),
|
||||
|| stored_envelope_master_key_version(metadata),
|
||||
Err(error),
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -1,454 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! SSE request headers in, SSE response headers out.
|
||||
|
||||
use crate::core::keying::metadata::{normalize_encryption_metadata_case, recode_minio_kms_context, stored_ssec_metadata};
|
||||
use crate::core::s3::ssec::ssec_invalid_request;
|
||||
use crate::error::SseError;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use http::{HeaderMap, HeaderName, HeaderValue};
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use rustfs_utils::http::headers::{
|
||||
AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS, AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM,
|
||||
AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT,
|
||||
SSEC_ALGORITHM_HEADER, SSEC_KEY_MD5_HEADER,
|
||||
};
|
||||
use rustfs_utils::http::object_encryption_keys::{
|
||||
INTERNAL_ENCRYPTION_CONTEXT_HEADER, INTERNAL_ENCRYPTION_KEY_ID_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
|
||||
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER, SSEType,
|
||||
normalize_managed_metadata,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
// The same header names s3s publishes. Owned so this module does not import s3s.
|
||||
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION: HeaderName = HeaderName::from_static("x-amz-server-side-encryption");
|
||||
|
||||
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID: HeaderName =
|
||||
HeaderName::from_static("x-amz-server-side-encryption-aws-kms-key-id");
|
||||
|
||||
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT: HeaderName =
|
||||
HeaderName::from_static("x-amz-server-side-encryption-context");
|
||||
|
||||
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM: HeaderName =
|
||||
HeaderName::from_static("x-amz-server-side-encryption-customer-algorithm");
|
||||
|
||||
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5: HeaderName =
|
||||
HeaderName::from_static("x-amz-server-side-encryption-customer-key-md5");
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn sse_invalid_argument(message: &str) -> SseError {
|
||||
SseError {
|
||||
code: S3ErrorCode::InvalidArgument,
|
||||
message: message.to_string(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// SSE-C parameters extracted from headers (algorithm, key, key MD5).
|
||||
pub type SsecParamsFromHeaders = (Option<String>, Option<String>, Option<String>);
|
||||
|
||||
/// Extract SSE-C parameters from request headers.
|
||||
/// Used as fallback when the S3 layer does not populate them in the input struct.
|
||||
///
|
||||
/// Returns an error if an SSE-C header is present but cannot be parsed as valid UTF-8,
|
||||
/// ensuring malformed headers do not bypass validation.
|
||||
pub fn extract_ssec_params_from_headers(headers: &HeaderMap) -> Result<SsecParamsFromHeaders, SseError> {
|
||||
let algorithm = match headers.get("x-amz-server-side-encryption-customer-algorithm") {
|
||||
None => Ok(None),
|
||||
Some(v) => v
|
||||
.to_str()
|
||||
.map(|s| Some(s.to_string()))
|
||||
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption-customer-algorithm header must be valid UTF-8.")),
|
||||
}?;
|
||||
|
||||
let key = match headers.get("x-amz-server-side-encryption-customer-key") {
|
||||
None => Ok(None),
|
||||
Some(v) => v
|
||||
.to_str()
|
||||
.map(|s| Some(s.to_string()))
|
||||
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption-customer-key header must be valid UTF-8.")),
|
||||
}?;
|
||||
|
||||
let key_md5 = match headers.get("x-amz-server-side-encryption-customer-key-md5") {
|
||||
None => Ok(None),
|
||||
Some(v) => v
|
||||
.to_str()
|
||||
.map(|s| Some(s.to_string()))
|
||||
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption-customer-key-md5 header must be valid UTF-8.")),
|
||||
}?;
|
||||
|
||||
Ok((algorithm, key, key_md5))
|
||||
}
|
||||
|
||||
/// Extract x-amz-server-side-encryption from request headers.
|
||||
/// Used as fallback when the S3 layer does not populate it in the input struct.
|
||||
///
|
||||
/// Returns an error if the header is present but cannot be parsed as valid UTF-8,
|
||||
/// ensuring malformed headers do not bypass validation.
|
||||
pub fn extract_server_side_encryption_from_headers(headers: &HeaderMap) -> Result<Option<String>, SseError> {
|
||||
match headers.get("x-amz-server-side-encryption") {
|
||||
None => Ok(None),
|
||||
Some(v) => v
|
||||
.to_str()
|
||||
.map(|s| Some(s.to_string()))
|
||||
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption header must be valid UTF-8.")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_ssekms_context_from_headers(headers: &HeaderMap) -> Result<Option<HashMap<String, String>>, SseError> {
|
||||
let Some(v) = headers.get(AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let value = v
|
||||
.to_str()
|
||||
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption-context header must be valid UTF-8."))?;
|
||||
let decoded = BASE64_STANDARD.decode_to_vec(value).map_err(|_| {
|
||||
sse_invalid_argument("The x-amz-server-side-encryption-context header must be valid base64-encoded JSON.")
|
||||
})?;
|
||||
|
||||
serde_json::from_slice(&decoded).map(Some).map_err(|_| {
|
||||
sse_invalid_argument("The x-amz-server-side-encryption-context header must be a base64-encoded JSON object.")
|
||||
})
|
||||
}
|
||||
|
||||
/// Rejects a client encryption context that would replace the location binding.
|
||||
///
|
||||
/// The request context binds the data key to `{bucket: bucket/key}` only when the
|
||||
/// client supplied no entry under that name, and only the client context is
|
||||
/// persisted. A client entry keyed by the bucket name therefore travels with the
|
||||
/// object and replaces the binding on every read, so the envelope would no longer
|
||||
/// be tied to the object's location. Only the write side rejects it: objects stored
|
||||
/// with such an entry stay readable because the read side rebuilds the context
|
||||
/// unchanged.
|
||||
pub(crate) fn reject_kms_context_location_override(
|
||||
bucket: &str,
|
||||
ssekms_context: Option<&HashMap<String, String>>,
|
||||
) -> Result<(), SseError> {
|
||||
if ssekms_context.is_some_and(|context| context.contains_key(bucket)) {
|
||||
return Err(sse_invalid_argument(&format!(
|
||||
"The x-amz-server-side-encryption-context header contains the key \"{bucket}\", which equals the bucket name; \
|
||||
that key is reserved for binding the data key to the object's location."
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn validate_sse_headers_for_write(
|
||||
server_side_encryption: Option<&str>,
|
||||
ssekms_key_id: Option<&String>,
|
||||
ssekms_context: Option<&HashMap<String, String>>,
|
||||
sse_customer_algorithm: Option<&String>,
|
||||
sse_customer_key: Option<&String>,
|
||||
sse_customer_key_md5: Option<&String>,
|
||||
require_sse_customer_key: bool,
|
||||
) -> Result<(), SseError> {
|
||||
if let Some(sse) = server_side_encryption {
|
||||
let s = sse;
|
||||
if s != AMZ_ENCRYPTION_AES && s != AMZ_ENCRYPTION_KMS {
|
||||
return Err(sse_invalid_argument(
|
||||
"The SSE algorithm specified is not supported. The valid values are AES256 or aws:kms.",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let has_ssec_headers = sse_customer_algorithm.is_some() || sse_customer_key.is_some() || sse_customer_key_md5.is_some();
|
||||
let has_managed_headers = server_side_encryption.is_some() || ssekms_key_id.is_some() || ssekms_context.is_some();
|
||||
|
||||
if has_ssec_headers {
|
||||
if has_managed_headers {
|
||||
return Err(sse_invalid_argument(
|
||||
"The SSE-C and managed server-side encryption headers cannot be used together.",
|
||||
));
|
||||
}
|
||||
|
||||
let has_valid_ssec_headers = if require_sse_customer_key {
|
||||
matches!(
|
||||
(sse_customer_algorithm, sse_customer_key, sse_customer_key_md5),
|
||||
(Some(_), Some(_), Some(_))
|
||||
)
|
||||
} else {
|
||||
matches!((sse_customer_algorithm, sse_customer_key_md5), (Some(_), Some(_)))
|
||||
};
|
||||
|
||||
if !has_valid_ssec_headers {
|
||||
let message = if require_sse_customer_key {
|
||||
"Missing SSE-C parameters. Algorithm, customer key and customer key MD5 are all required."
|
||||
} else {
|
||||
"Missing SSE-C parameters. Algorithm and customer key MD5 are required."
|
||||
};
|
||||
|
||||
return Err(ssec_invalid_request(message));
|
||||
}
|
||||
}
|
||||
|
||||
if ssekms_key_id.is_some() && server_side_encryption.is_none_or(|sse| sse != AMZ_ENCRYPTION_KMS) {
|
||||
return Err(sse_invalid_argument(
|
||||
"The SSE-KMS key ID header can only be used when x-amz-server-side-encryption is set to aws:kms.",
|
||||
));
|
||||
}
|
||||
|
||||
if ssekms_context.is_some() && server_side_encryption.is_none_or(|sse| sse != AMZ_ENCRYPTION_KMS) {
|
||||
return Err(sse_invalid_argument(
|
||||
"The SSE-KMS context header can only be used when x-amz-server-side-encryption is set to aws:kms.",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn validate_sse_headers_for_read(metadata: &HashMap<String, String>, headers: &HeaderMap) -> Result<(), SseError> {
|
||||
let has_req_ssec = headers.contains_key("x-amz-server-side-encryption-customer-algorithm")
|
||||
|| headers.contains_key("x-amz-server-side-encryption-customer-key")
|
||||
|| headers.contains_key("x-amz-server-side-encryption-customer-key-md5");
|
||||
|
||||
let has_req_sse = headers.contains_key("x-amz-server-side-encryption")
|
||||
|| headers.contains_key("x-amz-server-side-encryption-aws-kms-key-id")
|
||||
|| headers.contains_key("x-amz-server-side-encryption-context");
|
||||
|
||||
let is_object_ssec = stored_ssec_metadata(metadata);
|
||||
let is_object_sse = metadata.contains_key("x-amz-server-side-encryption");
|
||||
|
||||
if is_object_ssec {
|
||||
if has_req_sse {
|
||||
return Err(sse_invalid_argument(
|
||||
"Server-side encryption headers cannot be used with an object encrypted using SSE-C.",
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if is_object_sse && has_req_ssec {
|
||||
return Err(sse_invalid_argument(
|
||||
"SSE-C headers cannot be used with an object encrypted using server-side managed encryption.",
|
||||
));
|
||||
}
|
||||
|
||||
if has_req_ssec {
|
||||
return Err(ssec_invalid_request(
|
||||
"The object was stored without SSE-C. The correct SSE-C parameters must not be provided.",
|
||||
));
|
||||
}
|
||||
|
||||
if has_req_sse {
|
||||
return Err(sse_invalid_argument(
|
||||
"The object is not encrypted with server-side encryption. Do not provide server-side encryption headers.",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The public `x-amz-server-side-encryption` value a managed scheme reports.
|
||||
pub(crate) fn managed_sse_public_header(sse_type: SSEType) -> &'static str {
|
||||
match sse_type {
|
||||
SSEType::SseKms => AMZ_ENCRYPTION_KMS,
|
||||
// SSE-C never reaches the managed path; reporting AES256 keeps this
|
||||
// total without inventing a third public value.
|
||||
SSEType::SseS3 | SSEType::SseC => AMZ_ENCRYPTION_AES,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_ssec_read_headers(algorithm: Option<&String>, key: Option<&String>, key_md5: Option<&String>) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
if let Some(algorithm) = algorithm
|
||||
&& let Ok(mut value) = HeaderValue::from_str(algorithm.as_str())
|
||||
{
|
||||
value.set_sensitive(true);
|
||||
headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, value);
|
||||
}
|
||||
|
||||
if let Some(key) = key
|
||||
&& let Ok(mut value) = HeaderValue::from_str(key.as_str())
|
||||
{
|
||||
value.set_sensitive(true);
|
||||
headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, value);
|
||||
}
|
||||
|
||||
if let Some(key_md5) = key_md5
|
||||
&& let Ok(mut value) = HeaderValue::from_str(key_md5.as_str())
|
||||
{
|
||||
value.set_sensitive(true);
|
||||
headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, value);
|
||||
}
|
||||
|
||||
headers
|
||||
}
|
||||
|
||||
/// Response headers derived for a decrypted read without unwrapping the data key.
|
||||
#[derive(Debug)]
|
||||
pub struct SseReadResponseHeaders {
|
||||
pub server_side_encryption: String,
|
||||
pub sse_customer_algorithm: Option<String>,
|
||||
pub sse_customer_key_md5: Option<String>,
|
||||
pub ssekms_key_id: Option<String>,
|
||||
}
|
||||
|
||||
fn invalid_sse_response_metadata() -> SseError {
|
||||
SseError {
|
||||
code: S3ErrorCode::InternalError,
|
||||
message: "Persisted object encryption metadata is invalid.".to_string(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_sse_response_header(headers: &mut HeaderMap, name: HeaderName, value: &str) -> Result<(), SseError> {
|
||||
let value = HeaderValue::from_str(value).map_err(|_| invalid_sse_response_metadata())?;
|
||||
headers.insert(name, value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Project response headers after the caller has completed its existing read
|
||||
/// validation and KMS authorization path.
|
||||
pub fn project_sse_read_response_headers(
|
||||
metadata: &HashMap<String, String>,
|
||||
sse_customer_algorithm: Option<&String>,
|
||||
sse_customer_key_md5: Option<&String>,
|
||||
) -> Result<HeaderMap, SseError> {
|
||||
if metadata.keys().any(|key| {
|
||||
key.eq_ignore_ascii_case(AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY)
|
||||
|| key.eq_ignore_ascii_case(AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT)
|
||||
}) {
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
|
||||
let metadata = normalize_encryption_metadata_case(metadata).map_err(|_| invalid_sse_response_metadata())?;
|
||||
let public_mode = metadata.get("x-amz-server-side-encryption").map(String::as_str);
|
||||
let customer_algorithm = metadata.get(SSEC_ALGORITHM_HEADER).map(String::as_str);
|
||||
|
||||
let public_mode = match public_mode {
|
||||
Some(AMZ_ENCRYPTION_AES) => Some(SSEType::SseS3),
|
||||
Some(AMZ_ENCRYPTION_KMS) => Some(SSEType::SseKms),
|
||||
Some(_) => return Err(invalid_sse_response_metadata()),
|
||||
None => None,
|
||||
};
|
||||
if customer_algorithm.is_some_and(|algorithm| algorithm != AMZ_ENCRYPTION_AES) {
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
|
||||
let mode = if customer_algorithm.is_some() {
|
||||
if public_mode == Some(SSEType::SseKms) {
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
Some(SSEType::SseC)
|
||||
} else {
|
||||
public_mode
|
||||
};
|
||||
for marker_mode in [
|
||||
metadata
|
||||
.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)
|
||||
.then_some(SSEType::SseC),
|
||||
metadata
|
||||
.contains_key(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER)
|
||||
.then_some(SSEType::SseS3),
|
||||
metadata
|
||||
.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER)
|
||||
.then_some(SSEType::SseKms),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if mode != Some(marker_mode) {
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
}
|
||||
let Some(mode) = mode else {
|
||||
if metadata
|
||||
.keys()
|
||||
.any(|key| rustfs_utils::http::is_object_encryption_marker(key))
|
||||
{
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
return Ok(HeaderMap::new());
|
||||
};
|
||||
|
||||
let mut key_id = None;
|
||||
for value in [
|
||||
metadata.get("x-amz-server-side-encryption-aws-kms-key-id"),
|
||||
metadata.get(INTERNAL_ENCRYPTION_KEY_ID_HEADER),
|
||||
metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if key_id.is_some_and(|current| current != value) {
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
key_id = Some(value);
|
||||
}
|
||||
|
||||
let normalized_managed = normalize_managed_metadata(metadata.as_ref(), Some(recode_minio_kms_context));
|
||||
let mut response_headers = HeaderMap::with_capacity(3);
|
||||
match mode {
|
||||
SSEType::SseS3 => {
|
||||
if metadata.contains_key("x-amz-server-side-encryption-aws-kms-key-id") || metadata.contains_key(SSEC_KEY_MD5_HEADER)
|
||||
{
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
response_headers.insert(X_AMZ_SERVER_SIDE_ENCRYPTION, HeaderValue::from_static(AMZ_ENCRYPTION_AES));
|
||||
}
|
||||
SSEType::SseKms => {
|
||||
if metadata.contains_key(SSEC_KEY_MD5_HEADER) {
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
let key_id = key_id
|
||||
.map(String::as_str)
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(invalid_sse_response_metadata)?;
|
||||
response_headers.insert(X_AMZ_SERVER_SIDE_ENCRYPTION, HeaderValue::from_static(AMZ_ENCRYPTION_KMS));
|
||||
insert_sse_response_header(&mut response_headers, X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID, key_id)?;
|
||||
|
||||
if metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER)
|
||||
&& !normalized_managed.contains_key(INTERNAL_ENCRYPTION_CONTEXT_HEADER)
|
||||
{
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
if let Some(context) = normalized_managed.get(INTERNAL_ENCRYPTION_CONTEXT_HEADER) {
|
||||
serde_json::from_str::<HashMap<String, String>>(context).map_err(|_| invalid_sse_response_metadata())?;
|
||||
let encoded = BASE64_STANDARD.encode_to_string(context);
|
||||
insert_sse_response_header(&mut response_headers, X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT, &encoded)?;
|
||||
}
|
||||
}
|
||||
SSEType::SseC => {
|
||||
if key_id.is_some() || normalized_managed.contains_key(INTERNAL_ENCRYPTION_CONTEXT_HEADER) {
|
||||
return Err(invalid_sse_response_metadata());
|
||||
}
|
||||
let algorithm = sse_customer_algorithm
|
||||
.map(|value| value.as_ref())
|
||||
.filter(|value| *value == AMZ_ENCRYPTION_AES)
|
||||
.ok_or_else(|| {
|
||||
ssec_invalid_request(
|
||||
"The object was stored using a form of Server Side Encryption. The correct parameters must be provided to retrieve the object.",
|
||||
)
|
||||
})?;
|
||||
let key_md5 = sse_customer_key_md5
|
||||
.map(|value| value.as_ref())
|
||||
.ok_or_else(|| ssec_invalid_request("Missing SSE-C customer key MD5."))?;
|
||||
let stored_md5 = metadata.get(SSEC_KEY_MD5_HEADER).ok_or_else(invalid_sse_response_metadata)?;
|
||||
if stored_md5 != key_md5 {
|
||||
return Err(ssec_invalid_request(
|
||||
"The provided encryption parameters did not match the ones used originally to encrypt the object.",
|
||||
));
|
||||
}
|
||||
insert_sse_response_header(&mut response_headers, X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, algorithm)?;
|
||||
insert_sse_response_header(&mut response_headers, X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, key_md5)?;
|
||||
}
|
||||
}
|
||||
Ok(response_headers)
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The schemes S3 defines: SSE-S3, SSE-KMS and SSE-C, as a request names them and a response reports them.
|
||||
|
||||
pub(crate) mod authorization;
|
||||
pub(crate) mod headers;
|
||||
pub(crate) mod scheme;
|
||||
pub(crate) mod ssec;
|
||||
@@ -1,288 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! 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";
|
||||
|
||||
pub(crate) const SUPPORT_SSE_ALGORITHMS: &[&str] = &[DEFAULT_SSE_ALGORITHM];
|
||||
|
||||
/// SSE configuration resolved from request and bucket defaults
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SseConfiguration {
|
||||
/// Effective server-side encryption algorithm (after considering bucket defaults)
|
||||
pub effective_sse: String,
|
||||
/// Effective KMS key ID (after considering bucket defaults)
|
||||
pub effective_kms_key_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Managed SSE resolved from a bucket default encryption rule on a write path.
|
||||
///
|
||||
/// The single mapping shared by every writer: the resolver in this crate, and
|
||||
/// the server's PUT, COPY and extract paths. Unknown algorithms fall back to AES256 rather
|
||||
/// than to `None`. Resolving `None` instead lets a same-name copy under a
|
||||
/// malformed bucket default pass the `copy_changes_encryption` guard and take
|
||||
/// the metadata-only shortcut while this layer still encrypts: fresh DEK
|
||||
/// metadata is committed beside the untouched plaintext blocks and the object
|
||||
/// becomes unreadable. PutBucketEncryption refuses unknown algorithms, so this
|
||||
/// is reachable only through a configuration stored before that check or
|
||||
/// through hand-edited bucket metadata (backlog#1826).
|
||||
pub fn bucket_default_write_sse(sse_algorithm: &str) -> String {
|
||||
match sse_algorithm {
|
||||
"AES256" => String::from(AMZ_ENCRYPTION_AES),
|
||||
"aws:kms" => String::from(AMZ_ENCRYPTION_KMS),
|
||||
_ => String::from(AMZ_ENCRYPTION_AES),
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare SSE configuration by resolving request parameters with bucket defaults
|
||||
///
|
||||
/// This function:
|
||||
/// 1. Queries bucket default encryption configuration
|
||||
/// 2. Resolves effective encryption (request overrides bucket default)
|
||||
/// 3. Prepares metadata headers for managed SSE
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `bucket` - Bucket name
|
||||
/// * `server_side_encryption` - SSE algorithm from request (SSE-S3 or SSE-KMS)
|
||||
/// * `ssekms_key_id` - KMS key ID from request
|
||||
/// * `sse_customer_algorithm` - SSE-C algorithm from request
|
||||
///
|
||||
/// # Returns
|
||||
/// `SseConfiguration` with resolved encryption parameters and metadata headers
|
||||
pub(crate) async fn prepare_sse_configuration(
|
||||
host: &dyn SseHost,
|
||||
bucket: &str,
|
||||
server_side_encryption: Option<String>,
|
||||
ssekms_key_id: Option<String>,
|
||||
) -> Result<Option<SseConfiguration>, SseError> {
|
||||
if let Some(server_side_encryption) = server_side_encryption.clone()
|
||||
&& server_side_encryption.as_str() == AMZ_ENCRYPTION_AES
|
||||
{
|
||||
return Ok(Some(SseConfiguration {
|
||||
effective_sse: server_side_encryption,
|
||||
effective_kms_key_id: None,
|
||||
}));
|
||||
}
|
||||
|
||||
if let Some(server_side_encryption) = server_side_encryption.clone()
|
||||
&& let Some(ssekms_key_id) = ssekms_key_id
|
||||
{
|
||||
return Ok(Some(SseConfiguration {
|
||||
effective_sse: server_side_encryption,
|
||||
effective_kms_key_id: Some(ssekms_key_id),
|
||||
}));
|
||||
}
|
||||
|
||||
// Get bucket default encryption configuration.
|
||||
let bucket_encryption = host.bucket_encryption(bucket).await;
|
||||
debug!(
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
event = "bucket_sse_config_lookup",
|
||||
bucket = %bucket,
|
||||
found = matches!(bucket_encryption, Ok(Some(_))),
|
||||
"Bucket SSE configuration lookup completed"
|
||||
);
|
||||
|
||||
let Some(bucket_encryption) = bucket_encryption? else {
|
||||
// The bucket has no SSE config. If the user explicitly requested
|
||||
// aws:kms, we must honor that — return the explicit SSE header so
|
||||
// downstream logic can try (and fail if KMS is unavailable).
|
||||
return Ok(server_side_encryption.map(|sse| SseConfiguration {
|
||||
effective_sse: sse,
|
||||
effective_kms_key_id: ssekms_key_id,
|
||||
}));
|
||||
};
|
||||
|
||||
let default_rule = bucket_encryption.default_rule.as_ref();
|
||||
let effective_sse = server_side_encryption.clone().or_else(|| {
|
||||
default_rule.map(|sse| {
|
||||
debug!(
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
event = "bucket_sse_default_applied",
|
||||
bucket = %bucket,
|
||||
algorithm = sse.sse_algorithm.as_str(),
|
||||
has_kms_key_id = sse.kms_master_key_id.is_some(),
|
||||
"Bucket SSE default resolved"
|
||||
);
|
||||
bucket_default_write_sse(&sse.sse_algorithm)
|
||||
})
|
||||
});
|
||||
let Some(effective_sse) = effective_sse else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
debug!(
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
event = "effective_sse_resolved",
|
||||
bucket = %bucket,
|
||||
requested = ?server_side_encryption,
|
||||
effective = ?effective_sse,
|
||||
"Resolved effective SSE configuration"
|
||||
);
|
||||
|
||||
let effective_kms_key_id = resolve_effective_kms_key_id(Some(&effective_sse), ssekms_key_id, || {
|
||||
default_rule.and_then(|sse| sse.kms_master_key_id.clone())
|
||||
});
|
||||
|
||||
Ok(Some(SseConfiguration {
|
||||
effective_sse,
|
||||
effective_kms_key_id,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_effective_kms_key_id<F>(
|
||||
effective_sse: Option<&str>,
|
||||
requested_kms_key_id: Option<String>,
|
||||
bucket_default_kms_key_id: F,
|
||||
) -> Option<String>
|
||||
where
|
||||
F: FnOnce() -> Option<String>,
|
||||
{
|
||||
if effective_sse.is_none_or(|sse| sse != AMZ_ENCRYPTION_KMS) {
|
||||
return requested_kms_key_id;
|
||||
}
|
||||
|
||||
requested_kms_key_id.or_else(bucket_default_kms_key_id)
|
||||
}
|
||||
|
||||
/// The SSE headers of a write request, as the S3 layer received them.
|
||||
pub(crate) struct WriteSchemeHeaders<'a> {
|
||||
pub(crate) server_side_encryption: Option<String>,
|
||||
pub(crate) ssekms_key_id: Option<String>,
|
||||
pub(crate) ssekms_context: Option<&'a HashMap<String, String>>,
|
||||
pub(crate) sse_customer_algorithm: Option<String>,
|
||||
pub(crate) sse_customer_key: Option<String>,
|
||||
pub(crate) sse_customer_key_md5: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<String> },
|
||||
/// 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(..)",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
headers: WriteSchemeHeaders<'_>,
|
||||
) -> Result<Option<WriteScheme>, 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)
|
||||
{
|
||||
return Ok(Some(WriteScheme::SseC { algorithm, key, key_md5 }));
|
||||
}
|
||||
|
||||
let Some(config) = prepare_sse_configuration(host, bucket, headers.server_side_encryption, headers.ssekms_key_id).await?
|
||||
else {
|
||||
return 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
|
||||
/// encryption and decryption paths do.
|
||||
pub(crate) fn managed_sse_type(server_side_encryption: &str) -> SSEType {
|
||||
match server_side_encryption {
|
||||
AMZ_ENCRYPTION_KMS => SSEType::SseKms,
|
||||
_ => SSEType::SseS3,
|
||||
}
|
||||
}
|
||||
|
||||
/// Key id an SSE-KMS read authorizes and reports when the stored metadata
|
||||
/// carries none (legacy envelopes and MinIO-written objects predate the
|
||||
/// explicit key-id headers).
|
||||
///
|
||||
/// The KMS service's configured default key is the key such envelopes were
|
||||
/// actually wrapped under, so per-key authorization must target it — the bare
|
||||
/// literal `default` would silently escape any policy narrowed to real key
|
||||
/// ids. The literal remains only as the last resort when no service is
|
||||
/// running, matching what the legacy write path recorded implicitly.
|
||||
pub(crate) async fn resolve_stored_kms_key_id(host: &dyn SseHost, stored: Option<String>) -> String {
|
||||
if let Some(key_id) = stored {
|
||||
return key_id;
|
||||
}
|
||||
if let Some(service) = host.encryption_service().await
|
||||
&& let Some(key_id) = service.get_default_key_id()
|
||||
{
|
||||
return key_id.clone();
|
||||
}
|
||||
"default".to_string()
|
||||
}
|
||||
|
||||
/// Check if the server_side_encryption is a managed SSE type (SSE-S3 or SSE-KMS)
|
||||
#[inline]
|
||||
pub(crate) fn is_managed_sse(server_side_encryption: &str) -> bool {
|
||||
matches!(server_side_encryption, "AES256" | "aws:kms")
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! SSE-C: validating the customer-provided key and matching it against the stored object.
|
||||
|
||||
use crate::core::keying::metadata::{minio_sealed_ssec_metadata, stored_ssec_metadata};
|
||||
use crate::core::s3::scheme::{DEFAULT_SSE_ALGORITHM, SUPPORT_SSE_ALGORITHMS};
|
||||
use crate::error::SseError;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use md5::{Digest as Md5Digest, Md5};
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use std::collections::HashMap;
|
||||
use tracing::error;
|
||||
|
||||
fn md5_bytes(input: impl AsRef<[u8]>) -> [u8; 16] {
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(input.as_ref());
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
pub(crate) fn md5_base64(input: impl AsRef<[u8]>) -> String {
|
||||
BASE64_STANDARD.encode_to_string(md5_bytes(input))
|
||||
}
|
||||
|
||||
/// Validated SSE-C parameters
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct ValidatedSsecParams {
|
||||
/// Encryption algorithm (always "AES256" for SSE-C)
|
||||
pub algorithm: String,
|
||||
/// Decoded encryption key bytes (32 bytes for AES-256)
|
||||
pub key_bytes: [u8; 32],
|
||||
/// Base64-encoded MD5 of the key
|
||||
pub key_md5: String,
|
||||
}
|
||||
|
||||
/// SSE-C parameters from client request
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct SsecParams {
|
||||
/// Encryption algorithm
|
||||
pub algorithm: String,
|
||||
/// Base64-encoded encryption key
|
||||
pub key: String,
|
||||
/// Base64-encoded MD5 of the key
|
||||
pub key_md5: String,
|
||||
}
|
||||
|
||||
/// Validate SSE-C parameters from client request
|
||||
///
|
||||
/// Validates:
|
||||
/// 1. Algorithm is "AES256"
|
||||
/// 2. Key is valid Base64 and exactly 32 bytes
|
||||
/// 3. MD5 hash matches the key
|
||||
///
|
||||
/// # Returns
|
||||
/// `ValidatedSsecParams` with decoded key bytes
|
||||
pub(crate) fn validate_ssec_params(params: SsecParams) -> Result<ValidatedSsecParams, SseError> {
|
||||
if !SUPPORT_SSE_ALGORITHMS.contains(¶ms.algorithm.as_str()) {
|
||||
return Err(ssec_invalid_request(&format!(
|
||||
"Unsupported SSE-C algorithm. Only {DEFAULT_SSE_ALGORITHM} is supported."
|
||||
)));
|
||||
}
|
||||
|
||||
let key_bytes = BASE64_STANDARD.decode_to_vec(¶ms.key).map_err(|e| {
|
||||
error!("Failed to decode SSE-C key: {}", e);
|
||||
ssec_invalid_request("Invalid SSE-C key: not valid Base64.")
|
||||
})?;
|
||||
|
||||
if key_bytes.len() != 32 {
|
||||
return Err(ssec_invalid_request(&format!(
|
||||
"SSE-C key must be 32 bytes (256 bits), got {} bytes.",
|
||||
key_bytes.len()
|
||||
)));
|
||||
}
|
||||
|
||||
let computed_md5 = md5_base64(&key_bytes);
|
||||
if computed_md5 != params.key_md5 {
|
||||
return Err(ssec_invalid_request(
|
||||
"The calculated MD5 hash of the key did not match the hash that was provided.",
|
||||
));
|
||||
}
|
||||
|
||||
let key_array: [u8; 32] = key_bytes
|
||||
.try_into()
|
||||
.map_err(|_| ssec_invalid_request("SSE-C key must be exactly 32 bytes."))?;
|
||||
|
||||
Ok(ValidatedSsecParams {
|
||||
algorithm: params.algorithm,
|
||||
key_bytes: key_array,
|
||||
key_md5: params.key_md5,
|
||||
})
|
||||
}
|
||||
|
||||
/// Verify SSE-C key matches the stored metadata.
|
||||
///
|
||||
/// Used during GetObject/HeadObject to ensure the client provided the correct key.
|
||||
/// Returns 400 InvalidRequest on mismatch, consistent with AWS S3 behavior.
|
||||
pub(crate) fn verify_ssec_key_match(
|
||||
provided_md5: &str,
|
||||
stored_md5: Option<&String>,
|
||||
minio_sealed_ssec: bool,
|
||||
) -> Result<(), SseError> {
|
||||
match stored_md5 {
|
||||
Some(stored) if stored == provided_md5 => Ok(()),
|
||||
Some(_) => Err(ssec_invalid_request(
|
||||
"The provided encryption parameters did not match the ones used originally to encrypt the object.",
|
||||
)),
|
||||
// MinIO never persists the customer-key MD5, so this early check has
|
||||
// nothing to compare against on a migrated object. The key itself is
|
||||
// still proven: a wrong key fails the AEAD unseal of the sealed object
|
||||
// key. The check exists only for the friendlier early error, so its
|
||||
// absence is tolerated for exactly that shape and no other.
|
||||
None if minio_sealed_ssec => Ok(()),
|
||||
None => Err(ssec_invalid_request("Object has no stored SSE-C key metadata.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Algorithm an SSE-C object recorded; objects that recorded none were written as `AES256`.
|
||||
pub(crate) fn stored_ssec_algorithm(metadata: &HashMap<String, String>) -> &str {
|
||||
metadata
|
||||
.get("x-amz-server-side-encryption-customer-algorithm")
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("AES256")
|
||||
}
|
||||
|
||||
/// The customer key and MD5 of a read of an SSE-C object, once both are present and
|
||||
/// the MD5 matches what the object recorded.
|
||||
///
|
||||
/// The key itself is not validated here; the caller does that next, so a request
|
||||
/// that names the wrong key learns of the mismatch before anything else.
|
||||
pub(crate) fn require_matching_ssec_key<'r>(
|
||||
metadata: &HashMap<String, String>,
|
||||
sse_customer_key: Option<&'r String>,
|
||||
sse_customer_key_md5: Option<&'r String>,
|
||||
) -> Result<(&'r String, &'r String), SseError> {
|
||||
let (key, key_md5) = match (sse_customer_key, sse_customer_key_md5) {
|
||||
(Some(k), Some(md5)) => (k, md5),
|
||||
_ => {
|
||||
return Err(ssec_invalid_request(
|
||||
"The object was stored using a form of Server Side Encryption. \
|
||||
The correct parameters must be provided to retrieve the object.",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Verify that the provided key MD5 matches the stored MD5 for security
|
||||
let stored_md5 = metadata.get("x-amz-server-side-encryption-customer-key-md5");
|
||||
verify_ssec_key_match(key_md5, stored_md5, minio_sealed_ssec_metadata(metadata))?;
|
||||
|
||||
Ok((key, key_md5))
|
||||
}
|
||||
|
||||
/// Validate that the SSE-C headers required for reading an SSE-C encrypted object
|
||||
/// are present in the request. This is used by HeadObject which does not decrypt
|
||||
/// the data but still must verify the caller holds the correct key.
|
||||
///
|
||||
/// Performs full validation: decodes the customer key, recomputes its MD5,
|
||||
/// verifies the client-provided MD5 header matches the key, then compares
|
||||
/// the computed MD5 against the stored metadata. This prevents a client from
|
||||
/// bypassing validation by guessing/obtaining only the stored MD5 without
|
||||
/// possessing the actual encryption key.
|
||||
///
|
||||
/// Returns `Ok(())` if either the object is not SSE-C encrypted, or valid SSE-C
|
||||
/// headers are provided and the key matches. Returns 400 InvalidRequest otherwise.
|
||||
pub fn validate_ssec_for_read(
|
||||
metadata: &HashMap<String, String>,
|
||||
sse_customer_key: Option<&String>,
|
||||
sse_customer_key_md5: Option<&String>,
|
||||
) -> Result<(), SseError> {
|
||||
if !stored_ssec_metadata(metadata) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let (key, key_md5) = match (sse_customer_key, sse_customer_key_md5) {
|
||||
(Some(k), Some(md5)) => (k, md5),
|
||||
_ => {
|
||||
return Err(ssec_invalid_request(
|
||||
"The object was stored using a form of Server Side Encryption. \
|
||||
The correct parameters must be provided to retrieve the object.",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Full param validation: decode key, verify 32 bytes, recompute MD5
|
||||
// from actual key bytes and compare to the client-provided MD5 header.
|
||||
let algorithm = metadata
|
||||
.get("x-amz-server-side-encryption-customer-algorithm")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| DEFAULT_SSE_ALGORITHM.to_string());
|
||||
let validated = validate_ssec_params(SsecParams {
|
||||
algorithm,
|
||||
key: key.to_string(),
|
||||
key_md5: key_md5.clone(),
|
||||
})?;
|
||||
|
||||
let stored_md5 = metadata.get("x-amz-server-side-encryption-customer-key-md5");
|
||||
verify_ssec_key_match(&validated.key_md5, stored_md5, minio_sealed_ssec_metadata(metadata))
|
||||
}
|
||||
|
||||
/// Build an `SseError` with `InvalidRequest` (HTTP 400) for SSE-C related errors.
|
||||
pub fn ssec_invalid_request(message: &str) -> SseError {
|
||||
SseError {
|
||||
code: S3ErrorCode::InvalidRequest,
|
||||
message: message.to_string(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
@@ -1,550 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Write entry points: resolve the encryption material for a new object or multipart upload.
|
||||
|
||||
use crate::core::audit::{envelope_master_key_version, record_managed_kms_outcome};
|
||||
use crate::core::keying::context::build_object_encryption_context;
|
||||
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::reject_kms_context_location_override;
|
||||
use crate::core::s3::scheme::{
|
||||
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;
|
||||
use rustfs_kms::KmsUnavailableError;
|
||||
use rustfs_policy::policy::action::KmsAction;
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use rustfs_utils::http::headers::{AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS};
|
||||
use rustfs_utils::http::object_encryption_keys::SSEType;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Request parameters for unified encryption
|
||||
#[derive(Clone)]
|
||||
pub struct EncryptionRequest<'a> {
|
||||
/// Bucket name
|
||||
pub bucket: &'a str,
|
||||
/// Object key
|
||||
pub key: &'a str,
|
||||
/// Server-side encryption algorithm (SSE-S3 or SSE-KMS)
|
||||
pub server_side_encryption: Option<String>,
|
||||
/// KMS key ID (for SSE-KMS)
|
||||
pub ssekms_key_id: Option<String>,
|
||||
/// Optional client-provided KMS context for SSE-KMS.
|
||||
pub ssekms_context: Option<HashMap<String, String>>,
|
||||
/// SSE-C algorithm (customer-provided key)
|
||||
pub sse_customer_algorithm: Option<String>,
|
||||
/// SSE-C key (Base64-encoded)
|
||||
pub sse_customer_key: Option<String>,
|
||||
/// SSE-C key MD5 (Base64-encoded)
|
||||
pub sse_customer_key_md5: Option<String>,
|
||||
/// Content size (for metadata)
|
||||
pub content_size: i64,
|
||||
/// Caller the SSE-KMS key usage is authorized as. `None` marks an internal caller.
|
||||
pub principal: Option<&'a SseKmsPrincipal>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EncryptionRequest<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EncryptionRequest")
|
||||
.field("server_side_encryption", &self.server_side_encryption)
|
||||
.field("content_size", &self.content_size)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl EncryptionRequest<'_> {
|
||||
pub fn validate_complete_multipart_ssec(&self, user_defined: &HashMap<String, String>) -> Result<(), SseError> {
|
||||
let request_uses_ssec =
|
||||
self.sse_customer_algorithm.is_some() || self.sse_customer_key.is_some() || self.sse_customer_key_md5.is_some();
|
||||
if !request_uses_ssec {
|
||||
let stored_algorithm = user_defined.get("x-amz-server-side-encryption-customer-algorithm");
|
||||
let stored_key_md5 = user_defined.get("x-amz-server-side-encryption-customer-key-md5");
|
||||
return match (stored_algorithm, stored_key_md5) {
|
||||
(None, None) => Ok(()),
|
||||
(Some(algorithm), Some(key_md5))
|
||||
if algorithm == DEFAULT_SSE_ALGORITHM
|
||||
&& BASE64_STANDARD
|
||||
.decode_to_vec(key_md5)
|
||||
.is_ok_and(|decoded| decoded.len() == 16) =>
|
||||
{
|
||||
if rustfs_utils::http::contains_key_str(user_defined, rustfs_utils::http::SUFFIX_PLAINTEXT_CHECKSUM) {
|
||||
return Err(ssec_invalid_request(
|
||||
"SSE-C multipart uploads with additional checksums require the customer key for completion.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(ssec_invalid_request("The multipart upload contains invalid SSE-C metadata.")),
|
||||
};
|
||||
}
|
||||
self.validate_multipart_ssec(user_defined)
|
||||
}
|
||||
|
||||
pub fn validate_multipart_ssec(&self, user_defined: &HashMap<String, String>) -> Result<(), SseError> {
|
||||
let stored_algorithm = user_defined.get("x-amz-server-side-encryption-customer-algorithm");
|
||||
let stored_key_md5 = user_defined.get("x-amz-server-side-encryption-customer-key-md5");
|
||||
let session_uses_ssec = stored_algorithm.is_some() || stored_key_md5.is_some();
|
||||
let request_uses_ssec =
|
||||
self.sse_customer_algorithm.is_some() || self.sse_customer_key.is_some() || self.sse_customer_key_md5.is_some();
|
||||
|
||||
if !session_uses_ssec {
|
||||
return if request_uses_ssec {
|
||||
Err(ssec_invalid_request(
|
||||
"SSE-C parameters cannot be used for a multipart upload that was not initiated with SSE-C.",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
}
|
||||
|
||||
let (Some(algorithm), Some(key), Some(key_md5)) = (
|
||||
self.sse_customer_algorithm.as_ref(),
|
||||
self.sse_customer_key.as_ref(),
|
||||
self.sse_customer_key_md5.as_ref(),
|
||||
) else {
|
||||
return Err(ssec_invalid_request(
|
||||
"Missing SSE-C parameters. Algorithm, customer key and customer key MD5 are all required.",
|
||||
));
|
||||
};
|
||||
|
||||
let validated = validate_ssec_params(SsecParams {
|
||||
algorithm: algorithm.to_string(),
|
||||
key: key.to_string(),
|
||||
key_md5: key_md5.to_string(),
|
||||
})?;
|
||||
if stored_algorithm.map(String::as_str) != Some(validated.algorithm.as_str()) {
|
||||
return Err(ssec_invalid_request(
|
||||
"The provided encryption parameters did not match the multipart upload.",
|
||||
));
|
||||
}
|
||||
// Multipart session metadata is written by our own CreateMultipartUpload,
|
||||
// which always records the MD5 — the MinIO no-stored-MD5 shape cannot occur.
|
||||
verify_ssec_key_match(&validated.key_md5, stored_key_md5, false)
|
||||
}
|
||||
}
|
||||
|
||||
/// **Core API**: Apply encryption based on request parameters
|
||||
///
|
||||
/// This function automatically routes to the appropriate encryption method:
|
||||
/// - SSE-C if customer key is provided
|
||||
/// - SSE-S3/SSE-KMS if server-side encryption is requested
|
||||
/// - None if no encryption is requested
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `request` - Encryption request with all possible encryption parameters
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(Some(material))` - Encryption should be applied with the returned material
|
||||
/// * `Ok(None)` - No encryption requested
|
||||
/// * `Err` - Encryption configuration error
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust,ignore
|
||||
/// let request = EncryptionRequest {
|
||||
/// bucket: &bucket,
|
||||
/// key: &key,
|
||||
/// server_side_encryption: effective_sse.as_ref(),
|
||||
/// ssekms_key_id: effective_kms_key_id.as_deref(),
|
||||
/// sse_customer_algorithm: sse_customer_algorithm.as_ref(),
|
||||
/// sse_customer_key: sse_customer_key.as_deref(),
|
||||
/// sse_customer_key_md5: sse_customer_key_md5.as_deref(),
|
||||
/// content_size: actual_size,
|
||||
/// part_number: None,
|
||||
/// };
|
||||
///
|
||||
/// if let Some(material) = sse_encryption(host, request).await? {
|
||||
/// reader = material.wrap_reader(reader);
|
||||
/// metadata.extend(material.metadata);
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn sse_encryption(host: &dyn SseHost, request: EncryptionRequest<'_>) -> Result<Option<EncryptionMaterial>, SseError> {
|
||||
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?;
|
||||
|
||||
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),
|
||||
};
|
||||
|
||||
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
|
||||
///
|
||||
/// sse_prepare_encryption, support SSE-C, SSE-S3, SSE-KMS
|
||||
pub struct PrepareEncryptionRequest<'a> {
|
||||
/// Bucket name
|
||||
pub bucket: &'a str,
|
||||
/// Object key
|
||||
pub key: &'a str,
|
||||
/// Server-side encryption algorithm (SSE-S3 or SSE-KMS)
|
||||
pub server_side_encryption: Option<String>,
|
||||
/// KMS key ID (for SSE-KMS)
|
||||
pub ssekms_key_id: Option<String>,
|
||||
/// Optional client-provided KMS context for SSE-KMS.
|
||||
pub ssekms_context: Option<HashMap<String, String>>,
|
||||
/// SSE-C algorithm (customer-provided key)
|
||||
pub sse_customer_algorithm: Option<String>,
|
||||
/// SSE-C key (Base64-encoded)
|
||||
pub sse_customer_key: Option<String>,
|
||||
/// SSE-C key MD5 (Base64-encoded)
|
||||
pub sse_customer_key_md5: Option<String>,
|
||||
/// Caller the SSE-KMS key usage is authorized as. `None` marks an internal caller.
|
||||
///
|
||||
/// This is the only point at which a multipart upload evaluates KMS key permissions:
|
||||
/// it is where the session data key is generated. `UploadPart`, `UploadPartCopy` and
|
||||
/// `CompleteMultipartUpload` reuse that envelope and are not re-authorized.
|
||||
pub principal: Option<&'a SseKmsPrincipal>,
|
||||
}
|
||||
|
||||
pub async fn sse_prepare_encryption(
|
||||
host: &dyn SseHost,
|
||||
request: PrepareEncryptionRequest<'_>,
|
||||
) -> Result<Option<EncryptionMaterial>, SseError> {
|
||||
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?;
|
||||
|
||||
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),
|
||||
};
|
||||
|
||||
// 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(
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
algorithm: String,
|
||||
sse_key: Option<String>,
|
||||
sse_key_md5: String,
|
||||
) -> Result<EncryptionMaterial, SseError> {
|
||||
// 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: 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: object_key.key_kind,
|
||||
managed_kms_context: None,
|
||||
managed_sealed_key: object_key.sealed_key,
|
||||
})
|
||||
}
|
||||
|
||||
async fn apply_ssec_encryption_material(
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
algorithm: String,
|
||||
sse_key: String,
|
||||
sse_key_md5: String,
|
||||
content_size: i64,
|
||||
) -> Result<EncryptionMaterial, SseError> {
|
||||
let params = SsecParams {
|
||||
algorithm,
|
||||
key: sse_key,
|
||||
key_md5: sse_key_md5,
|
||||
};
|
||||
|
||||
let validated = validate_ssec_params(params)?;
|
||||
let object_key = new_key_under_customer_key(validated.key_bytes, bucket, key)?;
|
||||
|
||||
// Build metadata
|
||||
Ok(EncryptionMaterial {
|
||||
sse_type: SSEType::SseC,
|
||||
server_side_encryption: String::from(AMZ_ENCRYPTION_AES),
|
||||
kms_key_id: None,
|
||||
algorithm: validated.algorithm,
|
||||
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: object_key.key_kind,
|
||||
managed_kms_context: None,
|
||||
managed_sealed_key: object_key.sealed_key,
|
||||
})
|
||||
}
|
||||
|
||||
/// A managed-SSE (SSE-S3 / SSE-KMS) write, once its effective scheme is known.
|
||||
pub(crate) struct ManagedEncryptionRequest<'a> {
|
||||
pub(crate) bucket: &'a str,
|
||||
pub(crate) key: &'a str,
|
||||
pub(crate) server_side_encryption: String,
|
||||
pub(crate) kms_key_id: Option<String>,
|
||||
pub(crate) ssekms_context: Option<HashMap<String, String>>,
|
||||
pub(crate) content_size: i64,
|
||||
pub(crate) principal: Option<&'a SseKmsPrincipal>,
|
||||
}
|
||||
|
||||
pub(crate) async fn apply_managed_encryption_material(
|
||||
host: &dyn SseHost,
|
||||
request: ManagedEncryptionRequest<'_>,
|
||||
) -> Result<EncryptionMaterial, SseError> {
|
||||
// Request validation, not a KMS operation: reject before the KMS is called
|
||||
// and before an audit outcome is recorded.
|
||||
reject_kms_context_location_override(request.bucket, request.ssekms_context.as_ref())?;
|
||||
|
||||
let principal = request.principal;
|
||||
let requested_sse_type = managed_sse_type(request.server_side_encryption.as_str());
|
||||
let requested_key_id = request.kms_key_id.clone();
|
||||
let result = apply_managed_encryption_material_inner(host, request).await;
|
||||
|
||||
match &result {
|
||||
// The resolved key is only known on success: it may come from the request,
|
||||
// the bucket default or the KMS service default. On failure the audit entry
|
||||
// records what the caller asked for, which is what a reader needs to see.
|
||||
Ok(material) => record_managed_kms_outcome(
|
||||
principal,
|
||||
material.sse_type,
|
||||
material.kms_key_id.as_deref(),
|
||||
|| material.encrypted_data_key.as_deref().and_then(envelope_master_key_version),
|
||||
Ok(()),
|
||||
),
|
||||
Err(error) => record_managed_kms_outcome(principal, requested_sse_type, requested_key_id.as_deref(), || None, Err(error)),
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) async fn apply_managed_encryption_material_inner(
|
||||
host: &dyn SseHost,
|
||||
request: ManagedEncryptionRequest<'_>,
|
||||
) -> Result<EncryptionMaterial, SseError> {
|
||||
let ManagedEncryptionRequest {
|
||||
bucket,
|
||||
key,
|
||||
server_side_encryption,
|
||||
kms_key_id,
|
||||
ssekms_context,
|
||||
content_size,
|
||||
principal,
|
||||
} = request;
|
||||
if !is_managed_sse(&server_side_encryption) {
|
||||
return Err(SseError::internal(format!(
|
||||
"Unsupported server-side encryption: {}",
|
||||
server_side_encryption.as_str()
|
||||
)));
|
||||
}
|
||||
|
||||
let encryption_type = match server_side_encryption.as_str() {
|
||||
"AES256" => SSEType::SseS3,
|
||||
"aws:kms" => SSEType::SseKms,
|
||||
_ => SSEType::SseS3,
|
||||
};
|
||||
|
||||
// Determine KMS key ID to use for internal key wrapping.
|
||||
let mut kms_key_candidate = kms_key_id.clone();
|
||||
if kms_key_candidate.is_none() {
|
||||
// Try to get default key from KMS service (if available)
|
||||
if let Some(service) = host.encryption_service().await {
|
||||
kms_key_candidate = service.get_default_key_id().cloned();
|
||||
tracing::debug!(
|
||||
default_key_id = ?kms_key_candidate,
|
||||
"SSE-S3: KMS service available, default_key_id from config"
|
||||
);
|
||||
} else {
|
||||
tracing::debug!("SSE-S3: KMS encryption service not available");
|
||||
}
|
||||
}
|
||||
|
||||
let kms_key_to_use = match (encryption_type, kms_key_candidate.clone()) {
|
||||
(SSEType::SseS3, Some(kms_key_id)) => kms_key_id,
|
||||
(SSEType::SseS3, None) => {
|
||||
tracing::debug!("SSE-S3: no KMS key configured, falling back to \"default\" key ID");
|
||||
"default".to_string()
|
||||
}
|
||||
(SSEType::SseKms, Some(kms_key_id)) => kms_key_id,
|
||||
(SSEType::SseKms, None) => {
|
||||
// Neither the request nor the bucket default named a key and no
|
||||
// service default filled in. Without a service this is the same
|
||||
// outage/misconfiguration the provider check below reports, so it
|
||||
// must carry the same 503/400 split rather than an untyped
|
||||
// internal error; with a running service that has no default key
|
||||
// the caller simply has to name one.
|
||||
if host.encryption_service().await.is_none() {
|
||||
return Err(sse_kms_unavailable_error(kms_configured_but_unavailable(host).await));
|
||||
}
|
||||
return Err(SseError {
|
||||
code: S3ErrorCode::InvalidRequest,
|
||||
message: "SSE-KMS requires a KMS key id: the request named none and the KMS service has no default key"
|
||||
.to_string(),
|
||||
source: None,
|
||||
});
|
||||
}
|
||||
_ => unreachable!("managed SSE branch only supports SSE-S3 or SSE-KMS"),
|
||||
};
|
||||
|
||||
// The key is fully resolved here (request header, then bucket default, then the KMS
|
||||
// service default), so this is the first point at which the caller can be held to the
|
||||
// key it will actually be encrypted under.
|
||||
authorize_sse_kms_key(host, principal, encryption_type, KmsAction::GenerateDataKeyAction, &kms_key_to_use).await?;
|
||||
|
||||
// A node-local master key is the explicit SSE-S3 fallback. Letting it serve
|
||||
// an SSE-KMS request would persist an `aws:kms` marker and a KMS key id
|
||||
// that never wrapped the data key, so refuse rather than downgrade.
|
||||
//
|
||||
// The refusal sits after the authorization gate so an unauthorized caller
|
||||
// still sees AccessDenied whatever the KMS runtime state is, and it asks
|
||||
// the resolved provider rather than a parallel availability signal,
|
||||
// because the provider is what actually wraps the DEK.
|
||||
let provider = match get_sse_dek_provider(host).await {
|
||||
Ok(provider) => {
|
||||
if matches!(encryption_type, SSEType::SseKms) && provider.wraps_dek_with_local_master_key() {
|
||||
return Err(sse_kms_unavailable_error(kms_configured_but_unavailable(host).await));
|
||||
}
|
||||
provider
|
||||
}
|
||||
// With no master key set the local fallback fails with an SSE-S3-worded
|
||||
// configuration error. An SSE-KMS request never asked for that provider,
|
||||
// so it gets the SSE-KMS refusal instead of a message naming the wrong
|
||||
// scheme.
|
||||
Err(err) => {
|
||||
if matches!(encryption_type, SSEType::SseKms) && host.encryption_service().await.is_none() {
|
||||
return Err(sse_kms_unavailable_error(kms_configured_but_unavailable(host).await));
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let object_context = build_object_encryption_context(bucket, key, ssekms_context.as_ref());
|
||||
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();
|
||||
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: 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: object_key.key_kind,
|
||||
managed_kms_context: matches!(encryption_type, SSEType::SseKms).then_some(ssekms_context.unwrap_or_default()),
|
||||
managed_sealed_key: object_key.sealed_key,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether this node has a KMS configured that is not currently serving, which
|
||||
/// separates a transient outage (retryable, 503) from a deployment that never
|
||||
/// configured KMS at all (a client-side configuration error, 400).
|
||||
async fn kms_configured_but_unavailable(host: &dyn SseHost) -> bool {
|
||||
match host.kms_service_manager() {
|
||||
Some(manager) => !matches!(manager.get_status().await, rustfs_kms::KmsServiceStatus::NotConfigured),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sse_kms_unavailable_error(configured_but_unavailable: bool) -> SseError {
|
||||
if configured_but_unavailable {
|
||||
return SseError::internal(KmsUnavailableError);
|
||||
}
|
||||
SseError {
|
||||
code: S3ErrorCode::InvalidRequest,
|
||||
message: "SSE-KMS requires a configured and running KMS service".to_string(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The error every SSE operation reports, already classified for the S3 data path.
|
||||
|
||||
use rustfs_kms::{KmsError, KmsUnavailableError};
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
|
||||
type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
/// S3 error code a KMS key that does not exist is reported under.
|
||||
pub const KMS_KEY_NOT_FOUND_ERROR_CODE: &str = "KMS.NotFoundException";
|
||||
|
||||
pub(crate) const INTERNAL_ERROR_MESSAGE: &str = "We encountered an internal error, please try again.";
|
||||
const SERVICE_UNAVAILABLE_MESSAGE: &str = "The service is unavailable. Please retry.";
|
||||
const ACCESS_DENIED_MESSAGE: &str = "Access Denied.";
|
||||
|
||||
/// A failed SSE operation, carrying the S3 error code and message the caller answers with.
|
||||
///
|
||||
/// `source` keeps the underlying failure for logs and for classification by
|
||||
/// callers; it is never part of the response.
|
||||
#[derive(Debug)]
|
||||
pub struct SseError {
|
||||
pub code: S3ErrorCode,
|
||||
pub message: String,
|
||||
pub source: Option<BoxError>,
|
||||
}
|
||||
|
||||
impl SseError {
|
||||
/// Classify a failure that did not originate from the request itself.
|
||||
///
|
||||
/// A [`KmsUnavailableError`] is a retryable `ServiceUnavailable`, a
|
||||
/// [`KmsError`] follows [`data_plane_kms_error`], and everything else is an
|
||||
/// `InternalError` whose detail stays in `source` and out of the response.
|
||||
pub fn internal(error: impl Into<BoxError>) -> Self {
|
||||
let source = error.into();
|
||||
let (code, message) = if source.downcast_ref::<KmsUnavailableError>().is_some() {
|
||||
(S3ErrorCode::ServiceUnavailable, SERVICE_UNAVAILABLE_MESSAGE.to_string())
|
||||
} else if let Some(classified) = source.downcast_ref::<KmsError>().and_then(data_plane_kms_error) {
|
||||
classified
|
||||
} else {
|
||||
(S3ErrorCode::InternalError, INTERNAL_ERROR_MESSAGE.to_string())
|
||||
};
|
||||
Self {
|
||||
code,
|
||||
message,
|
||||
source: Some(source),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for SseError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for SseError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
self.source.as_deref().map(|source| source as _)
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a KMS failure that surfaced on the S3 data path to its S3 error code.
|
||||
///
|
||||
/// The contract deliberately differs from the admin key-lifecycle handlers:
|
||||
/// there a key id is the resource being addressed, so a missing key is `404`.
|
||||
/// Here the key id arrives inside a request header or a bucket default, so a
|
||||
/// key that is missing, disabled, or otherwise unusable is configuration the
|
||||
/// caller has to correct — AWS answers `400`, and reporting `500` instead both
|
||||
/// misfiles the failure as a server fault and makes SDKs back off and retry a
|
||||
/// request that cannot succeed.
|
||||
///
|
||||
/// `None` keeps the caller's fallthrough, which is the `500` that integrity
|
||||
/// faults — damaged, unreadable, or unknown-format key material — must keep.
|
||||
///
|
||||
/// Messages either name what the caller asked for or stay generic; detail that
|
||||
/// belongs to the deployment rather than the request stays in `source`, which
|
||||
/// the caller attaches and the logs retain.
|
||||
pub fn data_plane_kms_error(error: &KmsError) -> Option<(S3ErrorCode, String)> {
|
||||
use KmsError as Kms;
|
||||
|
||||
match error {
|
||||
Kms::KeyNotFound { key_id } => Some((
|
||||
S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()),
|
||||
format!("KMS key not found: {key_id}"),
|
||||
)),
|
||||
Kms::KeyVersionNotFound { key_id, version } => Some((
|
||||
S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()),
|
||||
format!("KMS key version {version} not found for key {key_id}"),
|
||||
)),
|
||||
// The key exists but its state forbids the operation (disabled,
|
||||
// pending deletion). AWS treats an invalid key state as a request
|
||||
// error, not a server fault.
|
||||
Kms::InvalidOperation { .. } => Some((S3ErrorCode::InvalidRequest, error.to_string())),
|
||||
// A policy decision needs a human, so it must be distinguishable from
|
||||
// the transient classes an SDK retries.
|
||||
Kms::AccessDenied { .. } => Some((S3ErrorCode::AccessDenied, ACCESS_DENIED_MESSAGE.to_string())),
|
||||
// Request-side faults: what was asked for cannot be served as asked.
|
||||
Kms::ContextMismatch { .. }
|
||||
| Kms::InvalidKey { .. }
|
||||
| Kms::ValidationError { .. }
|
||||
| Kms::UnsupportedAlgorithm { .. }
|
||||
| Kms::InvalidKeySize { .. } => Some((S3ErrorCode::InvalidRequest, error.to_string())),
|
||||
// A deployment whose KMS configuration cannot serve the request (for
|
||||
// example no key named and no default). Actionable, but the detail
|
||||
// describes the deployment, so it stays out of the response body.
|
||||
Kms::ConfigurationError { .. } => {
|
||||
Some((S3ErrorCode::InvalidRequest, "The KMS configuration cannot serve this request".to_string()))
|
||||
}
|
||||
// Transient: worth retrying, and must be counted against availability
|
||||
// rather than against the caller. `IoError` belongs here because it is
|
||||
// how a backend reports that its key store itself was unreachable —
|
||||
// rustfs/rustfs#7470 separated that from a missing key precisely so the
|
||||
// two stop looking alike, and leaving it on the 500 fallthrough would
|
||||
// erase that distinction again at the S3 boundary.
|
||||
Kms::BackendError { .. }
|
||||
| Kms::IoError { .. }
|
||||
| Kms::OperationTimedOut { .. }
|
||||
| Kms::OperationCancelled { .. }
|
||||
| Kms::CredentialsUnavailable { .. }
|
||||
| Kms::CacheError { .. } => Some((S3ErrorCode::ServiceUnavailable, SERVICE_UNAVAILABLE_MESSAGE.to_string())),
|
||||
// A permanent gap in the configured backend, never a missing resource.
|
||||
Kms::UnsupportedCapability { .. } => Some((S3ErrorCode::NotImplemented, error.to_string())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn internal_keeps_request_free_failures_generic() {
|
||||
let error = SseError::internal("Failed to decode IV: bad base64");
|
||||
|
||||
assert_eq!(error.code, S3ErrorCode::InternalError);
|
||||
assert_eq!(error.message, INTERNAL_ERROR_MESSAGE);
|
||||
assert!(
|
||||
error
|
||||
.source
|
||||
.as_ref()
|
||||
.is_some_and(|source| source.to_string().contains("Failed to decode IV"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_reports_an_unavailable_kms_as_retryable() {
|
||||
let error = SseError::internal(KmsUnavailableError);
|
||||
|
||||
assert_eq!(error.code, S3ErrorCode::ServiceUnavailable);
|
||||
assert_eq!(error.message, SERVICE_UNAVAILABLE_MESSAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_classifies_kms_errors_for_the_data_path() {
|
||||
let missing = SseError::internal(KmsError::key_not_found("absent-key"));
|
||||
assert_eq!(missing.code, S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()));
|
||||
assert_eq!(missing.message, "KMS key not found: absent-key");
|
||||
|
||||
let damaged = SseError::internal(KmsError::cryptographic_error("decrypt", "authentication failed"));
|
||||
assert_eq!(damaged.code, S3ErrorCode::InternalError);
|
||||
assert_eq!(damaged.message, INTERNAL_ERROR_MESSAGE);
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! What SSE needs from the server it runs in.
|
||||
//!
|
||||
//! This crate reaches the running server only through [`SseHost`]: it holds no
|
||||
//! handle to the storage engine, to IAM, or to the bucket metadata system. Every
|
||||
//! entry point that consults the server takes the host as its first argument, so
|
||||
//! a caller cannot reach key selection without saying which server it speaks for.
|
||||
|
||||
use crate::{SseError, SseKmsPrincipal};
|
||||
use async_trait::async_trait;
|
||||
use rustfs_kms::KmsServiceManager;
|
||||
use rustfs_kms::service::ObjectEncryptionService;
|
||||
use rustfs_policy::policy::action::KmsAction;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The server capabilities SSE key resolution depends on.
|
||||
#[async_trait]
|
||||
pub trait SseHost: Send + Sync {
|
||||
/// The KMS object-encryption service currently serving, if one is.
|
||||
///
|
||||
/// Resolved on every call: the KMS backend can be reconfigured while the
|
||||
/// server runs, so a service handle must not outlive the operation it serves.
|
||||
async fn encryption_service(&self) -> Option<Arc<ObjectEncryptionService>>;
|
||||
|
||||
/// The KMS service manager, when the server has one.
|
||||
///
|
||||
/// Only its status is read, to tell a configured KMS that is not serving
|
||||
/// (retryable) from a deployment that never configured one (a request error).
|
||||
fn kms_service_manager(&self) -> Option<Arc<KmsServiceManager>>;
|
||||
|
||||
/// The bucket's default-encryption configuration.
|
||||
///
|
||||
/// `Ok(None)` means the bucket has no encryption configuration.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Any failure to read the configuration, already classified for the S3
|
||||
/// response. A write must not proceed as if the bucket had no default when
|
||||
/// the configuration could not be read.
|
||||
async fn bucket_encryption(&self, bucket: &str) -> Result<Option<BucketEncryption>, SseError>;
|
||||
|
||||
/// The authorizer deciding per-key KMS permissions on the data path.
|
||||
fn kms_key_authorizer(&self) -> &dyn KmsKeyAuthorizer;
|
||||
}
|
||||
|
||||
/// A bucket's stored encryption configuration, reduced to what a write consults.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct BucketEncryption {
|
||||
/// The default-encryption rule of the first configuration rule, if it has one.
|
||||
pub default_rule: Option<BucketDefaultEncryption>,
|
||||
}
|
||||
|
||||
/// The `ApplyServerSideEncryptionByDefault` element of a bucket encryption rule.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BucketDefaultEncryption {
|
||||
/// The stored algorithm, exactly as persisted (`AES256`, `aws:kms`, or an unknown value).
|
||||
pub sse_algorithm: String,
|
||||
pub kms_master_key_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Decides whether a principal may use a specific KMS key on the data path.
|
||||
///
|
||||
/// Behind a trait so tests can pin the allow/deny contract of the SSE call sites
|
||||
/// without a running IAM subsystem.
|
||||
#[async_trait]
|
||||
pub trait KmsKeyAuthorizer: Send + Sync {
|
||||
/// # Errors
|
||||
///
|
||||
/// When the decision itself could not be made, for example because the
|
||||
/// policy subsystem is not ready. A denial is `Ok(false)`.
|
||||
async fn is_allowed(&self, principal: &SseKmsPrincipal, action: KmsAction, key_id: &str) -> Result<bool, SseError>;
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The provider that wraps and unwraps data keys through the KMS service.
|
||||
|
||||
use crate::core::audit::KmsDataPlaneFailure;
|
||||
use crate::error::SseError;
|
||||
use crate::host::SseHost;
|
||||
use crate::kms::provider::SseDekProvider;
|
||||
use async_trait::async_trait;
|
||||
use rustfs_kms::types::ObjectEncryptionContext;
|
||||
use rustfs_kms::{DataKey, KmsUnavailableError};
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Production KMS-backed DEK provider
|
||||
/// Resolves the latest ObjectEncryptionService on each call.
|
||||
pub(crate) struct KmsSseDekProvider<'a> {
|
||||
service_source: KmsServiceSource<'a>,
|
||||
}
|
||||
|
||||
/// Where a [`KmsSseDekProvider`] finds the service that is serving right now.
|
||||
enum KmsServiceSource<'a> {
|
||||
Host(&'a dyn SseHost),
|
||||
#[cfg(test)]
|
||||
Manager(Arc<rustfs_kms::KmsServiceManager>),
|
||||
}
|
||||
|
||||
pub(crate) fn kms_operation_error(error: rustfs_kms::KmsError) -> SseError {
|
||||
let class = rustfs_kms::audit::error_class(&error);
|
||||
let mut api_error = SseError::internal(error);
|
||||
// Wrap rather than replace the source so the original chain stays intact for
|
||||
// logging; the wrapper only adds the class the audit attachment needs.
|
||||
let source = api_error.source.take();
|
||||
api_error.source = Some(Box::new(KmsDataPlaneFailure { class, source }));
|
||||
api_error
|
||||
}
|
||||
|
||||
/// Classification for a failed data-key unwrap.
|
||||
///
|
||||
/// An AEAD failure stays `500` (the envelope is an integrity fault, not a
|
||||
/// request a retry or a different header can fix), but the generic internal
|
||||
/// error text hides the one diagnosis an operator needs: the configured
|
||||
/// backend holds different key material under this key id than the one that
|
||||
/// wrapped the object, typically after re-creating a key of the same name or
|
||||
/// switching backends.
|
||||
pub(crate) fn kms_unwrap_error(error: rustfs_kms::KmsError) -> SseError {
|
||||
let unwrap_rejected = matches!(error, rustfs_kms::KmsError::CryptographicError { .. });
|
||||
let mut api_error = kms_operation_error(error);
|
||||
if unwrap_rejected && api_error.code == S3ErrorCode::InternalError {
|
||||
api_error.message = "The object's data key envelope could not be unwrapped by the configured KMS backend: the \
|
||||
key material under this key id differs from the one that wrapped it, or the envelope is damaged"
|
||||
.to_string();
|
||||
}
|
||||
api_error
|
||||
}
|
||||
|
||||
impl<'a> KmsSseDekProvider<'a> {
|
||||
/// Create a new KMS-backed provider
|
||||
pub async fn new(host: &'a dyn SseHost) -> Result<Self, SseError> {
|
||||
let provider = Self {
|
||||
service_source: KmsServiceSource::Host(host),
|
||||
};
|
||||
provider
|
||||
.current_service()
|
||||
.await
|
||||
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
|
||||
Ok(provider)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn new_with_service_manager(service_manager: Arc<rustfs_kms::KmsServiceManager>) -> Result<Self, SseError> {
|
||||
let provider = Self {
|
||||
service_source: KmsServiceSource::Manager(service_manager),
|
||||
};
|
||||
provider
|
||||
.current_service()
|
||||
.await
|
||||
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
|
||||
Ok(provider)
|
||||
}
|
||||
|
||||
async fn current_service(&self) -> Option<Arc<rustfs_kms::service::ObjectEncryptionService>> {
|
||||
match &self.service_source {
|
||||
KmsServiceSource::Host(host) => host.encryption_service().await,
|
||||
#[cfg(test)]
|
||||
KmsServiceSource::Manager(service_manager) => service_manager.get_encryption_service().await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SseDekProvider for KmsSseDekProvider<'_> {
|
||||
async fn generate_sse_dek(
|
||||
&self,
|
||||
context: &ObjectEncryptionContext,
|
||||
kms_key_id: &str,
|
||||
) -> Result<(DataKey, Vec<u8>), SseError> {
|
||||
let kms_key_option = Some(kms_key_id.to_string());
|
||||
let service = self
|
||||
.current_service()
|
||||
.await
|
||||
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
|
||||
let (data_key, encrypted_data_key) = service
|
||||
.create_data_key(&kms_key_option, context)
|
||||
.await
|
||||
.map_err(kms_operation_error)?;
|
||||
|
||||
Ok((data_key, encrypted_data_key))
|
||||
}
|
||||
|
||||
async fn reads_bare_data_key_ciphertext(&self) -> bool {
|
||||
self.current_service()
|
||||
.await
|
||||
.is_some_and(|service| service.reads_bare_data_key_ciphertext())
|
||||
}
|
||||
|
||||
async fn rewrap_sse_dek(
|
||||
&self,
|
||||
encrypted_dek: &[u8],
|
||||
context: &ObjectEncryptionContext,
|
||||
) -> Result<rustfs_kms::types::RewrapDataKeyResponse, SseError> {
|
||||
let service = self
|
||||
.current_service()
|
||||
.await
|
||||
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
|
||||
service
|
||||
.rewrap_data_key(encrypted_dek, context)
|
||||
.await
|
||||
.map_err(kms_operation_error)
|
||||
}
|
||||
|
||||
async fn decrypt_sse_dek(
|
||||
&self,
|
||||
encrypted_dek: &[u8],
|
||||
_kms_key_id: &str,
|
||||
context: &ObjectEncryptionContext,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
let service = self
|
||||
.current_service()
|
||||
.await
|
||||
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
|
||||
let data_key = service
|
||||
.decrypt_data_key(encrypted_dek, context)
|
||||
.await
|
||||
.map_err(kms_unwrap_error)?;
|
||||
|
||||
Ok(data_key.plaintext_key)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
async fn decrypt_legacy_sse_dek(
|
||||
&self,
|
||||
encrypted_dek: &[u8],
|
||||
_kms_key_id: &str,
|
||||
_context: &ObjectEncryptionContext,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
let service = self
|
||||
.current_service()
|
||||
.await
|
||||
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
|
||||
let data_key = service
|
||||
.decrypt_legacy_data_key(encrypted_dek)
|
||||
.await
|
||||
.map_err(kms_unwrap_error)?;
|
||||
|
||||
Ok(data_key.plaintext_key)
|
||||
}
|
||||
}
|
||||
@@ -1,323 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The provider that wraps data keys with a node-local master key when no KMS is configured.
|
||||
|
||||
use crate::error::SseError;
|
||||
#[cfg(feature = "rio-v2")]
|
||||
use crate::kms::minio::{decrypt_minio_kms_data_key, minio_kms_associated_data};
|
||||
use crate::kms::provider::SseDekProvider;
|
||||
use aes_gcm::aead::{Aead, KeyInit};
|
||||
use aes_gcm::{Aes256Gcm, Key, Nonce};
|
||||
use async_trait::async_trait;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use rand::Rng;
|
||||
use rustfs_kms::DataKey;
|
||||
use rustfs_kms::types::ObjectEncryptionContext;
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use rustfs_utils::get_env_opt_str;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Local SSE DEK provider for deployments without a KMS.
|
||||
///
|
||||
/// Uses `RUSTFS_SSE_S3_MASTER_KEY` (base64-encoded 32-byte key) to wrap
|
||||
/// data-encryption keys with AES-256-GCM. This is the production fallback
|
||||
/// when no KMS service is configured.
|
||||
///
|
||||
/// # Environment Variable
|
||||
///
|
||||
/// ```text
|
||||
/// RUSTFS_SSE_S3_MASTER_KEY=<base64_encoded_32_byte_key>
|
||||
/// ```
|
||||
pub struct LocalSseDekProvider {
|
||||
master_key: [u8; 32],
|
||||
}
|
||||
|
||||
pub(crate) const LOCAL_SSE_DEK_FORMAT_VERSION: u8 = 1;
|
||||
|
||||
/// Environment variable that carries the local SSE-S3 master key.
|
||||
pub(crate) const ENV_SSE_S3_MASTER_KEY: &str = "RUSTFS_SSE_S3_MASTER_KEY";
|
||||
|
||||
/// The configured local master key, still encoded; `None` when unset or blank.
|
||||
fn local_master_key_env_value() -> Option<String> {
|
||||
get_env_opt_str(ENV_SSE_S3_MASTER_KEY).filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
/// Whether the operator configured a local SSE-S3 master key at all.
|
||||
///
|
||||
/// Says nothing about whether the value is usable; loading it decides that.
|
||||
pub(crate) fn local_master_key_configured() -> bool {
|
||||
local_master_key_env_value().is_some()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
/// Returns true when a managed-SSE data key is one RustFS itself wrote.
|
||||
///
|
||||
/// Both RustFS envelope shapes are strict JSON — the KMS envelope
|
||||
/// ([`rustfs_kms::is_data_key_envelope`]) and the local provider's
|
||||
/// [`LocalSseDekEnvelope`], whose `deny_unknown_fields` keeps it from accepting
|
||||
/// anything else. Recognition is deliberately positive: an unrecognized payload
|
||||
/// is left to MinIO's decoder rather than guessed at, and neither decoder is
|
||||
/// ever handed the other's format.
|
||||
pub(crate) fn is_rustfs_managed_data_key(encrypted_dek: &[u8]) -> bool {
|
||||
if rustfs_kms::is_data_key_envelope(encrypted_dek) {
|
||||
return true;
|
||||
}
|
||||
std::str::from_utf8(encrypted_dek)
|
||||
.ok()
|
||||
.is_some_and(|text| serde_json::from_str::<LocalSseDekEnvelope<'_>>(text).is_ok())
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct LocalSseDekEnvelope<'a> {
|
||||
pub(crate) version: u8,
|
||||
pub(crate) nonce: &'a str,
|
||||
ciphertext: &'a str,
|
||||
}
|
||||
|
||||
/// Whether [`LocalSseDekProvider`] could have written these bytes.
|
||||
///
|
||||
/// Covers both shapes [`LocalSseDekProvider::decrypt_dek`] accepts — anything
|
||||
/// presented as a JSON object, so a damaged local envelope keeps its own
|
||||
/// diagnosis, and the deprecated `nonce:ciphertext` base64 pair. Everything
|
||||
/// else is bytes the local provider can only reject.
|
||||
pub(crate) fn is_local_sse_dek(encrypted_dek: &[u8]) -> bool {
|
||||
let Ok(text) = std::str::from_utf8(encrypted_dek) else {
|
||||
return false;
|
||||
};
|
||||
if text.trim_start().starts_with('{') {
|
||||
return true;
|
||||
}
|
||||
let is_base64 = |part: &str| BASE64_STANDARD.decode_to_vec(part).is_ok();
|
||||
text.split_once(':')
|
||||
.is_some_and(|(nonce, ciphertext)| is_base64(nonce) && is_base64(ciphertext))
|
||||
}
|
||||
|
||||
/// Test-only alias so existing test code that references `TestSseDekProvider`
|
||||
/// continues to compile without changes.
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub type TestSseDekProvider = LocalSseDekProvider;
|
||||
|
||||
/// Parse the base64-encoded 32-byte master key from `__RUSTFS_SSE_SIMPLE_CMK`.
|
||||
///
|
||||
/// Returns an error (never crashes) for a missing, non-base64, wrong-length, or
|
||||
/// all-zero key so callers on the request path can fail the request instead of
|
||||
/// taking the whole server down (backlog#806).
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub(crate) fn parse_simple_sse_cmk(cmk_value: &str) -> Result<[u8; 32], SseError> {
|
||||
let trimmed = cmk_value.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err(SseError::internal(
|
||||
"SSE simple mode requires __RUSTFS_SSE_SIMPLE_CMK to be set to a base64-encoded 32-byte key",
|
||||
));
|
||||
}
|
||||
let decoded = BASE64_STANDARD
|
||||
.decode_to_vec(trimmed)
|
||||
.map_err(|e| SseError::internal(format!("__RUSTFS_SSE_SIMPLE_CMK must be valid base64: {e}")))?;
|
||||
let master_key: [u8; 32] = decoded.try_into().map_err(|v: Vec<u8>| {
|
||||
SseError::internal(format!("__RUSTFS_SSE_SIMPLE_CMK must decode to exactly 32 bytes, got {} bytes", v.len()))
|
||||
})?;
|
||||
if master_key == [0u8; 32] {
|
||||
return Err(SseError::internal("__RUSTFS_SSE_SIMPLE_CMK must not be an all-zero key"));
|
||||
}
|
||||
Ok(master_key)
|
||||
}
|
||||
|
||||
impl LocalSseDekProvider {
|
||||
/// Create a LocalSseDekProvider with a predefined key (for testing)
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub fn new_with_key(master_key: [u8; 32]) -> Self {
|
||||
Self { master_key }
|
||||
}
|
||||
|
||||
/// Create a TestSseDekProvider from `__RUSTFS_SSE_SIMPLE_CMK` (test-only).
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub fn new() -> Result<Self, SseError> {
|
||||
let cmk_value = std::env::var("__RUSTFS_SSE_SIMPLE_CMK").unwrap_or_default();
|
||||
// A missing/invalid key must surface as a request error, never crash the
|
||||
// whole server: `LocalSseDekProvider::new` is reached from the SSE request
|
||||
// path (get_sse_dek_provider), so `process::exit(1)` here turned a bad
|
||||
// `__RUSTFS_SSE_SIMPLE_CMK` into a process crash-loop DoS (backlog#806).
|
||||
let master_key = parse_simple_sse_cmk(&cmk_value)?;
|
||||
tracing::info!("Successfully loaded SSE master key (32 bytes) from __RUSTFS_SSE_SIMPLE_CMK");
|
||||
Ok(Self { master_key })
|
||||
}
|
||||
|
||||
/// Create a local SSE DEK provider for SSE-S3 when KMS is not configured.
|
||||
/// Requires RUSTFS_SSE_S3_MASTER_KEY to be a valid base64-encoded 32-byte key.
|
||||
///
|
||||
/// The failures here are server configuration problems, not internal
|
||||
/// faults: surface them as `InvalidRequest` (HTTP 400) so a managed-SSE
|
||||
/// request against an unconfigured server does not report 500 (rustfs#4844).
|
||||
pub fn new_from_env() -> Result<Self, SseError> {
|
||||
fn sse_not_configured(message: impl Into<String>) -> SseError {
|
||||
SseError {
|
||||
code: S3ErrorCode::InvalidRequest,
|
||||
message: message.into(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
let Some(raw_value) = local_master_key_env_value() else {
|
||||
return Err(sse_not_configured(
|
||||
"SSE-S3 requires RUSTFS_SSE_S3_MASTER_KEY to be set to a base64-encoded 32-byte key when KMS is not configured",
|
||||
));
|
||||
};
|
||||
|
||||
let decoded = BASE64_STANDARD.decode_to_vec(raw_value.trim()).map_err(|err| {
|
||||
sse_not_configured(format!(
|
||||
"RUSTFS_SSE_S3_MASTER_KEY must be valid base64 for SSE-S3 when KMS is not configured: {err}"
|
||||
))
|
||||
})?;
|
||||
let master_key: [u8; 32] = decoded.try_into().map_err(|_| {
|
||||
sse_not_configured("RUSTFS_SSE_S3_MASTER_KEY must decode to exactly 32 bytes for SSE-S3 when KMS is not configured")
|
||||
})?;
|
||||
|
||||
Ok(Self { master_key })
|
||||
}
|
||||
|
||||
// Simple encryption of DEK
|
||||
pub fn encrypt_dek(dek: [u8; 32], cmk_value: [u8; 32]) -> Result<String, SseError> {
|
||||
// Use AES-256-GCM to encrypt DEK
|
||||
let key = Key::<Aes256Gcm>::from(cmk_value);
|
||||
|
||||
let cipher = Aes256Gcm::new(&key);
|
||||
let mut nonce_bytes = [0u8; 12];
|
||||
rand::rng().fill_bytes(&mut nonce_bytes);
|
||||
let nonce = Nonce::from(nonce_bytes);
|
||||
let ciphertext = cipher
|
||||
.encrypt(&nonce, dek.as_slice())
|
||||
.map_err(|_| SseError::internal("Failed to encrypt DEK"))?;
|
||||
|
||||
let nonce = BASE64_STANDARD.encode_to_string(nonce);
|
||||
let ciphertext = BASE64_STANDARD.encode_to_string(ciphertext);
|
||||
serde_json::to_string(&LocalSseDekEnvelope {
|
||||
version: LOCAL_SSE_DEK_FORMAT_VERSION,
|
||||
nonce: &nonce,
|
||||
ciphertext: &ciphertext,
|
||||
})
|
||||
.map_err(|e| SseError::internal(format!("Failed to serialize encrypted DEK: {e}")))
|
||||
}
|
||||
|
||||
// Simple decryption of DEK
|
||||
pub fn decrypt_dek(encrypted_dek: &str, cmk_value: [u8; 32]) -> Result<[u8; 32], SseError> {
|
||||
let envelope = serde_json::from_str::<LocalSseDekEnvelope<'_>>(encrypted_dek);
|
||||
let (nonce, ciphertext) = match envelope {
|
||||
Ok(envelope) => {
|
||||
if envelope.version != LOCAL_SSE_DEK_FORMAT_VERSION {
|
||||
return Err(SseError::internal(format!(
|
||||
"Unsupported encrypted DEK format version: {}",
|
||||
envelope.version
|
||||
)));
|
||||
}
|
||||
(envelope.nonce, envelope.ciphertext)
|
||||
}
|
||||
Err(json_error) if encrypted_dek.trim_start().starts_with('{') => {
|
||||
return Err(SseError::internal(format!("Invalid encrypted DEK JSON format: {json_error}")));
|
||||
}
|
||||
Err(_) => {
|
||||
// DEPRECATED: read-only compatibility for persisted colon-delimited DEKs.
|
||||
// RUSTFS_COMPAT_TODO(sse-local-dek-json-v1): Remove after all supported upgrades have rewritten legacy DEKs.
|
||||
let Some((nonce, ciphertext)) = encrypted_dek.split_once(':') else {
|
||||
return Err(SseError::internal("Invalid encrypted DEK format"));
|
||||
};
|
||||
if ciphertext.contains(':') {
|
||||
return Err(SseError::internal("Invalid encrypted DEK format"));
|
||||
}
|
||||
(nonce, ciphertext)
|
||||
}
|
||||
};
|
||||
let nonce_vec = BASE64_STANDARD
|
||||
.decode_to_vec(nonce)
|
||||
.map_err(|_| SseError::internal("Invalid nonce format"))?;
|
||||
let ciphertext = BASE64_STANDARD
|
||||
.decode_to_vec(ciphertext)
|
||||
.map_err(|_| SseError::internal("Invalid ciphertext format"))?;
|
||||
|
||||
let key = Key::<Aes256Gcm>::from(cmk_value);
|
||||
let cipher = Aes256Gcm::new(&key);
|
||||
|
||||
let nonce_array: [u8; 12] = nonce_vec.try_into().map_err(|_| SseError::internal("Invalid nonce length"))?;
|
||||
let nonce = Nonce::from(nonce_array);
|
||||
|
||||
let plaintext = cipher
|
||||
.decrypt(&nonce, ciphertext.as_slice())
|
||||
.map_err(|e| SseError::internal(format!("Failed to decrypt DEK: {e}")))?;
|
||||
|
||||
let dek: [u8; 32] = plaintext
|
||||
.try_into()
|
||||
.map_err(|_| SseError::internal("Decrypted DEK has invalid length"))?;
|
||||
|
||||
Ok(dek)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SseDekProvider for LocalSseDekProvider {
|
||||
fn wraps_dek_with_local_master_key(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
async fn generate_sse_dek(
|
||||
&self,
|
||||
_context: &ObjectEncryptionContext,
|
||||
_kms_key_id: &str,
|
||||
) -> Result<(DataKey, Vec<u8>), SseError> {
|
||||
// Generate a 32-byte array as data key
|
||||
let mut dek = [0u8; 32];
|
||||
rand::rng().fill_bytes(&mut dek);
|
||||
|
||||
// Generate a 12-byte array as IV
|
||||
let mut nonce = [0u8; 12];
|
||||
rand::rng().fill_bytes(&mut nonce);
|
||||
|
||||
// Encrypt data key with master key
|
||||
let encrypted_dek = Self::encrypt_dek(dek, self.master_key)?;
|
||||
|
||||
// Return data key and IV
|
||||
Ok((
|
||||
DataKey {
|
||||
plaintext_key: dek,
|
||||
nonce,
|
||||
},
|
||||
encrypted_dek.into_bytes(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn decrypt_sse_dek(
|
||||
&self,
|
||||
encrypted_dek: &[u8],
|
||||
_kms_key_id: &str,
|
||||
_context: &ObjectEncryptionContext,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
// Decrypt data key with master key
|
||||
let encrypted_dek_str =
|
||||
std::str::from_utf8(encrypted_dek).map_err(|_| SseError::internal("Invalid UTF-8 in encrypted DEK"))?;
|
||||
let dek = Self::decrypt_dek(encrypted_dek_str, self.master_key)?;
|
||||
Ok(dek)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
async fn decrypt_minio_sse_dek(
|
||||
&self,
|
||||
encrypted_dek: &[u8],
|
||||
_kms_key_id: &str,
|
||||
context: &ObjectEncryptionContext,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
let aad = minio_kms_associated_data(context)?;
|
||||
decrypt_minio_kms_data_key(encrypted_dek, &self.master_key, &aad)
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Reading data keys sealed by MinIO's builtin KMS.
|
||||
|
||||
use crate::core::keying::context::canonical_kms_bucket_path;
|
||||
use crate::core::keying::object::HmacSha256;
|
||||
use crate::error::SseError;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use hmac::Mac;
|
||||
use rustfs_kms::types::ObjectEncryptionContext;
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Associated data MinIO binds when sealing a data key.
|
||||
///
|
||||
/// MinIO passes the object's encryption context as the AEAD's associated data,
|
||||
/// serialized as canonical JSON with sorted keys — the same canonicalization
|
||||
/// [`rustfs_kms::context_aad`] performs, which is why the context RustFS
|
||||
/// already rebuilds for the read can be reused verbatim. For SSE-S3 that
|
||||
/// context is `{bucket: "bucket/object"}`; for SSE-KMS it is whatever the
|
||||
/// request supplied, recovered from the stored MinIO context header.
|
||||
pub(crate) fn minio_kms_associated_data(context: &ObjectEncryptionContext) -> Result<Vec<u8>, SseError> {
|
||||
let mut ctx = context.encryption_context.clone();
|
||||
ctx.entry(context.bucket.clone())
|
||||
.or_insert_with(|| canonical_kms_bucket_path(&context.bucket, &context.object_key));
|
||||
rustfs_kms::context_aad(&ctx).map_err(|e| SseError::internal(format!("Failed to canonicalize MinIO KMS context: {e}")))
|
||||
}
|
||||
|
||||
/// MinIO's builtin-KMS ciphertext in its JSON encoding.
|
||||
///
|
||||
/// Deliberately its own type rather than a relaxation of
|
||||
/// [`LocalSseDekEnvelope`]: widening that envelope's `deny_unknown_fields`
|
||||
/// to admit this shape would also admit malformed RustFS envelopes, which
|
||||
/// backlog#1567 requires to keep failing closed.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct MinioKmsCiphertextJson {
|
||||
aead: String,
|
||||
#[allow(
|
||||
dead_code,
|
||||
reason = "present in MinIO's encoding; the key is identified by metadata instead"
|
||||
)]
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
iv: String,
|
||||
nonce: String,
|
||||
bytes: String,
|
||||
}
|
||||
|
||||
/// Bytes of trailing randomness every MinIO builtin-KMS ciphertext carries:
|
||||
/// a 16-byte IV followed by a 12-byte nonce, *after* the sealed bytes.
|
||||
const MINIO_KMS_RANDOM_LEN: usize = 28;
|
||||
|
||||
const MINIO_KMS_IV_LEN: usize = 16;
|
||||
|
||||
const MINIO_KMS_AEAD_AES_GCM: &str = "AES-256-GCM-HMAC-SHA-256";
|
||||
|
||||
const MINIO_KMS_AEAD_CHACHA20: &str = "ChaCha20Poly1305";
|
||||
|
||||
/// Unwrap a data key sealed by MinIO's builtin (static-secret) KMS.
|
||||
///
|
||||
/// The wire format is `sealed_bytes || iv[16] || nonce[12]` — the randomness
|
||||
/// trails the ciphertext rather than leading it, and MinIO's own decoder
|
||||
/// normalizes its legacy JSON encoding into exactly that byte order before
|
||||
/// opening it (`internal/kms/secret-key.go`, `parseCiphertext`). A raw
|
||||
/// (non-JSON) ciphertext is AES-256-GCM by definition there; the JSON form
|
||||
/// names its algorithm.
|
||||
///
|
||||
/// The sealing key is derived per ciphertext rather than being the master key:
|
||||
/// `HMAC-SHA256(master, iv)` for AES-256-GCM, `HChaCha20(master, iv)` for
|
||||
/// ChaCha20-Poly1305. The encryption context is bound as associated data.
|
||||
pub(crate) fn decrypt_minio_kms_data_key(encrypted_dek: &[u8], master_key: &[u8; 32], aad: &[u8]) -> Result<[u8; 32], SseError> {
|
||||
let (body, algorithm) = match std::str::from_utf8(encrypted_dek) {
|
||||
// MinIO only treats a payload as JSON when it both starts and ends like
|
||||
// an object, and falls back to the raw layout when it does not parse —
|
||||
// mirrored here so a ciphertext that merely looks like JSON is not
|
||||
// rejected outright.
|
||||
Ok(text)
|
||||
if text.starts_with('{')
|
||||
&& text.ends_with('}')
|
||||
&& let Ok(json) = serde_json::from_str::<MinioKmsCiphertextJson>(text) =>
|
||||
{
|
||||
let decode = |what: &str, value: &str| -> Result<Vec<u8>, SseError> {
|
||||
BASE64_STANDARD
|
||||
.decode_to_vec(value)
|
||||
.map_err(|e| SseError::internal(format!("Invalid MinIO KMS {what}: {e}")))
|
||||
};
|
||||
let mut body = decode("ciphertext", &json.bytes)?;
|
||||
body.extend_from_slice(&decode("iv", &json.iv)?);
|
||||
body.extend_from_slice(&decode("nonce", &json.nonce)?);
|
||||
(body, json.aead)
|
||||
}
|
||||
_ => (encrypted_dek.to_vec(), MINIO_KMS_AEAD_AES_GCM.to_string()),
|
||||
};
|
||||
|
||||
if body.len() <= MINIO_KMS_RANDOM_LEN {
|
||||
return Err(SseError::internal("MinIO KMS ciphertext is too short to carry its IV and nonce"));
|
||||
}
|
||||
let (sealed, random) = body.split_at(body.len() - MINIO_KMS_RANDOM_LEN);
|
||||
let (iv, nonce) = random.split_at(MINIO_KMS_IV_LEN);
|
||||
|
||||
let plaintext = match algorithm.as_str() {
|
||||
MINIO_KMS_AEAD_AES_GCM => {
|
||||
use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
|
||||
let mut mac = HmacSha256::new_from_slice(master_key)
|
||||
.map_err(|_| SseError::internal("MinIO KMS sealing key derivation failed"))?;
|
||||
mac.update(iv);
|
||||
let sealing_key: [u8; 32] = mac.finalize().into_bytes().into();
|
||||
let cipher = Aes256Gcm::new_from_slice(&sealing_key)
|
||||
.map_err(|_| SseError::internal("MinIO KMS sealing key is not a valid AES-256 key"))?;
|
||||
let nonce = aes_gcm::Nonce::try_from(nonce).map_err(|_| SseError::internal("MinIO KMS nonce is not 12 bytes"))?;
|
||||
cipher.decrypt(&nonce, aes_gcm::aead::Payload { msg: sealed, aad })
|
||||
}
|
||||
MINIO_KMS_AEAD_CHACHA20 => {
|
||||
use chacha20poly1305::{KeyInit, XChaCha20Poly1305, aead::Aead};
|
||||
// MinIO derives this branch's key with HChaCha20 over the 16-byte
|
||||
// IV, which is exactly XChaCha20-Poly1305's own construction, so the
|
||||
// extended-nonce cipher does the derivation rather than hand-rolling it.
|
||||
let mut extended = Vec::with_capacity(MINIO_KMS_IV_LEN + nonce.len());
|
||||
extended.extend_from_slice(iv);
|
||||
extended.extend_from_slice(nonce);
|
||||
let cipher = XChaCha20Poly1305::new_from_slice(master_key)
|
||||
.map_err(|_| SseError::internal("MinIO KMS master key is not a valid ChaCha20 key"))?;
|
||||
let nonce = chacha20poly1305::XNonce::try_from(extended.as_slice())
|
||||
.map_err(|_| SseError::internal("MinIO KMS extended nonce is not 24 bytes"))?;
|
||||
cipher.decrypt(&nonce, chacha20poly1305::aead::Payload { msg: sealed, aad })
|
||||
}
|
||||
other => {
|
||||
return Err(SseError::internal(format!("Unsupported MinIO KMS AEAD algorithm: {other}")));
|
||||
}
|
||||
}
|
||||
// An AEAD failure here is authentication, not a decode slip: a wrong master
|
||||
// key, a tampered ciphertext, and an encryption context that does not match
|
||||
// what sealed it all land here and must all fail closed.
|
||||
.map_err(|_| SseError::internal("MinIO KMS data key failed authentication"))?;
|
||||
|
||||
plaintext
|
||||
.try_into()
|
||||
.map_err(|value: Vec<u8>| SseError::internal(format!("MinIO KMS data key must be 32 bytes, got {}", value.len())))
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Data-key providers: where a data key is wrapped and unwrapped.
|
||||
|
||||
pub(crate) mod kms_backed;
|
||||
pub(crate) mod local;
|
||||
#[cfg(feature = "rio-v2")]
|
||||
pub(crate) mod minio;
|
||||
pub(crate) mod provider;
|
||||
@@ -1,288 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The data-key provider interface and the per-request choice between the KMS and the local master key.
|
||||
|
||||
use crate::error::SseError;
|
||||
use crate::host::SseHost;
|
||||
use crate::kms::kms_backed::KmsSseDekProvider;
|
||||
use crate::kms::local::LocalSseDekProvider;
|
||||
use async_trait::async_trait;
|
||||
use rustfs_kms::DataKey;
|
||||
use rustfs_kms::types::ObjectEncryptionContext;
|
||||
use std::sync::{Arc, LazyLock, RwLock};
|
||||
use tracing::debug;
|
||||
|
||||
/// Trait for SSE data encryption key management
|
||||
/// Abstracts the source of encryption keys (KMS, test provider, etc.)
|
||||
#[async_trait]
|
||||
pub trait SseDekProvider: Send + Sync {
|
||||
/// Generate an SSE data encryption key
|
||||
async fn generate_sse_dek(&self, context: &ObjectEncryptionContext, kms_key_id: &str)
|
||||
-> Result<(DataKey, Vec<u8>), SseError>;
|
||||
|
||||
/// Decrypt an SSE data encryption key (returns only plaintext key, nonce should be read from metadata)
|
||||
async fn decrypt_sse_dek(
|
||||
&self,
|
||||
encrypted_dek: &[u8],
|
||||
kms_key_id: &str,
|
||||
context: &ObjectEncryptionContext,
|
||||
) -> Result<[u8; 32], SseError>;
|
||||
|
||||
/// Whether this provider may own a stored data key that is not a RustFS
|
||||
/// envelope — see `KmsBackend::reads_bare_data_key_ciphertext`.
|
||||
async fn reads_bare_data_key_ciphertext(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Re-wrap a KMS-wrapped DEK envelope onto its master key's current
|
||||
/// version without exposing the plaintext DEK to the caller.
|
||||
///
|
||||
/// Defaults to refusing: only the KMS-backed provider can rewrap, and a
|
||||
/// provider that cannot must say so rather than hand back the input as if
|
||||
/// it had been re-protected.
|
||||
async fn rewrap_sse_dek(
|
||||
&self,
|
||||
_encrypted_dek: &[u8],
|
||||
_context: &ObjectEncryptionContext,
|
||||
) -> Result<rustfs_kms::types::RewrapDataKeyResponse, SseError> {
|
||||
Err(SseError::internal("This DEK provider cannot rewrap KMS-wrapped data keys"))
|
||||
}
|
||||
|
||||
/// Whether this provider wraps data keys with a node-local master key
|
||||
/// instead of a KMS service.
|
||||
///
|
||||
/// SSE-KMS must never be served by such a provider: the stored object would
|
||||
/// claim `aws:kms` and name a KMS key id that never wrapped anything.
|
||||
/// Defaults to false so only the local fallback has to declare itself.
|
||||
fn wraps_dek_with_local_master_key(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Decrypt a DEK from positively identified legacy managed metadata.
|
||||
#[cfg(feature = "rio-v2")]
|
||||
async fn decrypt_legacy_sse_dek(
|
||||
&self,
|
||||
encrypted_dek: &[u8],
|
||||
kms_key_id: &str,
|
||||
context: &ObjectEncryptionContext,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
self.decrypt_sse_dek(encrypted_dek, kms_key_id, context).await
|
||||
}
|
||||
|
||||
/// Unwrap a data key that MinIO's builtin KMS sealed.
|
||||
///
|
||||
/// A separate entry point rather than a shape sniff inside
|
||||
/// [`Self::decrypt_sse_dek`]: the caller already knows the object carries a
|
||||
/// MinIO sealed key, and MinIO's raw ciphertext is unstructured bytes that
|
||||
/// no parser can reliably tell apart from anything else. Routing on the
|
||||
/// caller's knowledge keeps a RustFS envelope from ever reaching MinIO's
|
||||
/// decoder, and vice versa.
|
||||
///
|
||||
/// Defaults to refusing: only a provider holding the MinIO master secret
|
||||
/// can serve these, and a provider that cannot must fail rather than fall
|
||||
/// back to a decoder that would misread the bytes.
|
||||
#[cfg(feature = "rio-v2")]
|
||||
async fn decrypt_minio_sse_dek(
|
||||
&self,
|
||||
_encrypted_dek: &[u8],
|
||||
_kms_key_id: &str,
|
||||
_context: &ObjectEncryptionContext,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
Err(SseError::internal(
|
||||
"This KMS provider cannot unwrap a data key sealed by MinIO's builtin KMS",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Unwrap the data key of an object that carries a sealed object key but no
|
||||
/// RustFS envelope.
|
||||
///
|
||||
/// Two writers produce that shape, and nothing in the bytes tells them apart:
|
||||
/// MinIO, whose data key is sealed under the static master key, and a RustFS
|
||||
/// `rio-v2` build on a backend that persisted its native ciphertext bare.
|
||||
/// MinIO's sealing is authenticated, so opening it under the local master key
|
||||
/// is a proof rather than a guess: the bare blob is offered to the KMS only
|
||||
/// once that has failed, or when no local master key exists to try. Without a
|
||||
/// backend that reads bare ciphertext the MinIO route is the only one, exactly
|
||||
/// as before.
|
||||
#[cfg(feature = "rio-v2")]
|
||||
pub(crate) async fn decrypt_unenveloped_sealed_dek(
|
||||
bare_kms: Option<Arc<dyn SseDekProvider + '_>>,
|
||||
local: Result<Arc<dyn SseDekProvider>, SseError>,
|
||||
encrypted_dek: &[u8],
|
||||
kms_key_id: &str,
|
||||
context: &ObjectEncryptionContext,
|
||||
) -> Result<[u8; 32], SseError> {
|
||||
let Some(kms) = bare_kms else {
|
||||
return local?.decrypt_minio_sse_dek(encrypted_dek, kms_key_id, context).await;
|
||||
};
|
||||
if let Ok(local) = local
|
||||
&& let Ok(data_key) = local.decrypt_minio_sse_dek(encrypted_dek, kms_key_id, context).await
|
||||
{
|
||||
return Ok(data_key);
|
||||
}
|
||||
kms.decrypt_sse_dek(encrypted_dek, kms_key_id, context).await
|
||||
}
|
||||
|
||||
/// The provider that unwraps KMS-wrapped data keys.
|
||||
///
|
||||
/// A provider registered through `set_sse_dek_provider_for_test` stands in for
|
||||
/// the fresh [`KmsSseDekProvider`], which cannot resolve a KMS service from a
|
||||
/// host that has none. Only `GLOBAL_KMS_DEK_PROVIDER` is consulted, never
|
||||
/// `GLOBAL_SSE_DEK_PROVIDER`, so a local provider cached by an earlier
|
||||
/// `get_local_sse_dek_provider` call cannot be selected to unwrap a KMS envelope.
|
||||
pub(crate) async fn kms_sse_dek_provider<'a>(host: &'a dyn SseHost) -> Result<Arc<dyn SseDekProvider + 'a>, SseError> {
|
||||
if let Some(cached) = GLOBAL_KMS_DEK_PROVIDER.read().ok().and_then(|guard| guard.as_ref().cloned()) {
|
||||
return Ok(cached);
|
||||
}
|
||||
Ok(Arc::new(KmsSseDekProvider::new(host).await?))
|
||||
}
|
||||
|
||||
/// The KMS provider, when its backend may own a stored data key that is not a
|
||||
/// RustFS envelope. `None` without a running KMS, which leaves such a key to
|
||||
/// the local provider exactly as before.
|
||||
pub(crate) async fn bare_data_key_kms_provider<'a>(host: &'a dyn SseHost) -> Option<Arc<dyn SseDekProvider + 'a>> {
|
||||
let provider = kms_sse_dek_provider(host).await.ok()?;
|
||||
provider.reads_bare_data_key_ciphertext().await.then_some(provider)
|
||||
}
|
||||
|
||||
/// Global SSE DEK provider cache for local / test providers.
|
||||
///
|
||||
/// Populated by `get_local_sse_dek_provider` and (for backward-compat in tests)
|
||||
/// `set_sse_dek_provider_for_test`. Read by `get_local_sse_dek_provider` only —
|
||||
/// the KMS-envelope decrypt path uses `GLOBAL_KMS_DEK_PROVIDER` so that a cached
|
||||
/// local provider can never be selected for a KMS-wrapped data-key.
|
||||
pub(crate) static GLOBAL_SSE_DEK_PROVIDER: LazyLock<RwLock<Option<Arc<dyn SseDekProvider>>>> =
|
||||
LazyLock::new(|| RwLock::new(None));
|
||||
|
||||
/// Global KMS DEK provider cache for test-injected KMS providers.
|
||||
///
|
||||
/// Populated **only** by `set_sse_dek_provider_for_test` (test-only).
|
||||
/// Read **only** by the KMS-envelope branch of `apply_managed_decryption_material`.
|
||||
/// Separation from `GLOBAL_SSE_DEK_PROVIDER` prevents a previously-cached local
|
||||
/// provider from being selected to unwrap a KMS data-key envelope.
|
||||
static GLOBAL_KMS_DEK_PROVIDER: LazyLock<RwLock<Option<Arc<dyn SseDekProvider>>>> = LazyLock::new(|| RwLock::new(None));
|
||||
|
||||
/// Get or initialize the global SSE DEK provider
|
||||
///
|
||||
/// Factory function that automatically selects the appropriate provider:
|
||||
/// - If `__RUSTFS_SSE_SIMPLE_CMK` environment variable exists: use SimpleSseDekProvider (test mode)
|
||||
/// - Otherwise: use KmsSseDekProvider (production mode with real KMS)
|
||||
///
|
||||
/// # Returns
|
||||
/// Arc to the global SSE DEK provider instance
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust,ignore
|
||||
/// let provider = get_sse_dek_provider(host).await?;
|
||||
/// let (data_key, encrypted_dek) = provider
|
||||
/// .generate_sse_dek("bucket", "key", "kms-key-id")
|
||||
/// .await?;
|
||||
/// ```
|
||||
pub(crate) async fn get_sse_dek_provider<'a>(host: &'a dyn SseHost) -> Result<Arc<dyn SseDekProvider + 'a>, SseError> {
|
||||
if host.encryption_service().await.is_some() {
|
||||
debug!("Using KmsSseDekProvider (KMS configured)");
|
||||
return Ok(Arc::new(KmsSseDekProvider::new(host).await?));
|
||||
}
|
||||
|
||||
get_local_sse_dek_provider()
|
||||
}
|
||||
|
||||
/// Get the local data-key provider, loading and caching it on first use.
|
||||
///
|
||||
/// Startup calls this to check the local master key ahead of traffic; a request
|
||||
/// that arrives without that step loads it the same way and gets the same error.
|
||||
pub(crate) fn get_local_sse_dek_provider() -> Result<Arc<dyn SseDekProvider>, SseError> {
|
||||
// An explicitly injected test provider overrides both the cache and the
|
||||
// environment-based selection below.
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
if let Some(injected) = test_injected_sse_dek_provider() {
|
||||
return Ok(injected);
|
||||
}
|
||||
|
||||
// Check if already initialized
|
||||
if let Some(provider) = GLOBAL_SSE_DEK_PROVIDER
|
||||
.read()
|
||||
.map_err(|_| SseError::internal("Failed to read global SSE DEK provider cache"))?
|
||||
.as_ref()
|
||||
.cloned()
|
||||
{
|
||||
return Ok(provider);
|
||||
}
|
||||
|
||||
// In test mode, prefer the simple CMK provider when the env var is set.
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
{
|
||||
if std::env::var("__RUSTFS_SSE_SIMPLE_CMK").is_ok() {
|
||||
debug!("Using LocalSseDekProvider (test mode) based on __RUSTFS_SSE_SIMPLE_CMK");
|
||||
let provider: Arc<dyn SseDekProvider> = Arc::new(LocalSseDekProvider::new()?);
|
||||
let mut slot = GLOBAL_SSE_DEK_PROVIDER
|
||||
.write()
|
||||
.map_err(|_| SseError::internal("Failed to update global SSE DEK provider cache"))?;
|
||||
if let Some(existing) = slot.as_ref() {
|
||||
return Ok(existing.clone());
|
||||
}
|
||||
*slot = Some(provider.clone());
|
||||
return Ok(provider);
|
||||
}
|
||||
}
|
||||
|
||||
// Production fallback: local SSE-S3 provider (no KMS configured).
|
||||
debug!("Using local SSE-S3 provider (KMS not configured)");
|
||||
let provider: Arc<dyn SseDekProvider> = Arc::new(LocalSseDekProvider::new_from_env()?);
|
||||
|
||||
let mut slot = GLOBAL_SSE_DEK_PROVIDER
|
||||
.write()
|
||||
.map_err(|_| SseError::internal("Failed to update global SSE DEK provider cache"))?;
|
||||
if let Some(existing) = slot.as_ref() {
|
||||
return Ok(existing.clone());
|
||||
}
|
||||
*slot = Some(provider.clone());
|
||||
|
||||
Ok(provider)
|
||||
}
|
||||
|
||||
/// Reset both global SSE DEK provider caches (for testing only)
|
||||
///
|
||||
/// Clears GLOBAL_SSE_DEK_PROVIDER (local/test providers) and
|
||||
/// GLOBAL_KMS_DEK_PROVIDER (test-injected KMS providers).
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub fn reset_sse_dek_provider() {
|
||||
if let Ok(mut slot) = GLOBAL_SSE_DEK_PROVIDER.write() {
|
||||
*slot = None;
|
||||
}
|
||||
if let Ok(mut slot) = GLOBAL_KMS_DEK_PROVIDER.write() {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub fn set_sse_dek_provider_for_test(provider: Arc<dyn SseDekProvider>) {
|
||||
if let Ok(mut slot) = GLOBAL_KMS_DEK_PROVIDER.write() {
|
||||
*slot = Some(provider.clone());
|
||||
}
|
||||
if let Ok(mut slot) = GLOBAL_SSE_DEK_PROVIDER.write() {
|
||||
*slot = Some(provider);
|
||||
}
|
||||
}
|
||||
|
||||
/// Provider explicitly injected via `set_sse_dek_provider_for_test`, if any.
|
||||
///
|
||||
/// Reads `GLOBAL_KMS_DEK_PROVIDER` because that slot is populated *only* by the
|
||||
/// test setter, so a hit here always means an explicit test injection.
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
fn test_injected_sse_dek_provider() -> Option<Arc<dyn SseDekProvider>> {
|
||||
GLOBAL_KMS_DEK_PROVIDER.read().ok().and_then(|guard| guard.as_ref().cloned())
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! S3 server-side encryption: which key encrypts an object, and what is stored to find it again.
|
||||
//!
|
||||
//! Covers the three S3 schemes:
|
||||
//! - SSE-S3 (`AES256`): a data key wrapped by a key the server owns
|
||||
//! - SSE-KMS (`aws:kms`): a data key wrapped by a KMS key the caller names
|
||||
//! - SSE-C: a key the client supplies on every request and the server never stores
|
||||
//!
|
||||
//! ## Where this crate sits
|
||||
//!
|
||||
//! Between the S3 layer and the storage engine, depending on neither. It decides
|
||||
//! the effective scheme of a write, obtains and unwraps data keys, authorizes the
|
||||
//! use of a KMS key, and encodes and reads the encryption metadata of an object.
|
||||
//! It does not transform object bytes: it hands back key material
|
||||
//! ([`EncryptionMaterial`], [`DecryptionMaterial`]) and the caller applies it.
|
||||
//!
|
||||
//! What it needs from the running server — the KMS service, a bucket's default
|
||||
//! encryption, a key-permission decision — arrives through [`SseHost`], passed
|
||||
//! to every entry point that consults the server. Failures are reported as
|
||||
//! [`SseError`], already classified with the S3 error code the caller answers with.
|
||||
//!
|
||||
//! ## Entry points
|
||||
//!
|
||||
//! - [`sse_encryption`] and [`sse_prepare_encryption`] resolve the material of a write;
|
||||
//! [`encryption_material_to_metadata`] turns it into the metadata to store.
|
||||
//! - [`sse_decryption`] resolves the material of a read from stored metadata;
|
||||
//! [`classify_sse_read_response`] derives the response headers without unwrapping a key.
|
||||
//! - [`rewrap_object_encryption_metadata`] moves a stored data key onto the current
|
||||
//! version of its KMS key.
|
||||
//! - [`startup::init`] settles the environment-driven configuration once per process
|
||||
//! and reports it; calling it is optional.
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! let request = EncryptionRequest {
|
||||
//! bucket: &bucket,
|
||||
//! key: &key,
|
||||
//! server_side_encryption: effective_sse,
|
||||
//! ssekms_key_id: effective_kms_key_id,
|
||||
//! ssekms_context: None,
|
||||
//! sse_customer_algorithm: None,
|
||||
//! sse_customer_key: None,
|
||||
//! sse_customer_key_md5: None,
|
||||
//! content_size: actual_size,
|
||||
//! principal: principal.as_ref(),
|
||||
//! };
|
||||
//!
|
||||
//! if let Some(material) = sse_encryption(host, request).await? {
|
||||
//! metadata.extend(encryption_material_to_metadata(&material)?);
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
mod core;
|
||||
mod error;
|
||||
mod host;
|
||||
mod kms;
|
||||
pub mod startup;
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub mod testing;
|
||||
#[cfg(test)]
|
||||
#[allow(unused_imports)]
|
||||
mod tests;
|
||||
|
||||
pub use crate::core::audit::KmsRequestAuditScope;
|
||||
pub use crate::core::keying::material::{DecryptionMaterial, EncryptionKeyKind, EncryptionMaterial, ManagedSealedKey};
|
||||
pub use crate::core::keying::metadata::{
|
||||
ConflictingEncryptionMetadata, encryption_material_to_metadata, mark_encrypted_multipart_metadata,
|
||||
normalize_encryption_metadata_case, stored_ssec_metadata, strip_managed_encryption_metadata,
|
||||
};
|
||||
pub use crate::core::read::{DecryptionRequest, classify_sse_read_response, sse_decryption};
|
||||
pub use crate::core::request::SseKmsPrincipal;
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub use crate::core::request::TestAuthorizationHooks;
|
||||
pub use crate::core::rewrap::{ObjectDekRewrapOutcome, rewrap_object_encryption_metadata};
|
||||
pub use crate::core::s3::authorization::{authorize_sse_kms_multipart_write, authorize_sse_kms_object_read};
|
||||
pub use crate::core::s3::headers::{
|
||||
SseReadResponseHeaders, SsecParamsFromHeaders, build_ssec_read_headers, extract_server_side_encryption_from_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, 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};
|
||||
pub use crate::host::{BucketDefaultEncryption, BucketEncryption, KmsKeyAuthorizer, SseHost};
|
||||
pub use crate::kms::local::LocalSseDekProvider;
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub use crate::kms::local::TestSseDekProvider;
|
||||
pub use crate::kms::provider::SseDekProvider;
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pub use crate::kms::provider::{reset_sse_dek_provider, set_sse_dek_provider_for_test};
|
||||
// The managed-SSE classifier lives in the shared encryption-keys module so the
|
||||
// scanner can reuse it; re-exported here so SSE callers find it beside the rest.
|
||||
pub use rustfs_utils::http::object_encryption_keys::SSEType;
|
||||
pub use rustfs_utils::http::object_encryption_keys::contains_managed_encryption_metadata;
|
||||
|
||||
pub(crate) const LOG_COMPONENT_STORAGE: &str = "storage";
|
||||
pub(crate) const LOG_SUBSYSTEM_SSE: &str = "sse";
|
||||
@@ -1,250 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The crate's process-startup step.
|
||||
//!
|
||||
//! [`init`] settles the two things that cannot change without a restart, both
|
||||
//! read from the environment, and reports them once:
|
||||
//!
|
||||
//! - whether SSE-KMS requests are authorized against the key they name;
|
||||
//! - whether the local SSE-S3 master key is usable.
|
||||
//!
|
||||
//! Nothing that follows the KMS service is decided here. The KMS can be
|
||||
//! configured, started, restarted, and stopped while the server runs, so the
|
||||
//! choice between the KMS and the local master key is made per request, and no
|
||||
//! KMS state is cached by this crate.
|
||||
//!
|
||||
//! Calling [`init`] is optional. A process that never calls it reads the same
|
||||
//! switch and loads the same master key on first use, with the same errors; it
|
||||
//! only goes without the startup report.
|
||||
|
||||
use crate::error::SseError;
|
||||
use crate::kms::local::{ENV_SSE_S3_MASTER_KEY, local_master_key_configured};
|
||||
use crate::kms::provider::get_local_sse_dek_provider;
|
||||
use crate::{LOG_COMPONENT_STORAGE, LOG_SUBSYSTEM_SSE};
|
||||
use rustfs_config::{DEFAULT_KMS_ENFORCE_SSE_KEY_POLICY, ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY};
|
||||
use rustfs_utils::get_env_bool;
|
||||
use std::sync::{LazyLock, OnceLock};
|
||||
|
||||
const EVENT_SSE_KMS_KEY_POLICY_MODE: &str = "sse_kms_key_policy_mode";
|
||||
const EVENT_SSE_LOCAL_MASTER_KEY: &str = "sse_local_master_key";
|
||||
|
||||
/// State of the local SSE-S3 master key at startup.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LocalMasterKeyStatus {
|
||||
/// Configured and usable; SSE-S3 works without a KMS.
|
||||
Loaded,
|
||||
/// Not configured; SSE-S3 requires a running KMS.
|
||||
NotSet,
|
||||
/// Configured but unusable; SSE-S3 requests that need it are rejected.
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl LocalMasterKeyStatus {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Loaded => "loaded",
|
||||
Self::NotSet => "not_set",
|
||||
Self::Invalid => "invalid",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`init`] settled for this process.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StartupReport {
|
||||
/// Whether SSE-KMS requests are authorized against the KMS key they name.
|
||||
pub key_policy_enforced: bool,
|
||||
/// State of the local SSE-S3 master key.
|
||||
pub local_master_key: LocalMasterKeyStatus,
|
||||
}
|
||||
|
||||
/// Settle the process-wide SSE configuration and report it.
|
||||
///
|
||||
/// Idempotent: the first call does the work and logs; later calls, such as a
|
||||
/// second embedded server in the same process, return the same report silently.
|
||||
/// An unusable master key does not fail startup, because a server whose KMS is
|
||||
/// running never needs it.
|
||||
pub fn init() -> StartupReport {
|
||||
static REPORT: OnceLock<StartupReport> = OnceLock::new();
|
||||
*REPORT.get_or_init(|| {
|
||||
let key_policy_enforced = key_policy_enforced();
|
||||
log_key_policy_mode(key_policy_enforced);
|
||||
|
||||
let local_master_key = load_local_master_key();
|
||||
log_local_master_key(&local_master_key);
|
||||
|
||||
StartupReport {
|
||||
key_policy_enforced,
|
||||
local_master_key: local_master_key.unwrap_or(LocalMasterKeyStatus::Invalid),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether per-key KMS authorization is enforced on the SSE-KMS data path.
|
||||
///
|
||||
/// Frozen on first read, by [`init`] or by the first request, so one process
|
||||
/// never answers the same question two ways.
|
||||
pub(crate) fn key_policy_enforced() -> bool {
|
||||
static ENFORCED: LazyLock<bool> =
|
||||
LazyLock::new(|| get_env_bool(ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY, DEFAULT_KMS_ENFORCE_SSE_KEY_POLICY));
|
||||
*ENFORCED
|
||||
}
|
||||
|
||||
/// Load the local master key through the loader the request path uses.
|
||||
///
|
||||
/// An absent key is a state, not a failure: only a configured key is loaded, so
|
||||
/// the error case is exactly "configured but unusable".
|
||||
fn load_local_master_key() -> Result<LocalMasterKeyStatus, SseError> {
|
||||
if !local_master_key_configured() {
|
||||
return Ok(LocalMasterKeyStatus::NotSet);
|
||||
}
|
||||
get_local_sse_dek_provider().map(|_| LocalMasterKeyStatus::Loaded)
|
||||
}
|
||||
|
||||
/// Report the configured SSE-KMS authorization mode.
|
||||
///
|
||||
/// The disabled case warns rather than logs: while enforcement is off, any identity
|
||||
/// allowed to write an object can encrypt it under any key, and operators should hear
|
||||
/// about that even though disabled is the long-term default.
|
||||
fn log_key_policy_mode(enforced: bool) {
|
||||
if enforced {
|
||||
tracing::info!(
|
||||
event = EVENT_SSE_KMS_KEY_POLICY_MODE,
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
enforced = true,
|
||||
"SSE-KMS requests are authorized against the resolved KMS key (kms:GenerateDataKey / kms:Decrypt)"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
tracing::warn!(
|
||||
event = EVENT_SSE_KMS_KEY_POLICY_MODE,
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
enforced = false,
|
||||
"SSE-KMS requests are not authorized against the KMS key they name; any identity allowed to \
|
||||
write an object may encrypt it under any key, and any identity allowed to read it may have it \
|
||||
decrypted. Grant kms:GenerateDataKey and kms:Decrypt on the keys your workloads use, then set \
|
||||
{ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY}=true."
|
||||
);
|
||||
}
|
||||
|
||||
/// Report the local master key's state.
|
||||
///
|
||||
/// The failure text is the one a request is answered with. It describes the
|
||||
/// configuration problem and never carries the configured value.
|
||||
fn log_local_master_key(outcome: &Result<LocalMasterKeyStatus, SseError>) {
|
||||
match outcome {
|
||||
Ok(status @ LocalMasterKeyStatus::Loaded) => tracing::info!(
|
||||
event = EVENT_SSE_LOCAL_MASTER_KEY,
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
state = status.as_str(),
|
||||
"{ENV_SSE_S3_MASTER_KEY} is loaded; SSE-S3 uses it whenever no KMS is running"
|
||||
),
|
||||
Ok(status) => tracing::info!(
|
||||
event = EVENT_SSE_LOCAL_MASTER_KEY,
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
state = status.as_str(),
|
||||
"{ENV_SSE_S3_MASTER_KEY} is not set; SSE-S3 requires a running KMS"
|
||||
),
|
||||
Err(error) => tracing::error!(
|
||||
event = EVENT_SSE_LOCAL_MASTER_KEY,
|
||||
component = LOG_COMPONENT_STORAGE,
|
||||
subsystem = LOG_SUBSYSTEM_SSE,
|
||||
state = LocalMasterKeyStatus::Invalid.as_str(),
|
||||
reason = %error.message,
|
||||
"{ENV_SSE_S3_MASTER_KEY} is set but unusable; SSE-S3 requests are rejected while no KMS is running"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::kms::provider::reset_sse_dek_provider;
|
||||
use crate::tests::lock_sse_test_state;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use temp_env::with_vars;
|
||||
|
||||
/// Run `check` with the local master key set to `value` and nothing cached or injected.
|
||||
async fn with_master_key<T>(value: Option<&str>, check: impl FnOnce() -> T) -> T {
|
||||
let _guard = lock_sse_test_state().await;
|
||||
reset_sse_dek_provider();
|
||||
let outcome = with_vars([(ENV_SSE_S3_MASTER_KEY, value), ("__RUSTFS_SSE_SIMPLE_CMK", None)], check);
|
||||
reset_sse_dek_provider();
|
||||
outcome
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_absent_master_key_is_reported_as_not_set() {
|
||||
let status = with_master_key(None, load_local_master_key)
|
||||
.await
|
||||
.expect("an absent key is a state, not a failure");
|
||||
assert_eq!(status, LocalMasterKeyStatus::NotSet);
|
||||
|
||||
let blank = with_master_key(Some(" "), load_local_master_key)
|
||||
.await
|
||||
.expect("a blank value counts as absent");
|
||||
assert_eq!(blank, LocalMasterKeyStatus::NotSet);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_valid_master_key_is_loaded_and_cached_for_requests() {
|
||||
let encoded = BASE64_STANDARD.encode_to_string([7u8; 32]);
|
||||
let cached = with_master_key(Some(&encoded), || {
|
||||
let status = load_local_master_key().expect("a 32-byte key should load");
|
||||
assert_eq!(status, LocalMasterKeyStatus::Loaded);
|
||||
// The request path must find the provider startup loaded, not load a second one.
|
||||
crate::kms::provider::GLOBAL_SSE_DEK_PROVIDER
|
||||
.read()
|
||||
.expect("provider cache lock")
|
||||
.is_some()
|
||||
})
|
||||
.await;
|
||||
assert!(cached, "startup should leave the provider cached for the request path");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unusable_master_key_fails_the_way_a_request_would() {
|
||||
let short = BASE64_STANDARD.encode_to_string([7u8; 16]);
|
||||
for unusable in ["not base64 at all!", short.as_str()] {
|
||||
let error = with_master_key(Some(unusable), load_local_master_key)
|
||||
.await
|
||||
.expect_err("an unusable key must not load");
|
||||
assert_eq!(error.code, S3ErrorCode::InvalidRequest);
|
||||
assert!(
|
||||
!error.message.contains(unusable),
|
||||
"the failure text must not carry the configured value: {}",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn init_reports_once_and_repeats_the_same_report() {
|
||||
let encoded = BASE64_STANDARD.encode_to_string([9u8; 32]);
|
||||
let (first, second) = with_master_key(Some(&encoded), || (init(), init())).await;
|
||||
|
||||
assert_eq!(first, second, "a second call must return the first report");
|
||||
assert_eq!(first.key_policy_enforced, key_policy_enforced());
|
||||
// The report is settled once per process, so this holds whether this test
|
||||
// or another caller of `init` ran first.
|
||||
assert_eq!(init(), first);
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Fixtures for tests of SSE call sites, in this crate and in its dependents.
|
||||
|
||||
use crate::{KmsKeyAuthorizer, SseError, SseKmsPrincipal};
|
||||
use async_trait::async_trait;
|
||||
use base64_simd::STANDARD as BASE64_STANDARD;
|
||||
use rustfs_policy::policy::action::KmsAction;
|
||||
use rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS;
|
||||
use rustfs_utils::http::object_encryption_keys::{
|
||||
INTERNAL_ENCRYPTION_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER,
|
||||
INTERNAL_ENCRYPTION_KEY_ID_HEADER,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
/// An authorizer that answers every request the same way and records what it was asked.
|
||||
pub struct RecordingKmsKeyAuthorizer {
|
||||
allowed: bool,
|
||||
calls: Mutex<Vec<(KmsAction, String)>>,
|
||||
}
|
||||
|
||||
impl RecordingKmsKeyAuthorizer {
|
||||
pub fn new(allowed: bool) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
allowed,
|
||||
calls: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The `(action, key id)` pairs this authorizer was asked about, in order.
|
||||
pub fn calls(&self) -> Vec<(KmsAction, String)> {
|
||||
self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl KmsKeyAuthorizer for RecordingKmsKeyAuthorizer {
|
||||
async fn is_allowed(&self, _principal: &SseKmsPrincipal, action: KmsAction, key_id: &str) -> Result<bool, SseError> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push((action, key_id.to_string()));
|
||||
Ok(self.allowed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stored metadata of an SSE-KMS object wrapped under the key `finance-key`.
|
||||
pub fn sse_kms_object_metadata() -> HashMap<String, String> {
|
||||
HashMap::from([
|
||||
("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_KMS.to_string()),
|
||||
("x-amz-server-side-encryption-aws-kms-key-id".to_string(), "finance-key".to_string()),
|
||||
(INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "finance-key".to_string()),
|
||||
(INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string([7u8; 48])),
|
||||
(INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([9u8; 12])),
|
||||
(INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), "aws:kms".to_string()),
|
||||
])
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -30,11 +30,9 @@ Contract crates stay below implementation crates. Forbidden edges:
|
||||
| `security-governance -> rustfs` | Governance contracts stay below the binary crate |
|
||||
| `extension-schema -> rustfs` | The extension schema is consumed by the binary, never the reverse |
|
||||
| `extension-schema -> ecstore` | The extension schema must not reach storage internals |
|
||||
| `sse -> ecstore`, `sse -> iam`, `sse -> rustfs` | SSE key resolution reaches the running server only through its `SseHost` port |
|
||||
|
||||
- `rustfs-storage-api` exposes storage-facing replication status/state contracts only through `crates/storage-api/src/replication.rs`, so its temporary dependency on `rustfs-filemeta` wire types stays centralized and no `rustfs-replication` / `rustfs-storage-api` cycle appears.
|
||||
- Leaf crates (`config`, `credentials`, `crypto`, `io-metrics`, `madmin`) may not depend on other `rustfs-*` crates, in either TOML spelling, except the adjudicated edges pinned in the guard's leaf allowlist: `io-metrics -> rustfs-s3-ops` (pure contract crates sharing the `S3Operation` vocabulary) and `madmin -> rustfs-signer` (the SigV4-signed admin SDK client). A new leaf exception must be a pure contract dependency (types and enums only, no I/O, no globals, no non-contract internal dependencies) and land together with its allowlist entry.
|
||||
- `rustfs-sse` sits between the S3 layer and the storage engine and depends on neither. Its internal dependencies are pinned in the same guard to `rustfs-config`, `rustfs-kms`, `rustfs-policy`, `rustfs-s3-types`, and `rustfs-utils`; the KMS service, a bucket's default encryption, and key-permission decisions arrive through `rustfs_sse::SseHost`, which `rustfs/src/storage/sse.rs` implements. That file also owns every translation across the engine boundary (`ObjectEncryptionResolver`, `WriteEncryption`, `MultipartCompletionAuthorization`), so neither side names the other's types.
|
||||
- Compile-time source reads follow the same direction: `include_str!` / `include!` of a `.rs` file must not resolve outside the including crate (`scripts/check_layer_dependencies.sh`). Shared source-text expectations belong in a contract surface such as `rustfs_protos::compat_manifest` (`crates/protos/src/compat_manifest.rs`) and are asserted by each owning crate.
|
||||
|
||||
## ECStore Access Boundary
|
||||
|
||||
@@ -47,7 +47,7 @@ RustFS-side statics that matter architecturally because other modules are tempte
|
||||
| `KEYSTONE_AUTH`, `KEYSTONE_MAPPER`, `KEYSTONE_CONFIG` | `rustfs/src/auth_keystone.rs` | Keystone provider, mapper, and config stay private to the Keystone owner. |
|
||||
| `DEADLOCK_DETECTOR` | `rustfs/src/storage/deadlock_detector.rs` | Detector lifecycle stays private to the storage deadlock detector. |
|
||||
| `CONCURRENCY_MANAGER` | `rustfs/src/storage/concurrency/manager.rs` | Storage concurrency scheduler state stays inside the concurrency owner. |
|
||||
| `GLOBAL_KMS_DEK_PROVIDER`, `GLOBAL_SSE_DEK_PROVIDER` | `crates/sse/src/kms/provider.rs` | DEK provider caches stay private to the SSE owner. |
|
||||
| `GLOBAL_KMS_DEK_PROVIDER`, `GLOBAL_SSE_DEK_PROVIDER` | `rustfs/src/storage/sse.rs` | DEK provider caches stay private to the SSE owner. |
|
||||
| `ECSTORE_EVENT_DISPATCH_HOOK` | `rustfs/src/server/event.rs` | Event bridge registration goes through the storage facade. |
|
||||
| `AUDIT_MODULE_ENABLED`, `NOTIFY_MODULE_ENABLED` | `rustfs/src/module_switches.rs` | Module toggles are read through module-switch helpers; `MODULE_SWITCH_RMW_LOCK` (`rustfs/src/server/module_switch.rs`) serializes persisted updates. |
|
||||
| `RUNTIME_CONFIG_RELOAD_MUTEX` | `rustfs/src/admin/service/config.rs` | Serializes dynamic config reload fanout. |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# KMS Bulk Rekey Job Contract
|
||||
|
||||
**Use this when:** changing the bulk envelope re-wrap sweep (`rustfs/src/kms_rekey.rs`), its admin endpoints (`rustfs/src/admin/handlers/kms_rekey.rs`), the re-wrap primitive, or anything that decides which objects a rekey may touch.
|
||||
**Source of truth:** `rustfs/src/kms_rekey.rs`, `rustfs/src/admin/handlers/kms_rekey.rs`, `rewrap_object_encryption_metadata` in `crates/sse/src/core/rewrap.rs`, `KmsManager::rewrap_data_key` / `KmsManager::describe_data_key_wrapping` in `crates/kms/src/manager.rs`, `put_object_metadata` in `crates/ecstore/src/set_disk/ops/object.rs`.
|
||||
**Source of truth:** `rustfs/src/kms_rekey.rs`, `rustfs/src/admin/handlers/kms_rekey.rs`, `rewrap_object_encryption_metadata` in `rustfs/src/storage/sse.rs`, `KmsManager::rewrap_data_key` / `KmsManager::describe_data_key_wrapping` in `crates/kms/src/manager.rs`, `put_object_metadata` in `crates/ecstore/src/set_disk/ops/object.rs`.
|
||||
|
||||
The bulk rekey job re-wraps stored data-key envelopes under the current key-encryption key (KEK) without rewriting object bodies. This document is the acceptance bar; where the shipped v1 sweep deliberately narrows it, [Implementation Status](#implementation-status-v1-sweep) records the deviation.
|
||||
|
||||
@@ -52,7 +52,7 @@ Idempotency comes from object metadata itself: the envelope's state is the targe
|
||||
|
||||
### Reading the wrapping KEK version
|
||||
|
||||
There is no key-version metadata key. Object metadata carries the key id (`x-rustfs-encryption-key-id`) and the sealed blob under `x-rustfs-encryption-key`; `DecryptResponse` in `crates/kms/src/types.rs` does not report a version either. The version is recoverable because the sealed blob is structured: for every backend that builds one, the ciphertext is the JSON of `DataKeyEnvelope` (`crates/kms/src/encryption/dek.rs`), and the read path already discriminates on it via `is_data_key_envelope` in `crates/sse/src/core/read.rs`.
|
||||
There is no key-version metadata key. Object metadata carries the key id (`x-rustfs-encryption-key-id`) and the sealed blob under `x-rustfs-encryption-key`; `DecryptResponse` in `crates/kms/src/types.rs` does not report a version either. The version is recoverable because the sealed blob is structured: for every backend that builds one, the ciphertext is the JSON of `DataKeyEnvelope` (`crates/kms/src/encryption/dek.rs`), and the read path already discriminates on it via `is_data_key_envelope` in `rustfs/src/storage/sse.rs`.
|
||||
|
||||
| Backend | Rotates | Where the wrapping version lives | Recoverable by a scan |
|
||||
|---|---|---|---|
|
||||
@@ -95,7 +95,7 @@ Replication destinations are unresolved: propagation depends on `rustfs/backlog#
|
||||
|
||||
Three properties of `put_object_metadata` (`crates/ecstore/src/set_disk/ops/object.rs`) constrain the re-wrap write:
|
||||
|
||||
- **The merge is additive; it cannot remove keys.** Overwriting a key that keeps its name is safe; a re-wrap that changes *which* keys describe the envelope leaves the old keys behind. This is a live hazard: `parse_minio_managed_sealed_key` in `crates/sse/src/core/keying/object.rs` selects the MinIO decrypt branch on the mere presence of the MinIO seal-algorithm header, so a RustFS-native envelope written onto MinIO-compatible headers without neutralizing them steers reads down the stale branch. Any envelope-shape change must neutralize superseded keys in the same write.
|
||||
- **The merge is additive; it cannot remove keys.** Overwriting a key that keeps its name is safe; a re-wrap that changes *which* keys describe the envelope leaves the old keys behind. This is a live hazard: `parse_minio_managed_sealed_key` in `rustfs/src/storage/sse.rs` selects the MinIO decrypt branch on the mere presence of the MinIO seal-algorithm header, so a RustFS-native envelope written onto MinIO-compatible headers without neutralizing them steers reads down the stale branch. Any envelope-shape change must neutralize superseded keys in the same write.
|
||||
- **Object-lock retention is enforced before the merge.** `check_object_lock_retention_update` (`crates/ecstore/src/set_disk/mod.rs`) runs first; rekey inherits its decision and must not acquire a bypass.
|
||||
- **`mod_time` is preserved unless the caller sets it.** The re-wrap path leaves it unset so age-based lifecycle rules are not perturbed.
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# MinIO On-Disk Format Interoperability
|
||||
|
||||
**Use this when:** deciding whether a MinIO drive set, bucket-metadata blob, or SSE object can be read or imported by a given RustFS build, or before touching any constant or codec listed under Version Anchors.
|
||||
**Source of truth:** `crates/filemeta/src/filemeta.rs`, `crates/filemeta/src/filemeta/codec.rs`, `crates/ecstore/src/bucket/metadata.rs`, `crates/ecstore/src/bucket/migration.rs`, `crates/sse/src/core/`, `crates/sse/src/kms/`, `rustfs/Cargo.toml` `[features]`, `.github/workflows/ci.yml`, `.github/workflows/minio-interop.yml`.
|
||||
**Source of truth:** `crates/filemeta/src/filemeta.rs`, `crates/filemeta/src/filemeta/codec.rs`, `crates/ecstore/src/bucket/metadata.rs`, `crates/ecstore/src/bucket/migration.rs`, `rustfs/src/storage/sse.rs`, `rustfs/Cargo.toml` `[features]`, `.github/workflows/ci.yml`, `.github/workflows/minio-interop.yml`.
|
||||
|
||||
This is an interop contract, not a plan. Migration is one-way (MinIO to RustFS). Erasure-coding internals are owned by [erasure-coding.md](erasure-coding.md); this document owns the interop claim, the fixture evidence, and the out-of-scope list.
|
||||
|
||||
## Scope Matrix By Build Variant
|
||||
|
||||
Build variants are the `rustfs` crate features in `rustfs/Cargo.toml`: `default`, `full`, and `rio-v2` (which enables `rustfs-ecstore/rio-v2` and `rustfs-sse/rio-v2`, and pulls in `crates/rio-v2`). `rio-v2` is absent from both `default` and `full`.
|
||||
Build variants are the `rustfs` crate features in `rustfs/Cargo.toml`: `default`, `full`, and `rio-v2` (which enables `rustfs-ecstore/rio-v2` and pulls in `crates/rio-v2`). `rio-v2` is absent from both `default` and `full`.
|
||||
|
||||
| MinIO artifact | `default` / `full` build | `rio-v2` build | Notes |
|
||||
|---|:--:|:--:|---|
|
||||
@@ -81,7 +81,7 @@ The `xl.meta` around a MinIO SSE object parses in every build, so such objects l
|
||||
|
||||
### Seams
|
||||
|
||||
The cryptography (DARE v2 stream format, object-key derivation, sealing) was never the gap. Three metadata seams above it rejected MinIO objects; all are closed in `rio-v2` builds. Symbols are under `crates/sse/src/core/` unless noted.
|
||||
The cryptography (DARE v2 stream format, object-key derivation, sealing) was never the gap. Three metadata seams above it rejected MinIO objects; all are closed in `rio-v2` builds. Symbols are in `rustfs/src/storage/sse.rs` unless noted.
|
||||
|
||||
| Seam | Resolution |
|
||||
|---|---|
|
||||
@@ -113,10 +113,10 @@ Inventory the source first: bucket default encryption means objects can be encry
|
||||
| Fact | Value |
|
||||
|---|---|
|
||||
| Shipping status | Ships in no default build: absent from `default` and `full` in `rustfs/Cargo.toml`; released binaries and container images never include it. Enable with `--features rio-v2`. |
|
||||
| Pull-request coverage | `test-and-lint-rio-v2` in `.github/workflows/ci.yml`: clippy plus `cargo nextest` for `rustfs`, `rustfs-ecstore`, and `rustfs-sse` with `--features rio-v2`. This is the cfg-seam guard; it keeps the feature compiling and its unit suite green on every pull request. |
|
||||
| Pull-request coverage | `test-and-lint-rio-v2` in `.github/workflows/ci.yml`: clippy plus `cargo nextest` for `rustfs` and `rustfs-ecstore` with `--features rio-v2`. This is the cfg-seam guard; it keeps the feature compiling and its unit suite green on every pull request. |
|
||||
| Full-suite lane | `build-rustfs-debug-binary-rio-v2` and `e2e-tests-rio-v2` in `ci.yml` run only on the nightly schedule and manual dispatch (`cache-warm.yml` keeps the `ci-feat-rio` cache warm so the scheduled build fits its timeout). |
|
||||
| Interop evidence | `.github/workflows/minio-interop.yml` (nightly plus manual) regenerates real MinIO backend trees via `crates/rio-v2/tests/minio_fixture_lab/` and runs the `#[ignore]` reader tests in `rustfs/src/storage/minio_generated_read_test.rs` with `--features rio-v2`. Its freshness is tracked in `.github/scheduled-validations.json`. |
|
||||
| Promote-or-delete condition | The variant stays dormant until one of two things happens. **Promote**: a release commits to shipping MinIO SSE migration as a supported capability; then `rio-v2` joins `default`/`full`, the scheduled lanes run on every pull request, and this section is rewritten. **Delete**: no release commits to it and the scheduled lanes are not kept green; then the feature flag, `crates/rio-v2`, the cfg seams under `crates/sse/src/`, the three `ci.yml` jobs, the `cache-warm.yml` warm step, `minio-interop.yml`, and its `scheduled-validations.json` entry are removed in one change. Either outcome must update `ARCHITECTURE.md` and the `ci.yml` job comments that cite this section. |
|
||||
| Promote-or-delete condition | The variant stays dormant until one of two things happens. **Promote**: a release commits to shipping MinIO SSE migration as a supported capability; then `rio-v2` joins `default`/`full`, the scheduled lanes run on every pull request, and this section is rewritten. **Delete**: no release commits to it and the scheduled lanes are not kept green; then the feature flag, `crates/rio-v2`, the cfg seams in `rustfs/src/storage/sse.rs`, the three `ci.yml` jobs, the `cache-warm.yml` warm step, `minio-interop.yml`, and its `scheduled-validations.json` entry are removed in one change. Either outcome must update `ARCHITECTURE.md` and the `ci.yml` job comments that cite this section. |
|
||||
|
||||
## Fixture Evidence
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# AWS KMS backend: setup, verification, and operations
|
||||
|
||||
**Use this when:** connecting RustFS to AWS KMS for the first time, verifying an existing AWS-backed deployment, upgrading one from 1.0.4 or 1.0.5, or deciding how to run and protect the AWS keys RustFS depends on.
|
||||
**Source of truth:** `crates/kms/src/backends/aws.rs` (backend behavior and its deviations), `crates/kms/src/config.rs` (`ENV_KMS_AWS_*`), `crates/kms/src/policy.rs` (retry, deadline and circuit breaker), `crates/sse/src/core/` (SSE data path). 中文版: [kms-aws-backend-guide.zh-CN.md](kms-aws-backend-guide.zh-CN.md).
|
||||
**Source of truth:** `crates/kms/src/backends/aws.rs` (backend behavior and its deviations), `crates/kms/src/config.rs` (`ENV_KMS_AWS_*`), `crates/kms/src/policy.rs` (retry, deadline and circuit breaker), `rustfs/src/storage/sse.rs` (SSE data path). 中文版: [kms-aws-backend-guide.zh-CN.md](kms-aws-backend-guide.zh-CN.md).
|
||||
|
||||
The statements about behavior on this page were observed against the real AWS KMS service (region `eu-north-1`) and, for failures AWS cannot be asked to produce on demand, against a loopback stand-in that speaks the AWS KMS wire protocol. Where a statement is guidance that was not exercised, it says so. For the contract-level differences between AWS and the other backends, see [KMS backend security properties](kms-backend-security.md#aws-kms-deviations-from-the-shared-backend-contract).
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# AWS KMS 后端:接入、验证与运维
|
||||
|
||||
**适用场景:** 首次把 RustFS 接入 AWS KMS、验证已有的 AWS 后端部署、从 1.0.4 或 1.0.5 升级,或者规划如何运维并保护 RustFS 所依赖的 AWS 密钥。
|
||||
**事实来源:** `crates/kms/src/backends/aws.rs`(后端行为及其差异)、`crates/kms/src/config.rs`(`ENV_KMS_AWS_*`)、`crates/kms/src/policy.rs`(重试、超时与熔断)、`crates/sse/src/core/`(SSE 数据面)。English: [kms-aws-backend-guide.md](kms-aws-backend-guide.md)。
|
||||
**事实来源:** `crates/kms/src/backends/aws.rs`(后端行为及其差异)、`crates/kms/src/config.rs`(`ENV_KMS_AWS_*`)、`crates/kms/src/policy.rs`(重试、超时与熔断)、`rustfs/src/storage/sse.rs`(SSE 数据面)。English: [kms-aws-backend-guide.md](kms-aws-backend-guide.md)。
|
||||
|
||||
本页关于行为的描述,均来自对真实 AWS KMS 服务(区域 `eu-north-1`)的实测;对于无法让 AWS 按需产生的故障,则使用一个实现了 AWS KMS 线上协议的本机替身来实测。属于未经实测的建议之处,文中会明确标注。AWS 与其它后端在契约层面的差异,见 [KMS backend security properties](kms-backend-security.md#aws-kms-deviations-from-the-shared-backend-contract)。
|
||||
|
||||
|
||||
@@ -46,3 +46,15 @@ The companion [auto-testing scanner usage suite](https://github.com/rustfs/auto-
|
||||
`GET /rustfs/admin/v3/realtime?scope=cluster&types=1&n=1` returns one NDJSON frame containing `cluster_scanner` and `final: true` under the existing realtime metrics permission. `nodes_responded` counts configured members that supplied a supported sample. Compare it with `nodes_total`. `sampled_at` identifies the observation time, including when concurrent refreshes share the result. Scanning requires an active coordinator whose epoch and cycle match the durable scanner record. Idle requires complete coverage and an identified coordinator. Missing or contradictory evidence gives `unknown`. The optional `current`, `last_attempt` and `last_success_at` fields distinguish work in progress, a completed attempt (which may be partial), and a successful cycle. An interrupted worker records its budget reason, lost leadership or cancellation even when the drain deadline prevents completion. Successful completion time comes only from persisted cycle history. The current cycle's object count measures work performed during that cycle.
|
||||
|
||||
Older servers can ignore the query and return their ordinary response. Check for `inventory` or `cluster_scanner` before interpreting the corresponding response as the new contract.
|
||||
|
||||
## Console bucket scan progress
|
||||
|
||||
`GET /rustfs/admin/v3/accountinfo` may attach `scan_progress` to each authorized bucket. Its `objects` and `size` describe accepted scanned coverage, not the bucket total, a lower bound on current contents, or a percentage. Concurrent changes can invalidate any such comparison. `stage` distinguishes `enumerating`, `scanning`, `awaiting_sources` and `completed`; completion means all logical sources supplied a completed traversal sample, without granting a usage certificate. Enumeration alone leaves both counters absent. `sources_observed` and `sources_total` make missing sets explicit. `updated_at` is the oldest contributing measurement time in Unix milliseconds. Saving an unchanged frontier or retained compacted receipt, including after a cold executor handoff, does not refresh that time. Legacy receipts without measurement metadata remain reusable for scanning but cannot supply a new numeric display sample with a fabricated age.
|
||||
|
||||
The scanner saves compact progress companions on their contributing erasure sets after committing bucket checkpoints. Retries replace a sample instead of adding deltas, and physical replicas are alternative views of one logical source. A new executor that has not yet measured another range retains the prior accepted sample and its original timestamp. Reader-local admission epochs and wakeup counters never fence a shared diagnostic sample; its movement scope comes from persisted pool/rebalance metadata. Missing, unsupported or corrupt companions do not affect checkpoint recovery or complete usage. Admin reads bind companions to the current bucket incarnation, set layout and durable movement generation, use bounded concurrent reads, and never list S3 objects or load the full checkpoint graph. The response keeps existing `objects` and `size` fields independent; Console retains their prior values and shows scan progress separately. Optional `usage_updated_at` preserves the original bucket certificate time, independently of the progress timestamp. Older servers and clients can omit or ignore these additive fields.
|
||||
|
||||
The two-second Admin read budget reserves its final quarter for movement-scope validation. Each validated source contributes immediately, so a stalled source or another bucket's identity lookup cannot erase completed reads. A bucket with missing sources reports `awaiting_sources`; unavailable final scope validation still omits the diagnostic view.
|
||||
|
||||
Progress extraction shares the checkpoint's serialized buffers, including paged payloads, with at most one dedicated CPU worker per process. It releases movement admission after capturing the durable generation and leaves native I/O workers available for primary saves. Waiting for the worker and preparing its input are included in the two-second diagnostic preparation budget; cancellation is checked during decoding. A nonpreemptible validation may finish after its waiter expires, retaining one decoded checkpoint until it exits. Its resource permit remains held, preventing repeated saves from accumulating workers or decoded copies, and its expired result is not published. Primary and companion publication retain their existing epoch and revision checks; scanner cycle budgets are unchanged.
|
||||
|
||||
The adaptive best-effort backup budget covers preparation, manifest publication, reconciliation and page reclamation together. Exhausting it stops waiting for the backup without undoing a successful primary checkpoint. An uncertain backup outcome can be recovered from storage on a later turn; it does not extend the current turn's budget.
|
||||
|
||||
+1
-3
@@ -80,7 +80,7 @@ e2e-test-hooks = ["rustfs-ecstore/e2e-test-hooks", "rustfs-scanner/e2e-test-hook
|
||||
connect-e2e-short-credentials = []
|
||||
# Builds the dedicated rustfs-cli-e2e target with a build-time public enrollment root.
|
||||
offline-enrollment-e2e-root = []
|
||||
rio-v2 = ["rustfs-ecstore/rio-v2", "rustfs-sse/rio-v2"]
|
||||
rio-v2 = ["rustfs-ecstore/rio-v2"]
|
||||
# Linux-only cuObject S3-over-RDMA GET into client (GPU) memory; needs libcuobjserver.
|
||||
cuobject = ["dep:rustfs-cuobject", "rustfs-cuobject/server"]
|
||||
# NIXL/UCX transport for S3-over-RDMA; replaces cuobject when both are enabled.
|
||||
@@ -281,7 +281,6 @@ rustfs-rio = { workspace = true }
|
||||
rustfs-s3-client = { workspace = true }
|
||||
rustfs-s3-types = { workspace = true, features = ["compat-s3s"] }
|
||||
rustfs-s3-ops = { workspace = true }
|
||||
rustfs-sse = { workspace = true }
|
||||
rustfs-security-governance = { workspace = true }
|
||||
rustfs-data-usage = { workspace = true }
|
||||
rustfs-s3select-api = { workspace = true }
|
||||
@@ -425,7 +424,6 @@ h2.workspace = true
|
||||
rustfs-targets = { workspace = true, features = ["test-support"] }
|
||||
uuid = { workspace = true, features = ["v4", "v5", "fast-rng", "macro-diagnostics"] }
|
||||
rustfs-iam = { workspace = true, features = ["test-util"] }
|
||||
rustfs-sse = { workspace = true, features = ["test-util"] }
|
||||
serial_test = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
aws-config = { workspace = true }
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::admin::service::caller_identity::oidc_profile_fields;
|
||||
use crate::admin::storage_api::bucket::versioning_sys::BucketVersioningSys;
|
||||
use crate::admin::storage_api::contract::admin::StorageAdminApi;
|
||||
use crate::admin::storage_api::contract::bucket::{BucketOperations, BucketOptions};
|
||||
use crate::admin::storage_api::data_usage::load_admin_data_usage_with_memory_overlay;
|
||||
use crate::admin::storage_api::data_usage::{load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin};
|
||||
use crate::admin::storage_api::metadata_sys;
|
||||
use crate::auth::get_condition_values;
|
||||
use crate::server::ADMIN_PREFIX;
|
||||
@@ -28,7 +28,7 @@ use http::header::CONTENT_TYPE;
|
||||
use http::{HeaderMap, HeaderValue};
|
||||
use hyper::{Method, StatusCode};
|
||||
use matchit::Params;
|
||||
use rustfs_data_usage::{BucketUsageInfo, DataUsageInfo};
|
||||
use rustfs_data_usage::{BucketScanStage, BucketUsageInfo, BucketUsageValueState, DataUsageInfo};
|
||||
use rustfs_gateway_types::dto::Status;
|
||||
use rustfs_gateway_types::persistence::PersistedObjectLockConfiguration as ObjectLockConfiguration;
|
||||
use rustfs_gateway_types::persistence::PersistedReplicationConfiguration;
|
||||
@@ -89,10 +89,46 @@ fn apply_usage_to_bucket_access_info(bucket_info: &mut rustfs_madmin::BucketAcce
|
||||
|
||||
bucket_info.size = Some(usage.size);
|
||||
bucket_info.objects = Some(usage.objects_count);
|
||||
bucket_info.usage_value_state = usage.usage_value_state.map(|state| {
|
||||
match state {
|
||||
BucketUsageValueState::Certified => "certified",
|
||||
BucketUsageValueState::Carried => "carried",
|
||||
BucketUsageValueState::Observed => "observed",
|
||||
BucketUsageValueState::Unknown => "unknown",
|
||||
}
|
||||
.to_owned()
|
||||
});
|
||||
bucket_info.usage_updated_at = usage.usage_certification.and_then(|certificate| {
|
||||
u64::try_from(
|
||||
certificate
|
||||
.certified_at
|
||||
.duration_since(std::time::SystemTime::UNIX_EPOCH)
|
||||
.ok()?
|
||||
.as_millis(),
|
||||
)
|
||||
.ok()
|
||||
});
|
||||
bucket_info.object_sizes_histogram = Some(usage.object_size_histogram.clone());
|
||||
bucket_info.object_versions_histogram = Some(usage.object_versions_histogram.clone());
|
||||
}
|
||||
|
||||
fn bucket_scan_progress_response(progress: rustfs_data_usage::BucketScanProgress) -> rustfs_madmin::BucketScanProgress {
|
||||
let stage = match progress.stage {
|
||||
BucketScanStage::Enumerating => "enumerating",
|
||||
BucketScanStage::Scanning => "scanning",
|
||||
BucketScanStage::AwaitingSources => "awaiting_sources",
|
||||
BucketScanStage::Completed => "completed",
|
||||
};
|
||||
rustfs_madmin::BucketScanProgress {
|
||||
stage: stage.to_owned(),
|
||||
updated_at: progress.updated_at,
|
||||
objects: progress.objects,
|
||||
size: progress.size,
|
||||
sources_observed: progress.sources_observed,
|
||||
sources_total: progress.sources_total,
|
||||
}
|
||||
}
|
||||
|
||||
fn object_lock_config_enabled(config: &ObjectLockConfiguration) -> bool {
|
||||
config
|
||||
.object_lock_enabled
|
||||
@@ -301,13 +337,21 @@ impl Operation for AccountInfoHandler {
|
||||
}
|
||||
}
|
||||
|
||||
let allowed = account_info.buckets.iter().map(|bucket| bucket.name.clone()).collect();
|
||||
let measured =
|
||||
crate::admin::storage_api::data_usage::verified_account_bucket_usage(store, data_usage_info.buckets_usage, allowed)
|
||||
.await;
|
||||
let visible_buckets = account_info
|
||||
.buckets
|
||||
.iter()
|
||||
.map(|bucket| bucket.name.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut progress = load_bucket_scan_progress_for_admin(store.clone(), &visible_buckets, &data_usage_info).await;
|
||||
let measured = crate::admin::storage_api::data_usage::verified_account_bucket_usage(
|
||||
store,
|
||||
data_usage_info.buckets_usage,
|
||||
visible_buckets,
|
||||
)
|
||||
.await;
|
||||
for bucket in &mut account_info.buckets {
|
||||
let usage = measured.get(&bucket.name);
|
||||
apply_usage_to_bucket_access_info(bucket, usage);
|
||||
apply_usage_to_bucket_access_info(bucket, measured.get(&bucket.name));
|
||||
bucket.scan_progress = progress.remove(&bucket.name).map(bucket_scan_progress_response);
|
||||
}
|
||||
|
||||
let data = serde_json::to_vec(&AccountInfoResponse {
|
||||
@@ -422,6 +466,85 @@ mod tests {
|
||||
assert_eq!(bucket_info.object_versions_histogram, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accountinfo_partial_progress_never_fills_total_usage_fields() {
|
||||
let mut bucket_info = rustfs_madmin::BucketAccessInfo {
|
||||
name: "scanning".into(),
|
||||
scan_progress: Some(bucket_scan_progress_response(rustfs_data_usage::BucketScanProgress {
|
||||
stage: rustfs_data_usage::BucketScanStage::Scanning,
|
||||
updated_at: 1000,
|
||||
objects: Some(7),
|
||||
size: Some(71),
|
||||
sources_observed: 1,
|
||||
sources_total: 2,
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
apply_usage_to_bucket_access_info(&mut bucket_info, None);
|
||||
let value = serde_json::to_value(&bucket_info).expect("serialize partial-only bucket");
|
||||
assert!(value.get("objects").is_none());
|
||||
assert!(value.get("size").is_none());
|
||||
assert_eq!(value["scan_progress"]["objects"], 7);
|
||||
assert_eq!(value["scan_progress"]["size"], 71);
|
||||
let mut usage = BucketUsageInfo {
|
||||
size: 900,
|
||||
objects_count: 90,
|
||||
..Default::default()
|
||||
};
|
||||
usage.certify(rustfs_data_usage::BucketUsageCertification {
|
||||
epoch: 1,
|
||||
cycle: 2,
|
||||
certified_at: std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(500),
|
||||
});
|
||||
apply_usage_to_bucket_access_info(&mut bucket_info, Some(&usage));
|
||||
assert_eq!((bucket_info.objects, bucket_info.size), (Some(90), Some(900)));
|
||||
assert_eq!(bucket_info.usage_updated_at, Some(500));
|
||||
assert_eq!(bucket_info.scan_progress.expect("separate partial view").objects, Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accountinfo_scan_progress_projection_preserves_wire_contract() {
|
||||
for (stage, objects, size, sources_observed) in [
|
||||
(BucketScanStage::Enumerating, None, None, 2),
|
||||
(BucketScanStage::Scanning, Some(7), Some(71), 2),
|
||||
(BucketScanStage::AwaitingSources, Some(0), Some(0), 1),
|
||||
(BucketScanStage::Completed, Some(7), Some(71), 2),
|
||||
] {
|
||||
let progress = rustfs_data_usage::BucketScanProgress {
|
||||
stage,
|
||||
updated_at: 1000,
|
||||
objects,
|
||||
size,
|
||||
sources_observed,
|
||||
sources_total: 2,
|
||||
};
|
||||
let expected = serde_json::to_value(&progress).expect("domain progress wire contract");
|
||||
let response = bucket_scan_progress_response(progress);
|
||||
assert_eq!(serde_json::to_value(response).expect("SDK progress response"), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accountinfo_usage_provenance_projection_preserves_wire_contract() {
|
||||
for state in [
|
||||
BucketUsageValueState::Certified,
|
||||
BucketUsageValueState::Carried,
|
||||
BucketUsageValueState::Observed,
|
||||
BucketUsageValueState::Unknown,
|
||||
] {
|
||||
let usage = BucketUsageInfo {
|
||||
usage_value_state: Some(state),
|
||||
..Default::default()
|
||||
};
|
||||
let mut bucket = rustfs_madmin::BucketAccessInfo::default();
|
||||
apply_usage_to_bucket_access_info(&mut bucket, Some(&usage));
|
||||
assert_eq!(
|
||||
serde_json::to_value(bucket).expect("SDK usage provenance")["usage_value_state"],
|
||||
serde_json::to_value(state).expect("domain provenance wire contract")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accountinfo_data_usage_error_message_is_generic() {
|
||||
let err = map_data_usage_result::<&str>(Err("sensitive disk path")).expect_err("load failure must reach the response");
|
||||
|
||||
@@ -1263,8 +1263,7 @@ mod tests {
|
||||
req.extensions.insert(slot.clone());
|
||||
req.extensions.insert(ReqInfo::default());
|
||||
req.headers.insert(http::header::IF_NONE_MATCH, HeaderValue::from_static("*"));
|
||||
let result =
|
||||
authorized_object_lambda_get_request(&object_lambda_test_envelope(&req), &bucket, "object").await;
|
||||
let result = authorized_object_lambda_get_request(&RequestEnvelope::from_s3s(&req), &bucket, "object").await;
|
||||
// Version-only Allow covers current reads; Version Deny overrides
|
||||
// the explicit current-read Allow as well as version grants.
|
||||
if deny_versions || (version.is_some() && !grant_versions) {
|
||||
@@ -1299,21 +1298,6 @@ mod tests {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
/// Method, URI, headers, and extensions. These fixtures leave credentials, region, and service absent.
|
||||
fn object_lambda_test_envelope(req: &S3Request<Body>) -> RequestEnvelope {
|
||||
RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: req.method.clone(),
|
||||
uri: req.uri.clone(),
|
||||
headers: req.headers.clone(),
|
||||
credentials: None,
|
||||
region: None,
|
||||
service: None,
|
||||
},
|
||||
req.extensions.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct StaticResolver(IpAddr);
|
||||
|
||||
@@ -2126,7 +2110,7 @@ mod tests {
|
||||
};
|
||||
|
||||
let payload = build_object_lambda_event_payload(
|
||||
&object_lambda_test_envelope(&req),
|
||||
&RequestEnvelope::from_s3s(&req),
|
||||
"arn:acme:s3-object-lambda::transformer:webhook",
|
||||
"https://example.com/source",
|
||||
"route-123",
|
||||
@@ -2437,7 +2421,7 @@ mod tests {
|
||||
req.headers
|
||||
.insert(http::header::IF_MATCH, HeaderValue::from_static("\"abc\""));
|
||||
|
||||
let (uri, input) = build_object_lambda_get_request(&object_lambda_test_envelope(&req), "demo-bucket", "object.txt")
|
||||
let (uri, input) = build_object_lambda_get_request(&RequestEnvelope::from_s3s(&req), "demo-bucket", "object.txt")
|
||||
.expect("bridge request should build");
|
||||
|
||||
assert_eq!(uri.path(), "/demo-bucket/object.txt");
|
||||
@@ -2449,7 +2433,7 @@ mod tests {
|
||||
assert_eq!(input.range, Some(rustfs_gateway_types::ByteRange::FromTo { first: 5, last: 10 }));
|
||||
req.headers
|
||||
.insert(http::header::IF_MATCH, HeaderValue::from_static("invalid etag"));
|
||||
assert!(build_object_lambda_get_request(&object_lambda_test_envelope(&req), "demo-bucket", "object.txt").is_err());
|
||||
assert!(build_object_lambda_get_request(&RequestEnvelope::from_s3s(&req), "demo-bucket", "object.txt").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2470,7 +2454,7 @@ mod tests {
|
||||
req.headers
|
||||
.insert(http::header::RANGE, HeaderValue::from_static("bytes=10-5"));
|
||||
|
||||
let err = build_object_lambda_get_request(&object_lambda_test_envelope(&req), "demo-bucket", "object.txt")
|
||||
let err = build_object_lambda_get_request(&RequestEnvelope::from_s3s(&req), "demo-bucket", "object.txt")
|
||||
.err()
|
||||
.expect("invalid range must fail");
|
||||
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
|
||||
|
||||
@@ -946,6 +946,14 @@ pub(crate) mod data_usage {
|
||||
pub(crate) use crate::storage::storage_api::ecstore_data_usage::verified_account_bucket_usage;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) async fn load_bucket_scan_progress_for_admin(
|
||||
store: Arc<crate::storage::storage_api::ECStore>,
|
||||
buckets: &[String],
|
||||
baseline: &rustfs_data_usage::DataUsageInfo,
|
||||
) -> std::collections::HashMap<String, rustfs_data_usage::BucketScanProgress> {
|
||||
crate::storage::storage_api::ecstore_data_usage::load_bucket_scan_progress_for_admin(store, buckets, baseline).await
|
||||
}
|
||||
|
||||
pub(crate) async fn load_data_usage_from_backend(
|
||||
store: Arc<crate::storage::storage_api::ECStore>,
|
||||
) -> Result<rustfs_data_usage::DataUsageInfo, crate::storage::storage_api::StorageError> {
|
||||
|
||||
@@ -1185,18 +1185,7 @@ mod tests {
|
||||
service: None,
|
||||
trailing_headers: None,
|
||||
};
|
||||
// Method GET, URI `/missing`, empty headers, and empty extensions.
|
||||
let get_env = crate::app::RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: get.method.clone(),
|
||||
uri: get.uri.clone(),
|
||||
headers: get.headers.clone(),
|
||||
credentials: None,
|
||||
region: None,
|
||||
service: None,
|
||||
},
|
||||
get.extensions.clone(),
|
||||
);
|
||||
let get_env = crate::app::RequestEnvelope::from_s3s(&get);
|
||||
let authorized_generation =
|
||||
super::super::storage_api::bucket_usecase::access::load_bucket_generation_from_store(
|
||||
&store,
|
||||
@@ -1226,17 +1215,7 @@ mod tests {
|
||||
assert_ne!(replacement, old.incarnation_id());
|
||||
sys.remove(&input.bucket);
|
||||
let mut without_source = get.clone();
|
||||
let mut without_source_env = crate::app::RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: without_source.method.clone(),
|
||||
uri: without_source.uri.clone(),
|
||||
headers: without_source.headers.clone(),
|
||||
credentials: None,
|
||||
region: None,
|
||||
service: None,
|
||||
},
|
||||
without_source.extensions.clone(),
|
||||
);
|
||||
let mut without_source_env = crate::app::RequestEnvelope::from_s3s(&without_source);
|
||||
super::super::storage_api::bucket_usecase::access::prepare_odm_read_generation(
|
||||
&store,
|
||||
&mut without_source_env,
|
||||
|
||||
@@ -371,7 +371,7 @@ impl DefaultBucketUsecase {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::bucket_usecase::test_support::{owned_envelope, s3_op_total};
|
||||
use crate::app::bucket_usecase::test_support::{build_request_with_req_info, owned_envelope, s3_op_total};
|
||||
use http::Method;
|
||||
|
||||
#[test]
|
||||
@@ -403,24 +403,9 @@ mod tests {
|
||||
}
|
||||
|
||||
/// The envelope of a request whose access phase installed `req_info`, or none.
|
||||
/// Method PUT, URI `/`, empty headers, and that extension only.
|
||||
fn envelope(req_info: Option<ReqInfo>) -> RequestEnvelope {
|
||||
match req_info {
|
||||
Some(req_info) => {
|
||||
let mut extensions = http::Extensions::new();
|
||||
extensions.insert(req_info);
|
||||
RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: Method::PUT,
|
||||
uri: http::Uri::from_static("/"),
|
||||
headers: http::HeaderMap::new(),
|
||||
credentials: None,
|
||||
region: None,
|
||||
service: None,
|
||||
},
|
||||
extensions,
|
||||
)
|
||||
}
|
||||
Some(req_info) => RequestEnvelope::from_s3s(&build_request_with_req_info((), Method::PUT, req_info)),
|
||||
None => owned_envelope(Method::PUT),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ use super::storage_api::multipart_usecase::s3_api::multipart::{
|
||||
};
|
||||
use super::storage_api::multipart_usecase::set_disk::is_valid_storage_class;
|
||||
use super::storage_api::multipart_usecase::sse::{
|
||||
DecryptionRequest, EncryptionKeyKind, EncryptionRequest, PrepareEncryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt,
|
||||
DecryptionRequest, EncryptionKeyKind, EncryptionRequest, PrepareEncryptionRequest, SseKmsPrincipal,
|
||||
apply_bucket_default_lock_retention, authorize_sse_kms_multipart_write, authorize_sse_kms_object_read,
|
||||
build_ssec_read_headers, encryption_material_to_metadata, extract_server_side_encryption_from_headers,
|
||||
extract_ssec_params_from_headers, extract_ssekms_context_from_headers, get_buffer_size_opt_in,
|
||||
|
||||
@@ -515,21 +515,6 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::app::storage_api::s3::{S3ErrorCode, dto::CreateMultipartUploadInput};
|
||||
|
||||
/// Method, URI, headers, extensions, region, and service. These fixtures leave credentials absent.
|
||||
fn envelope_from_request<T>(req: &crate::app::storage_api::s3::S3Request<T>) -> RequestEnvelope {
|
||||
RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: req.method.clone(),
|
||||
uri: req.uri.clone(),
|
||||
headers: req.headers.clone(),
|
||||
credentials: None,
|
||||
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
|
||||
service: req.service.clone(),
|
||||
},
|
||||
req.extensions.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_multipart_baseline_legacy_direct() {
|
||||
use crate::app::storage_api::s3::dto::Timestamp;
|
||||
@@ -675,10 +660,7 @@ mod tests {
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let envelope = envelope_from_request(&request);
|
||||
let query_version = request.input.version_id.take();
|
||||
let fields = CreateMultipartUploadFields::from_legacy(request.input);
|
||||
let result = usecase.execute_create_multipart_upload(envelope, fields, query_version).await;
|
||||
let result = usecase.execute_create_multipart_upload_from_s3s(request).await;
|
||||
assert!(
|
||||
store
|
||||
.list_multipart_uploads(&bucket, "", None, None, None, 100)
|
||||
@@ -687,10 +669,7 @@ mod tests {
|
||||
.uploads
|
||||
.is_empty()
|
||||
);
|
||||
let err = match result {
|
||||
Err(error) => crate::app::storage_api::s3::S3Error::from(error),
|
||||
Ok(_) => panic!("quota-enabled ciphertext multipart replication must be refused"),
|
||||
};
|
||||
let err = result.expect_err("quota-enabled ciphertext multipart replication must be refused");
|
||||
assert_eq!(err.code(), &S3ErrorCode::InvalidRequest);
|
||||
assert_eq!(
|
||||
err.message(),
|
||||
@@ -741,10 +720,7 @@ mod tests {
|
||||
enforced: true,
|
||||
authorizer: authorizer.clone(),
|
||||
});
|
||||
let envelope = envelope_from_request(&req);
|
||||
let query_version = req.input.version_id.take();
|
||||
let fields = CreateMultipartUploadFields::from_legacy(req.input);
|
||||
let result = usecase.execute_create_multipart_upload(envelope, fields, query_version).await;
|
||||
let result = usecase.execute_create_multipart_upload_from_s3s(req).await;
|
||||
let uploads = store
|
||||
.list_multipart_uploads(&bucket, "", None, None, None, 100)
|
||||
.await
|
||||
@@ -753,15 +729,10 @@ mod tests {
|
||||
assert_eq!(uploads.len(), usize::from(allowed));
|
||||
assert_eq!(authorizer.calls(), [(KmsAction::GenerateDataKeyAction, key_id.to_owned())]);
|
||||
if allowed {
|
||||
let Ok(output) = result else {
|
||||
panic!("KMS authorizes the selected key");
|
||||
};
|
||||
assert_eq!(output.upload_id.as_str(), uploads[0].upload_id.as_str());
|
||||
let output = result.expect("KMS authorizes the selected key").output;
|
||||
assert_eq!(output.upload_id.as_deref(), Some(uploads[0].upload_id.as_str()));
|
||||
} else {
|
||||
let Err(error) = result else {
|
||||
panic!("KMS denied the selected key");
|
||||
};
|
||||
let error = crate::app::storage_api::s3::S3Error::from(error);
|
||||
let error = result.expect_err("KMS denied the selected key");
|
||||
assert_eq!(error.code(), &S3ErrorCode::AccessDenied);
|
||||
}
|
||||
}
|
||||
@@ -804,28 +775,16 @@ mod tests {
|
||||
assert!(slot.install(context));
|
||||
let bucket = format!("create-multipart-{}", Uuid::new_v4().simple());
|
||||
let other = format!("create-multipart-{}", Uuid::new_v4().simple());
|
||||
let make_request = |target_bucket: &str| {
|
||||
let mut input = CreateMultipartUploadInput {
|
||||
bucket: target_bucket.to_owned(),
|
||||
let request = |bucket: &str| {
|
||||
let input = CreateMultipartUploadInput {
|
||||
bucket: bucket.to_owned(),
|
||||
key: "object".to_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut extensions = Extensions::new();
|
||||
extensions.insert(slot.clone());
|
||||
let envelope = RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: Method::POST,
|
||||
uri: format!("/{target_bucket}/object?uploads").parse().expect("fixture URI"),
|
||||
headers: http::HeaderMap::new(),
|
||||
credentials: None,
|
||||
region: None,
|
||||
service: None,
|
||||
},
|
||||
extensions,
|
||||
);
|
||||
let query_version = input.version_id.take();
|
||||
let fields = CreateMultipartUploadFields::from_legacy(input);
|
||||
(envelope, fields, query_version)
|
||||
let mut request = build_request(input, Method::POST);
|
||||
request.uri = format!("/{bucket}/object?uploads").parse().expect("fixture URI");
|
||||
request.extensions.insert(slot.clone());
|
||||
request
|
||||
};
|
||||
for name in [&bucket, &other] {
|
||||
store
|
||||
@@ -834,6 +793,14 @@ mod tests {
|
||||
.expect("create bucket");
|
||||
}
|
||||
|
||||
let make_request = |target_bucket: &str| {
|
||||
let mut req = request(target_bucket);
|
||||
let envelope = RequestEnvelope::from_s3s(&req);
|
||||
let query_version = req.input.version_id.take();
|
||||
let fields = CreateMultipartUploadFields::from_legacy(req.input);
|
||||
(envelope, fields, query_version)
|
||||
};
|
||||
|
||||
let (mut stale_env, stale_fields, stale_ver) = make_request(&bucket);
|
||||
let guard = load_bucket_generation_from_store(&store, &stale_env, &bucket)
|
||||
.await
|
||||
|
||||
@@ -378,8 +378,7 @@ impl DefaultMultipartUsecase {
|
||||
content_size: actual_size,
|
||||
principal: None,
|
||||
}
|
||||
.validate_multipart_ssec(&fi.user_defined)
|
||||
.map_err(ApiError::from)?;
|
||||
.validate_multipart_ssec(&fi.user_defined)?;
|
||||
}
|
||||
let (requested_sse, requested_kms_key_id) = if has_ssec {
|
||||
let ssec_material = sse_decryption(DecryptionRequest {
|
||||
@@ -586,26 +585,11 @@ mod tests {
|
||||
use crate::app::storage_api::s3::dto::{StreamingBlob, UploadPartInput};
|
||||
use http::HeaderValue;
|
||||
|
||||
/// Method, URI, headers, extensions, region, and service. These fixtures leave credentials absent.
|
||||
fn envelope_from_presigned_fixture<T>(req: &crate::app::storage_api::s3::S3Request<T>) -> RequestEnvelope {
|
||||
RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: req.method.clone(),
|
||||
uri: req.uri.clone(),
|
||||
headers: req.headers.clone(),
|
||||
credentials: None,
|
||||
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
|
||||
service: req.service.clone(),
|
||||
},
|
||||
req.extensions.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
fn presigned_checksum_request(query: &str) -> (RequestEnvelope, UploadPartWriteInput) {
|
||||
let mut req = build_request(UploadPartInput::default(), Method::PUT);
|
||||
req.uri = format!("/bucket/object?{query}").parse().unwrap();
|
||||
req.extensions.insert(VerifiedPresignedRequest);
|
||||
(envelope_from_presigned_fixture(&req), UploadPartWriteInput::from_legacy(req.input, None))
|
||||
(RequestEnvelope::from_s3s(&req), UploadPartWriteInput::from_legacy(req.input, None))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -691,7 +675,7 @@ mod tests {
|
||||
fn normalize_presigned_part_checksums_requires_verified_presign() {
|
||||
let mut legacy = build_request(UploadPartInput::default(), Method::PUT);
|
||||
legacy.uri = "/bucket/object?x-amz-checksum-sha256=one".parse().unwrap();
|
||||
let mut req = envelope_from_presigned_fixture(&legacy);
|
||||
let mut req = RequestEnvelope::from_s3s(&legacy);
|
||||
let mut input = UploadPartWriteInput::from_legacy(legacy.input, None);
|
||||
normalize_presigned_part_checksums(&mut req, &mut input).unwrap();
|
||||
assert!(input.checksum_sha256.is_none());
|
||||
|
||||
@@ -313,8 +313,7 @@ impl DefaultMultipartUsecase {
|
||||
content_size: 0,
|
||||
principal: None,
|
||||
}
|
||||
.validate_multipart_ssec(&mp_info.user_defined)
|
||||
.map_err(ApiError::from)?;
|
||||
.validate_multipart_ssec(&mp_info.user_defined)?;
|
||||
|
||||
let src_versioned = BucketVersioningSys::prefix_enabled(&src_bucket, &src_key).await;
|
||||
let src_version_suspended = BucketVersioningSys::prefix_suspended(&src_bucket, &src_key).await;
|
||||
|
||||
@@ -2872,6 +2872,9 @@ mod tests {
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio_tar::{Builder, EntryType, Header};
|
||||
|
||||
#[path = "gateway_test.rs"]
|
||||
mod gateway_test;
|
||||
|
||||
fn archive_input(bucket: &str, key: &str, archive: Vec<u8>) -> PutObjectWriteInput {
|
||||
PutObjectWriteInput {
|
||||
bucket: bucket.to_owned(),
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn snowball_extract_preserves_sha256_failure_after_sniffing() {
|
||||
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
|
||||
use crate::server::TestGateway;
|
||||
use http_body_util::BodyExt as _;
|
||||
|
||||
let (store, context) = real_store_test_context().await;
|
||||
let bucket = format!("extract-body-error-{}", Uuid::new_v4());
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create extract test bucket");
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_path("member.txt").expect("valid member path");
|
||||
header.set_size(0);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
let mut archive = header.as_bytes().to_vec();
|
||||
archive.extend_from_slice(&[0; 1024]);
|
||||
let archive = Bytes::from(archive);
|
||||
let slot = crate::app::runtime_sources::ServerContextSlot::new();
|
||||
assert!(slot.install(Arc::clone(&context)));
|
||||
let gateway = TestGateway::over(&context, slot);
|
||||
for valid in [false, true] {
|
||||
let digest = if valid {
|
||||
rustfs_utils::crypto::hex_sha256(&archive, str::to_owned)
|
||||
} else {
|
||||
"00".repeat(32)
|
||||
};
|
||||
// The first frame supplies the sniff prefix. The gateway compares the signed
|
||||
// payload digest when it reaches the end of the second frame.
|
||||
let body = Body::from_segments([archive.slice(..16), archive.slice(16..)]);
|
||||
let request = http::Request::put(format!("http://localhost/{bucket}/archive.tar"))
|
||||
.header(http::header::HOST, "localhost")
|
||||
.header(http::header::CONTENT_LENGTH, archive.len())
|
||||
.header("x-amz-meta-snowball-auto-extract", "true")
|
||||
.header("x-amz-content-sha256", digest)
|
||||
.body(body)
|
||||
.unwrap();
|
||||
let request = rustfs_signer::try_sign_v4(
|
||||
request,
|
||||
i64::try_from(archive.len()).unwrap(),
|
||||
TestGateway::ACCESS_KEY,
|
||||
TestGateway::SECRET_KEY,
|
||||
"",
|
||||
"us-east-1",
|
||||
)
|
||||
.expect("sign Snowball upload");
|
||||
let response = gateway.call(request).await;
|
||||
let status = response.status();
|
||||
let response = response.into_body().collect().await.unwrap().to_bytes();
|
||||
if valid {
|
||||
assert_eq!(status, http::StatusCode::OK, "{response:?}");
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, "member.txt", &ObjectOptions::default())
|
||||
.await
|
||||
.expect("matching digest must extract the member")
|
||||
.size,
|
||||
0
|
||||
);
|
||||
} else {
|
||||
assert_eq!(status, http::StatusCode::BAD_REQUEST, "{response:?}");
|
||||
assert!(
|
||||
std::str::from_utf8(&response)
|
||||
.unwrap()
|
||||
.contains("<Code>XAmzContentSHA256Mismatch</Code>"),
|
||||
"{response:?}"
|
||||
);
|
||||
let missing = store
|
||||
.get_object_info(&bucket, "member.txt", &ObjectOptions::default())
|
||||
.await
|
||||
.expect_err("rejected archive cannot publish a member");
|
||||
assert!(is_err_object_not_found(&missing), "{missing}");
|
||||
}
|
||||
let missing = store
|
||||
.get_object_info(&bucket, "archive.tar", &ObjectOptions::default())
|
||||
.await
|
||||
.expect_err("the archive itself must not be stored");
|
||||
assert!(is_err_object_not_found(&missing), "{missing}");
|
||||
}
|
||||
}
|
||||
@@ -107,14 +107,8 @@ use super::storage_api::object_usecase::s3_api::multipart::parse_list_parts_para
|
||||
use super::storage_api::object_usecase::set_disk::{
|
||||
get_lock_acquire_timeout, get_object_disk_read_timeout, is_valid_storage_class,
|
||||
};
|
||||
#[cfg(not(test))]
|
||||
use super::storage_api::object_usecase::sse::{DecryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt};
|
||||
#[cfg(test)]
|
||||
pub(crate) use super::storage_api::object_usecase::sse::{
|
||||
DecryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt, sse_decryption,
|
||||
};
|
||||
use super::storage_api::object_usecase::sse::{
|
||||
EncryptionMaterialExt, EncryptionRequest, apply_bucket_default_lock_retention, authorize_sse_kms_object_read,
|
||||
DecryptionRequest, EncryptionRequest, SseKmsPrincipal, apply_bucket_default_lock_retention, authorize_sse_kms_object_read,
|
||||
bucket_default_write_sse, build_ssec_read_headers, classify_sse_read_response, encryption_material_to_metadata,
|
||||
extract_server_side_encryption_from_headers, extract_ssec_params_from_headers, extract_ssekms_context_from_headers,
|
||||
get_buffer_size_opt_in, load_bucket_object_lock_config_state, map_get_object_reader_error, sse_encryption,
|
||||
|
||||
@@ -637,81 +637,6 @@ async fn owned_audit_only_operation_matches_the_recorded_entries() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial(owned_audit_probe)]
|
||||
async fn owned_operation_attaches_the_sse_kms_summary_to_the_audit_entry() {
|
||||
use crate::app::object::{DecryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt as _, sse_decryption};
|
||||
use crate::server::{refresh_audit_module_enabled, refresh_notify_module_enabled};
|
||||
|
||||
temp_env::async_with_vars(
|
||||
[
|
||||
(rustfs_config::ENV_NOTIFY_ENABLE, Some("false")),
|
||||
(rustfs_config::ENV_AUDIT_ENABLE, Some("true")),
|
||||
],
|
||||
async {
|
||||
refresh_notify_module_enabled();
|
||||
refresh_audit_module_enabled();
|
||||
|
||||
let bucket = "h2-kms-audit";
|
||||
let probe = MutationCompletionProbe::install(bucket);
|
||||
let mut headers = HeaderMap::new();
|
||||
let mut extensions = Extensions::new();
|
||||
common(&mut headers, &mut extensions, bucket, "ledger.csv");
|
||||
extensions.insert(context("kms-tagged-request"));
|
||||
let envelope = RequestEnvelope::from_parts(
|
||||
RequestHead {
|
||||
method: Method::GET,
|
||||
uri: Uri::from_static("/h2-kms-audit/ledger.csv"),
|
||||
headers,
|
||||
credentials: None,
|
||||
region: None,
|
||||
service: None,
|
||||
},
|
||||
extensions,
|
||||
);
|
||||
let helper = OperationHelper::from_view(&envelope.audit_view(), EventName::ObjectAccessedGet, S3Operation::GetObject);
|
||||
|
||||
let wrapped_key = base64_simd::STANDARD.encode_to_string([7u8; 48]);
|
||||
let metadata = std::collections::HashMap::from([
|
||||
("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()),
|
||||
("x-rustfs-encryption-key-id".to_string(), "finance-key".to_string()),
|
||||
("x-rustfs-encryption-key".to_string(), wrapped_key.clone()),
|
||||
("x-rustfs-encryption-algorithm".to_string(), "aws:kms".to_string()),
|
||||
]);
|
||||
let principal = SseKmsPrincipal::from_request(&envelope).expect("authenticated request has a principal");
|
||||
sse_decryption(DecryptionRequest {
|
||||
bucket: "finance",
|
||||
key: "ledger.csv",
|
||||
metadata: &metadata,
|
||||
sse_customer_key: None,
|
||||
sse_customer_key_md5: None,
|
||||
principal: Some(&principal),
|
||||
})
|
||||
.await
|
||||
.expect_err("metadata without an IV cannot be unwrapped");
|
||||
|
||||
drop(helper.complete_owned(&Ok(()), StatusCode::OK, &HeaderMap::new()));
|
||||
probe.wait_for(1, 0).await;
|
||||
let audits = probe.audits.lock().expect("audit entries");
|
||||
assert_eq!(audits.len(), 1);
|
||||
let tags = audits[0]
|
||||
.tags
|
||||
.as_ref()
|
||||
.expect("a request that used KMS must carry its summary");
|
||||
assert_eq!(tags.get("sseType").and_then(Value::as_str), Some("SSE-KMS"));
|
||||
assert_eq!(tags.get("kmsKeyId").and_then(Value::as_str), Some("finance-key"));
|
||||
assert_eq!(tags.get("kmsOutcome").and_then(Value::as_str), Some("failure"));
|
||||
assert!(tags.contains_key("kmsErrorClass"), "a failed KMS interaction must be classified");
|
||||
assert!(
|
||||
!serde_json::to_string(tags)
|
||||
.expect("audit tags serialize")
|
||||
.contains(&wrapped_key)
|
||||
);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// The one field the two edges record differently: for an error without a
|
||||
/// message the owned entry carries the code name, while the legacy entry carries
|
||||
/// whatever default message s3s stored for the code (its prose for a known code,
|
||||
|
||||
@@ -76,21 +76,6 @@ fn build_request<T>(input: T, method: Method) -> S3Request<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Method, URI, headers, extensions, region, and service. These fixtures leave credentials absent.
|
||||
fn envelope_from_request<T>(req: &S3Request<T>) -> RequestEnvelope {
|
||||
RequestEnvelope::from_parts(
|
||||
RequestHead {
|
||||
method: req.method.clone(),
|
||||
uri: req.uri.clone(),
|
||||
headers: req.headers.clone(),
|
||||
credentials: None,
|
||||
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
|
||||
service: req.service.clone(),
|
||||
},
|
||||
req.extensions.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
fn ensure_req_info<T>(req: &mut S3Request<T>) {
|
||||
req.extensions.insert(ReqInfo::default());
|
||||
}
|
||||
@@ -333,7 +318,7 @@ async fn owned_authorization_reloads_tags_when_version_changes() {
|
||||
..Default::default()
|
||||
});
|
||||
legacy.extensions.insert(slot);
|
||||
let mut owned = envelope_from_request(&legacy);
|
||||
let mut owned = crate::app::RequestEnvelope::from_s3s(&legacy);
|
||||
for (index, allowed, expected_tag) in [(0, true, "allowed"), (1, false, "denied"), (0, true, "allowed")] {
|
||||
let version = &versions[index];
|
||||
owned.req_info_mut().expect("owned info").version_id = Some(version.clone());
|
||||
@@ -422,15 +407,15 @@ async fn table_publication_guard_timeout_blocks_put_delete_and_multipart_authori
|
||||
put_req.extensions.insert(server_ctx.clone());
|
||||
delete_req.extensions.insert(server_ctx.clone());
|
||||
multipart_req.extensions.insert(server_ctx);
|
||||
let mut owned_put = envelope_from_request(&put_req);
|
||||
let mut owned_put = crate::app::RequestEnvelope::from_s3s(&put_req);
|
||||
let owned_info = owned_put.req_info_mut().expect("owned request info");
|
||||
owned_info.bucket = Some(bucket.clone());
|
||||
owned_info.object = Some("object".to_string());
|
||||
let mut owned_delete = envelope_from_request(&delete_req);
|
||||
let mut owned_delete = crate::app::RequestEnvelope::from_s3s(&delete_req);
|
||||
let delete_info = owned_delete.req_info_mut().expect("owned delete info");
|
||||
delete_info.bucket = Some(bucket.clone());
|
||||
delete_info.object = Some("object".to_string());
|
||||
let mut owned_multipart = envelope_from_request(&multipart_req);
|
||||
let mut owned_multipart = crate::app::RequestEnvelope::from_s3s(&multipart_req);
|
||||
let multipart_info = owned_multipart.req_info_mut().expect("owned multipart info");
|
||||
multipart_info.bucket = Some(bucket.clone());
|
||||
multipart_info.object = Some("object".to_string());
|
||||
@@ -590,7 +575,7 @@ async fn owned_and_legacy_create_bucket_authorization_use_location_constraint()
|
||||
.as_ref()
|
||||
.and_then(|c| c.location_constraint.as_ref())
|
||||
.map(|l| l.as_str().to_owned());
|
||||
let mut owned = envelope_from_request(&legacy);
|
||||
let mut owned = crate::app::RequestEnvelope::from_s3s(&legacy);
|
||||
let action = Action::S3Action(S3Action::CreateBucketAction);
|
||||
let owned_result = crate::app::authorize_owned_request(&mut owned, action, location).await;
|
||||
if allowed {
|
||||
@@ -628,7 +613,7 @@ async fn owned_and_legacy_create_bucket_authorization_use_location_constraint()
|
||||
cred: Some(credentials.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
let mut owned = envelope_from_request(&legacy);
|
||||
let mut owned = crate::app::RequestEnvelope::from_s3s(&legacy);
|
||||
let input =
|
||||
rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::create_bucket::input_from_s3s(legacy.input.clone())
|
||||
.expect("a valid CreateBucket input");
|
||||
@@ -679,7 +664,7 @@ async fn owned_and_legacy_delete_bucket_authorization_agree() {
|
||||
cred: Some(credentials.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
let mut owned = envelope_from_request(&legacy);
|
||||
let mut owned = crate::app::RequestEnvelope::from_s3s(&legacy);
|
||||
let owned_result = authorize_delete_bucket(&mut owned, bucket).await;
|
||||
|
||||
let case = format!("{bucket} {header:?}");
|
||||
@@ -700,7 +685,7 @@ fn owned_and_legacy_conditions_read_the_same_request_body_policy_inputs() {
|
||||
location_constraint: None,
|
||||
};
|
||||
let conditions_of = |req: &S3Request<()>, action| {
|
||||
let owned = envelope_from_request(req);
|
||||
let owned = crate::app::RequestEnvelope::from_s3s(req);
|
||||
support::authorization_conditions(&owned, &principal, &support::request_authz_facts(&owned, target(action)))
|
||||
.expect("owned conditions")
|
||||
};
|
||||
@@ -755,7 +740,7 @@ fn installed_body_inputs_describe_the_request_the_same_on_both_forms() {
|
||||
legacy
|
||||
.headers
|
||||
.insert("x-amz-object-lock-mode", HeaderValue::from_static("COMPLIANCE"));
|
||||
let mut owned = envelope_from_request(&legacy);
|
||||
let mut owned = RequestEnvelope::from_s3s(&legacy);
|
||||
owned.install_requested_object_tags(RequestedObjectTags(vec![("class".to_owned(), "public".to_owned())]));
|
||||
owned.install_requested_legal_hold(RequestedObjectLegalHold::default());
|
||||
owned.install_requested_retention(RequestedObjectLockRetention {
|
||||
@@ -823,7 +808,7 @@ fn create_bucket_location_constraint_conditions_use_only_xml() {
|
||||
.and_then(|c| c.location_constraint.as_ref())
|
||||
.map(|l| l.as_str().to_owned());
|
||||
let principal = AuthzPrincipal::new(&credentials, "");
|
||||
let owned = envelope_from_request(&req);
|
||||
let owned = crate::app::RequestEnvelope::from_s3s(&req);
|
||||
let owned_facts = support::request_authz_facts(
|
||||
&owned,
|
||||
AuthzTarget {
|
||||
@@ -907,7 +892,7 @@ async fn request_slot_keeps_bucket_policy_bound_to_its_store() {
|
||||
..Default::default()
|
||||
});
|
||||
request_a.extensions.insert(slot_a);
|
||||
let mut owned_a = envelope_from_request(&request_a);
|
||||
let mut owned_a = crate::app::RequestEnvelope::from_s3s(&request_a);
|
||||
crate::app::authorize_owned_request(&mut owned_a, Action::S3Action(S3Action::PutObjectAction), None)
|
||||
.await
|
||||
.expect("store A policy should authorize owned request");
|
||||
@@ -919,7 +904,7 @@ async fn request_slot_keeps_bucket_policy_bound_to_its_store() {
|
||||
..Default::default()
|
||||
});
|
||||
request_b.extensions.insert(slot_b);
|
||||
let mut owned_b = envelope_from_request(&request_b);
|
||||
let mut owned_b = crate::app::RequestEnvelope::from_s3s(&request_b);
|
||||
let owned_err = crate::app::authorize_owned_request(&mut owned_b, Action::S3Action(S3Action::PutObjectAction), None)
|
||||
.await
|
||||
.expect_err("store B policy must deny owned request");
|
||||
@@ -945,7 +930,7 @@ async fn request_slot_keeps_bucket_policy_bound_to_its_store() {
|
||||
..Default::default()
|
||||
});
|
||||
allowed_request_b.extensions.insert(slot_b);
|
||||
let mut owned_allowed_b = envelope_from_request(&allowed_request_b);
|
||||
let mut owned_allowed_b = crate::app::RequestEnvelope::from_s3s(&allowed_request_b);
|
||||
crate::app::authorize_owned_request(&mut owned_allowed_b, Action::S3Action(S3Action::PutObjectAction), None)
|
||||
.await
|
||||
.expect("store B policy should authorize owned request before public access block");
|
||||
@@ -968,7 +953,7 @@ async fn request_slot_keeps_bucket_policy_bound_to_its_store() {
|
||||
..Default::default()
|
||||
});
|
||||
restricted_request_b.extensions.insert(slot_b);
|
||||
let mut owned_restricted_b = envelope_from_request(&restricted_request_b);
|
||||
let mut owned_restricted_b = crate::app::RequestEnvelope::from_s3s(&restricted_request_b);
|
||||
let owned_err =
|
||||
crate::app::authorize_owned_request(&mut owned_restricted_b, Action::S3Action(S3Action::PutObjectAction), None)
|
||||
.await
|
||||
@@ -1011,7 +996,7 @@ async fn request_slot_keeps_bucket_policy_bound_to_its_store() {
|
||||
..Default::default()
|
||||
});
|
||||
tagged_request_b.extensions.insert(slot_b);
|
||||
let mut owned_tagged_b = envelope_from_request(&tagged_request_b);
|
||||
let mut owned_tagged_b = crate::app::RequestEnvelope::from_s3s(&tagged_request_b);
|
||||
crate::app::authorize_owned_request(&mut owned_tagged_b, Action::S3Action(S3Action::PutObjectAction), None)
|
||||
.await
|
||||
.expect("store B existing object tags should authorize owned request");
|
||||
@@ -1026,7 +1011,7 @@ async fn request_slot_keeps_bucket_policy_bound_to_its_store() {
|
||||
let mut unready_request = build_request((), Method::PUT);
|
||||
unready_request.extensions.insert(ServerContextSlot::new());
|
||||
ensure_req_info(&mut unready_request);
|
||||
let mut owned_unready = envelope_from_request(&unready_request);
|
||||
let mut owned_unready = crate::app::RequestEnvelope::from_s3s(&unready_request);
|
||||
let err = support::request_object_store(&owned_unready).expect_err("an unready request slot must not use an ambient store");
|
||||
assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::InternalError);
|
||||
let owned_err = crate::app::authorize_owned_request(&mut owned_unready, Action::S3Action(S3Action::PutObjectAction), None)
|
||||
@@ -1066,13 +1051,13 @@ fn get_object() -> rustfs_policy::policy::action::Action {
|
||||
#[tokio::test]
|
||||
async fn owned_entry_points_reject_duplicate_signed_metadata_like_the_legacy_edge() {
|
||||
let query = "x-amz-meta-a=1&x-amz-meta-a=2";
|
||||
let mut owned = envelope_from_request(&signed_zip_request(query));
|
||||
let mut owned = RequestEnvelope::from_s3s(&signed_zip_request(query));
|
||||
let owned_err = crate::app::authorize_owned_request(&mut owned, get_object(), None)
|
||||
.await
|
||||
.expect_err("owned rejects a repeated metadata key");
|
||||
assert_eq!(owned_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidArgument);
|
||||
|
||||
let mut internal = envelope_from_request(&signed_zip_request(query));
|
||||
let mut internal = RequestEnvelope::from_s3s(&signed_zip_request(query));
|
||||
let internal_err = crate::app::authorize_owned_internal_object_request(&mut internal, get_object())
|
||||
.await
|
||||
.expect_err("owned internal rejects a repeated metadata key");
|
||||
@@ -1082,7 +1067,7 @@ async fn owned_entry_points_reject_duplicate_signed_metadata_like_the_legacy_edg
|
||||
#[tokio::test]
|
||||
async fn owned_entry_points_hoist_signed_metadata_into_the_headers_policy_reads() {
|
||||
let query = "x-amz-meta-a=1";
|
||||
let mut owned = envelope_from_request(&signed_zip_request(query));
|
||||
let mut owned = RequestEnvelope::from_s3s(&signed_zip_request(query));
|
||||
let owned_err = crate::app::authorize_owned_request(&mut owned, get_object(), None)
|
||||
.await
|
||||
.expect_err("no ReqInfo");
|
||||
@@ -1151,12 +1136,12 @@ async fn owned_entry_point_fails_closed_without_a_body_policy_input() {
|
||||
}),
|
||||
];
|
||||
for (name, req, action, supply) in cases {
|
||||
let mut missing = envelope_from_request(&req);
|
||||
let mut missing = RequestEnvelope::from_s3s(&req);
|
||||
let err = crate::app::authorize_owned_request(&mut missing, action, None)
|
||||
.await
|
||||
.expect_err(name);
|
||||
assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied, "{name}: missing input must deny");
|
||||
let mut internal = envelope_from_request(&req);
|
||||
let mut internal = RequestEnvelope::from_s3s(&req);
|
||||
let err = crate::app::authorize_owned_internal_object_request(&mut internal, action)
|
||||
.await
|
||||
.expect_err(name);
|
||||
@@ -1169,7 +1154,7 @@ async fn owned_entry_point_fails_closed_without_a_body_policy_input() {
|
||||
// With the input carried, the request reaches the core, which stops on the absent ReqInfo.
|
||||
let mut supplied_req = req;
|
||||
supply(&mut supplied_req.extensions);
|
||||
let mut supplied = envelope_from_request(&supplied_req);
|
||||
let mut supplied = RequestEnvelope::from_s3s(&supplied_req);
|
||||
let err = crate::app::authorize_owned_request(&mut supplied, action, None)
|
||||
.await
|
||||
.expect_err(name);
|
||||
@@ -1575,10 +1560,10 @@ async fn owned_and_legacy_entry_points_reach_the_same_decisions() {
|
||||
..Default::default()
|
||||
});
|
||||
(case.facts)(&mut legacy);
|
||||
let mut owned = envelope_from_request(&legacy);
|
||||
let mut owned = RequestEnvelope::from_s3s(&legacy);
|
||||
// The object shape both edges' access hooks call, on a forked envelope as an archive
|
||||
// member is authorized: it must reach the same decision.
|
||||
let mut owned_shape = envelope_from_request(&legacy).fork_for_authorization();
|
||||
let mut owned_shape = RequestEnvelope::from_s3s(&legacy).fork_for_authorization();
|
||||
let action = Action::S3Action(case.action);
|
||||
let owned_result = crate::app::authorize_owned_request(&mut owned, action, None).await;
|
||||
let shape_result = crate::app::storage_api::owned_parity::authorize_object_request(
|
||||
@@ -1729,7 +1714,7 @@ async fn owned_and_legacy_bucket_config_mutations_hand_on_the_same_decision_and_
|
||||
is_owner,
|
||||
..Default::default()
|
||||
});
|
||||
let mut owned = envelope_from_request(&legacy);
|
||||
let mut owned = RequestEnvelope::from_s3s(&legacy);
|
||||
let action = Action::S3Action(action);
|
||||
|
||||
let owned_result = authorize_bucket_config_mutation(&slot, &mut owned, bucket, action)
|
||||
@@ -1983,7 +1968,7 @@ async fn owned_and_legacy_write_checks_hand_on_the_same_decision_and_state() {
|
||||
..Default::default()
|
||||
});
|
||||
facts(&mut legacy);
|
||||
let mut owned = envelope_from_request(&legacy);
|
||||
let mut owned = RequestEnvelope::from_s3s(&legacy);
|
||||
let owned_outcome = run_write_shape(shape, &mut owned).await;
|
||||
if owned_outcome != expected {
|
||||
mismatches.push(format!("{name}: expected {expected:?}, owned {owned_outcome:?}"));
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
use super::storage_api::select_object::StorageError;
|
||||
use super::storage_api::select_object::options::get_opts;
|
||||
use super::storage_api::select_object::request_context::spawn_traced;
|
||||
use super::storage_api::select_object::sse::{
|
||||
SseKmsPrincipal, SseKmsPrincipalExt, authorize_sse_kms_object_read, project_sse_read_response_headers,
|
||||
};
|
||||
use super::storage_api::select_object::sse::{SseKmsPrincipal, authorize_sse_kms_object_read, project_sse_read_response_headers};
|
||||
use super::storage_api::select_object::{
|
||||
StoragePrepareSelectObjectSnapshotError, StorageSelectObjectSnapshot, get_validated_store, validate_sse_headers_for_read,
|
||||
validate_ssec_for_read,
|
||||
|
||||
@@ -1703,9 +1703,9 @@ pub(crate) mod sse {
|
||||
validate_bucket_object_lock_enabled_state,
|
||||
};
|
||||
pub(crate) use crate::storage::storage_api::sse_consumer::{
|
||||
EncryptionKeyKind, EncryptionMaterialExt, SseKmsPrincipalExt, bucket_default_write_sse, build_ssec_read_headers,
|
||||
encryption_material_to_metadata, extract_ssec_params_from_headers, extract_ssekms_context_from_headers,
|
||||
map_get_object_reader_error, mark_encrypted_multipart_metadata, multipart_completion_authorization, stored_ssec_metadata,
|
||||
EncryptionKeyKind, bucket_default_write_sse, build_ssec_read_headers, encryption_material_to_metadata,
|
||||
extract_ssec_params_from_headers, extract_ssekms_context_from_headers, map_get_object_reader_error,
|
||||
mark_encrypted_multipart_metadata, multipart_completion_authorization, stored_ssec_metadata,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -24,27 +24,7 @@ pub(crate) async fn list_objects_v2(
|
||||
req: S3Request<ListObjectsV2Input>,
|
||||
) -> S3Result<S3Response<ListObjectsV2Output>> {
|
||||
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::list_objects_v2 as ops;
|
||||
// Same facts `RequestEnvelope::from_s3s` copies: method, URI, headers, extensions, region, service, and credentials.
|
||||
let credentials = req.credentials.as_ref().map(|credentials| {
|
||||
let session_token = crate::auth::get_session_token(&req.uri, &req.headers).map(str::to_owned);
|
||||
crate::app::RequestCredentials::new(
|
||||
credentials.access_key.clone(),
|
||||
credentials.secret_key.expose().to_owned(),
|
||||
session_token.clone(),
|
||||
)
|
||||
.unwrap_or_else(|_| crate::app::RequestCredentials::without_secret_key(credentials.access_key.clone(), session_token))
|
||||
});
|
||||
let envelope = crate::app::RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: req.method.clone(),
|
||||
uri: req.uri.clone(),
|
||||
headers: req.headers.clone(),
|
||||
credentials,
|
||||
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
|
||||
service: req.service.clone(),
|
||||
},
|
||||
req.extensions.clone(),
|
||||
);
|
||||
let envelope = crate::app::RequestEnvelope::from_s3s(&req);
|
||||
let input = ops::input_from_s3s(req.input).map_err(crate::app::dto_values::seam_error)?;
|
||||
let mut output = list_objects_v2_owned(usecase, envelope, input).await?;
|
||||
let migration_list = output.rustfs_on_demand_migration_list.take();
|
||||
|
||||
+72
-13
@@ -18,7 +18,6 @@ use http::StatusCode;
|
||||
use rustfs_kms::KmsUnavailableError;
|
||||
use rustfs_lock::LockError;
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
use rustfs_sse::{SseError, data_plane_kms_error};
|
||||
use s3s::S3Error as LegacyS3Error;
|
||||
use s3s::stream::{aws_chunked_stream::AwsChunkedStreamError, upload_stream::UploadStreamError};
|
||||
|
||||
@@ -52,7 +51,7 @@ pub(crate) fn rpc_replay_admission_exhausted_status() -> tonic::Status {
|
||||
const UNSUPPORTED_PARTICIPANT_MESSAGE: &str = "A storage participant does not support this operation's protocol version. If the cluster is being upgraded, finish upgrading every node and retry.";
|
||||
|
||||
/// S3 error code for a request that names a KMS key the KMS does not hold.
|
||||
pub use rustfs_sse::KMS_KEY_NOT_FOUND_ERROR_CODE;
|
||||
pub const KMS_KEY_NOT_FOUND_ERROR_CODE: &str = "KMS.NotFoundException";
|
||||
|
||||
fn lock_resource_class(resource: Option<&str>) -> &'static str {
|
||||
let Some(resource) = resource else {
|
||||
@@ -123,6 +122,77 @@ fn record_s3_lock_failure(err: &StorageError) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a KMS failure that surfaced on the S3 data path to its S3 error code.
|
||||
///
|
||||
/// The contract deliberately differs from the admin lifecycle handlers
|
||||
/// (`kms_key_lifecycle::lifecycle_error_status`): there a key id is the
|
||||
/// resource being addressed, so a missing key is `404`. Here the key id
|
||||
/// arrives inside a request header or a bucket default, so a key that is
|
||||
/// missing, disabled, or otherwise unusable is configuration the caller has to
|
||||
/// correct — AWS answers `400`, and reporting `500` instead both misfiles the
|
||||
/// failure as a server fault and makes SDKs back off and retry a request that
|
||||
/// cannot succeed.
|
||||
///
|
||||
/// `None` keeps the caller's fallthrough, which is the `500` that integrity
|
||||
/// faults — damaged, unreadable, or unknown-format key material — must keep.
|
||||
///
|
||||
/// Messages either name what the caller asked for or stay generic; detail that
|
||||
/// belongs to the deployment rather than the request stays in `source`, which
|
||||
/// the caller attaches and the logs retain.
|
||||
fn data_plane_kms_error(error: &rustfs_kms::KmsError) -> Option<(S3ErrorCode, String)> {
|
||||
use rustfs_kms::KmsError as Kms;
|
||||
|
||||
let generic = |code: S3ErrorCode| {
|
||||
let message = ApiError::error_code_to_message(&code);
|
||||
Some((code, message))
|
||||
};
|
||||
|
||||
match error {
|
||||
Kms::KeyNotFound { key_id } => Some((
|
||||
S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()),
|
||||
format!("KMS key not found: {key_id}"),
|
||||
)),
|
||||
Kms::KeyVersionNotFound { key_id, version } => Some((
|
||||
S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()),
|
||||
format!("KMS key version {version} not found for key {key_id}"),
|
||||
)),
|
||||
// The key exists but its state forbids the operation (disabled,
|
||||
// pending deletion). AWS treats an invalid key state as a request
|
||||
// error, not a server fault.
|
||||
Kms::InvalidOperation { .. } => Some((S3ErrorCode::InvalidRequest, error.to_string())),
|
||||
// A policy decision needs a human, so it must be distinguishable from
|
||||
// the transient classes an SDK retries.
|
||||
Kms::AccessDenied { .. } => generic(S3ErrorCode::AccessDenied),
|
||||
// Request-side faults: what was asked for cannot be served as asked.
|
||||
Kms::ContextMismatch { .. }
|
||||
| Kms::InvalidKey { .. }
|
||||
| Kms::ValidationError { .. }
|
||||
| Kms::UnsupportedAlgorithm { .. }
|
||||
| Kms::InvalidKeySize { .. } => Some((S3ErrorCode::InvalidRequest, error.to_string())),
|
||||
// A deployment whose KMS configuration cannot serve the request (for
|
||||
// example no key named and no default). Actionable, but the detail
|
||||
// describes the deployment, so it stays out of the response body.
|
||||
Kms::ConfigurationError { .. } => {
|
||||
Some((S3ErrorCode::InvalidRequest, "The KMS configuration cannot serve this request".to_string()))
|
||||
}
|
||||
// Transient: worth retrying, and must be counted against availability
|
||||
// rather than against the caller. `IoError` belongs here because it is
|
||||
// how a backend reports that its key store itself was unreachable —
|
||||
// rustfs/rustfs#7470 separated that from a missing key precisely so the
|
||||
// two stop looking alike, and leaving it on the 500 fallthrough would
|
||||
// erase that distinction again at the S3 boundary.
|
||||
Kms::BackendError { .. }
|
||||
| Kms::IoError { .. }
|
||||
| Kms::OperationTimedOut { .. }
|
||||
| Kms::OperationCancelled { .. }
|
||||
| Kms::CredentialsUnavailable { .. }
|
||||
| Kms::CacheError { .. } => generic(S3ErrorCode::ServiceUnavailable),
|
||||
// A permanent gap in the configured backend, never a missing resource.
|
||||
Kms::UnsupportedCapability { .. } => Some((S3ErrorCode::NotImplemented, error.to_string())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP status of the error codes s3s cannot derive on its own.
|
||||
///
|
||||
/// s3s answers `None` for every `Custom` code, which the response layer turns
|
||||
@@ -697,17 +767,6 @@ impl From<crate::table_catalog::TableCatalogStoreError> for ApiError {
|
||||
}
|
||||
}
|
||||
|
||||
/// An SSE failure arrives already classified for the S3 data path; carry it over as is.
|
||||
impl From<SseError> for ApiError {
|
||||
fn from(err: SseError) -> Self {
|
||||
ApiError {
|
||||
code: err.code,
|
||||
message: err.message,
|
||||
source: err.source,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StorageError> for ApiError {
|
||||
fn from(err: StorageError) -> Self {
|
||||
record_s3_lock_failure(&err);
|
||||
|
||||
+2
-4
@@ -25,7 +25,7 @@ use crate::storage_api::startup::init::{
|
||||
use crate::storage_api::startup::services::ECStore;
|
||||
#[cfg(any(feature = "ftps", feature = "webdav", feature = "sftp"))]
|
||||
use crate::storage_api::startup::services::ServerContextSlot;
|
||||
use crate::storage_api::startup::sse::init_sse_startup;
|
||||
use crate::storage_api::startup::sse::log_sse_kms_key_policy_mode;
|
||||
use crate::{admin, config, startup_runtime_sources, version};
|
||||
use rustfs_config::{
|
||||
DEFAULT_BUFFER_MAX_SIZE, DEFAULT_BUFFER_MIN_SIZE, DEFAULT_BUFFER_PROFILE, DEFAULT_BUFFER_UNKNOWN_SIZE, DEFAULT_UPDATE_CHECK,
|
||||
@@ -539,9 +539,7 @@ pub async fn init_kms_system(config: &config::Config, store: Arc<ECStore>) -> st
|
||||
// Initialize global KMS service manager (starts in NotConfigured state)
|
||||
let service_manager = startup_runtime_sources::init_kms_service_manager();
|
||||
|
||||
// Settles what SSE reads from the environment. Idempotent, so a second
|
||||
// embedded server in this process reports nothing new.
|
||||
init_sse_startup();
|
||||
log_sse_kms_key_policy_mode();
|
||||
|
||||
// A key referenced by any bucket's encryption configuration must never be
|
||||
// deleted. Register the gate before the service can start so every
|
||||
|
||||
@@ -324,31 +324,6 @@ fn copy_output_facts(tag: Option<&str>) -> CopyObjectWriteOutput {
|
||||
checksum_type: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Same facts `RequestEnvelope::from_s3s` copies: method, URI, headers, extensions, region, service, and credentials.
|
||||
fn envelope_from_legacy_copy_request(req: &s3s::S3Request<()>) -> crate::app::RequestEnvelope {
|
||||
let credentials = req.credentials.as_ref().map(|credentials| {
|
||||
let session_token = crate::auth::get_session_token(&req.uri, &req.headers).map(str::to_owned);
|
||||
crate::app::RequestCredentials::new(
|
||||
credentials.access_key.clone(),
|
||||
credentials.secret_key.expose().to_owned(),
|
||||
session_token.clone(),
|
||||
)
|
||||
.unwrap_or_else(|_| crate::app::RequestCredentials::without_secret_key(credentials.access_key.clone(), session_token))
|
||||
});
|
||||
crate::app::RequestEnvelope::from_parts(
|
||||
crate::app::RequestHead {
|
||||
method: req.method.clone(),
|
||||
uri: req.uri.clone(),
|
||||
headers: req.headers.clone(),
|
||||
credentials,
|
||||
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
|
||||
service: req.service.clone(),
|
||||
},
|
||||
req.extensions.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_copy_request_head_matches_legacy() {
|
||||
fn facts(envelope: &crate::app::RequestEnvelope) -> serde_json::Value {
|
||||
@@ -380,7 +355,7 @@ fn protocol_copy_request_head_matches_legacy() {
|
||||
credentials: &credentials,
|
||||
};
|
||||
let old = ProtocolStorageClient::create_request((), Method::PUT, uri.clone(), params()).expect("legacy request");
|
||||
let old = envelope_from_legacy_copy_request(&old);
|
||||
let old = crate::app::RequestEnvelope::from_s3s(&old);
|
||||
let current = ProtocolStorageClient::create_envelope(Method::PUT, uri, params());
|
||||
assert_eq!(facts(¤t), facts(&old));
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
use super::{ListPartsInfo, dto, list_parts_output};
|
||||
use crate::app::storage_api::bucket_usecase::s3_api::bucket::{RUSTFS_OWNER_DISPLAY_NAME, RUSTFS_OWNER_ID};
|
||||
use crate::storage_api::server::gateway_stack::PartInfo;
|
||||
use crate::storage_api::server::http::access::test_support::PartInfo;
|
||||
use rustfs_gateway::{Limits, MetaView, OperationCodec, ResponseBody, TargetKind, WireRequest};
|
||||
use rustfs_s3_types::S3ErrorCode;
|
||||
|
||||
|
||||
@@ -562,188 +562,5 @@ impl IamKeyLookup for ServerIam {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod snowball_tests {
|
||||
use super::*;
|
||||
use crate::app::storage_api::error::is_err_object_not_found;
|
||||
use crate::app::storage_api::test::StorageObjectOptions;
|
||||
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
|
||||
use crate::app::storage_api::test::contract::object::ObjectOperations as _;
|
||||
use bytes::Bytes;
|
||||
use http_body_util::BodyExt as _;
|
||||
use rustfs_gateway_stream::Body;
|
||||
use tokio_tar::Header;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn snowball_extract_preserves_sha256_failure_after_sniffing() {
|
||||
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
|
||||
if crate::runtime_sources::current_app_context().is_none() {
|
||||
crate::runtime_sources::install_test_app_context(Arc::clone(&store)).await;
|
||||
}
|
||||
let ambient = crate::runtime_sources::current_app_context().expect("Snowball gateway test requires an AppContext");
|
||||
let context = Arc::new(crate::runtime_sources::AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()));
|
||||
let bucket = format!("extract-body-error-{}", Uuid::new_v4());
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create extract test bucket");
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_path("member.txt").expect("valid member path");
|
||||
header.set_size(0);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
let mut archive = header.as_bytes().to_vec();
|
||||
archive.extend_from_slice(&[0; 1024]);
|
||||
let archive = Bytes::from(archive);
|
||||
let slot = ServerContextSlot::new();
|
||||
assert!(slot.install(Arc::clone(&context)));
|
||||
let gateway = TestGateway::over(&context, slot);
|
||||
for valid in [false, true] {
|
||||
let digest = if valid {
|
||||
rustfs_utils::crypto::hex_sha256(&archive, str::to_owned)
|
||||
} else {
|
||||
"00".repeat(32)
|
||||
};
|
||||
// The first frame supplies the sniff prefix. The gateway compares the signed
|
||||
// payload digest when it reaches the end of the second frame.
|
||||
let body = Body::from_segments([archive.slice(..16), archive.slice(16..)]);
|
||||
let request = http::Request::put(format!("http://localhost/{bucket}/archive.tar"))
|
||||
.header(http::header::HOST, "localhost")
|
||||
.header(http::header::CONTENT_LENGTH, archive.len())
|
||||
.header("x-amz-meta-snowball-auto-extract", "true")
|
||||
.header("x-amz-content-sha256", digest)
|
||||
.body(body)
|
||||
.expect("build Snowball upload");
|
||||
let request = rustfs_signer::try_sign_v4(
|
||||
request,
|
||||
i64::try_from(archive.len()).expect("archive length fits i64"),
|
||||
TestGateway::ACCESS_KEY,
|
||||
TestGateway::SECRET_KEY,
|
||||
"",
|
||||
"us-east-1",
|
||||
)
|
||||
.expect("sign Snowball upload");
|
||||
let response = gateway.call(request).await;
|
||||
let status = response.status();
|
||||
let response = response
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.expect("collect Snowball response")
|
||||
.to_bytes();
|
||||
if valid {
|
||||
assert_eq!(status, http::StatusCode::OK, "{response:?}");
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, "member.txt", &StorageObjectOptions::default())
|
||||
.await
|
||||
.expect("matching digest must extract the member")
|
||||
.size,
|
||||
0
|
||||
);
|
||||
} else {
|
||||
assert_eq!(status, http::StatusCode::BAD_REQUEST, "{response:?}");
|
||||
assert!(
|
||||
std::str::from_utf8(&response)
|
||||
.expect("S3 error response is UTF-8")
|
||||
.contains("<Code>XAmzContentSHA256Mismatch</Code>"),
|
||||
"{response:?}"
|
||||
);
|
||||
let missing = store
|
||||
.get_object_info(&bucket, "member.txt", &StorageObjectOptions::default())
|
||||
.await
|
||||
.expect_err("rejected archive cannot publish a member");
|
||||
assert!(is_err_object_not_found(&missing), "{missing}");
|
||||
}
|
||||
let missing = store
|
||||
.get_object_info(&bucket, "archive.tar", &StorageObjectOptions::default())
|
||||
.await
|
||||
.expect_err("the archive itself must not be stored");
|
||||
assert!(is_err_object_not_found(&missing), "{missing}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod object_lock_tests {
|
||||
use super::*;
|
||||
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
|
||||
use bytes::Bytes;
|
||||
use http::{Method, StatusCode};
|
||||
use http_body_util::BodyExt as _;
|
||||
use md5::Digest as _;
|
||||
use rustfs_gateway_types::persistence::parse_object_lock;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn object_lock_round_trips_the_default_retention() {
|
||||
let ambient = crate::app::gating_test_env::shared_gating_ambient().await;
|
||||
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
|
||||
let context = Arc::new(crate::runtime_sources::AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()));
|
||||
let slot = ServerContextSlot::new();
|
||||
assert!(slot.install(Arc::clone(&context)));
|
||||
let gateway = TestGateway::over(&context, slot);
|
||||
let bucket = format!("lock-config-{}", Uuid::new_v4());
|
||||
store
|
||||
.make_bucket(
|
||||
&bucket,
|
||||
&MakeBucketOptions {
|
||||
lock_enabled: true,
|
||||
versioning_enabled: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("create object-lock bucket");
|
||||
|
||||
let xml = b"<ObjectLockConfiguration><ObjectLockEnabled>Enabled</ObjectLockEnabled>\
|
||||
<Rule><DefaultRetention><Mode>GOVERNANCE</Mode><Days>30</Days></DefaultRetention></Rule></ObjectLockConfiguration>";
|
||||
let target = format!("/{bucket}?object-lock");
|
||||
let checksum = base64_simd::STANDARD.encode_to_string(md5::Md5::digest(xml));
|
||||
let put = gateway
|
||||
.signed(Method::PUT, &target, vec![("content-md5", checksum)], Bytes::from_static(xml))
|
||||
.await
|
||||
.expect("PUT Object Lock configuration");
|
||||
let put_status = put.status();
|
||||
let put_body = put
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.expect("collect PUT Object Lock response")
|
||||
.to_bytes();
|
||||
assert_eq!(put_status, StatusCode::OK, "{}", String::from_utf8_lossy(&put_body));
|
||||
|
||||
let (stored, _) = crate::storage_api::server::gateway_stack::get_object_lock_config(&bucket)
|
||||
.await
|
||||
.expect("stored lock config");
|
||||
assert_eq!(stored.object_lock_enabled.as_deref(), Some("Enabled"));
|
||||
|
||||
let get = gateway
|
||||
.signed(Method::GET, &target, vec![], Bytes::new())
|
||||
.await
|
||||
.expect("GET Object Lock configuration");
|
||||
assert_eq!(get.status(), StatusCode::OK);
|
||||
let body = get
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.expect("collect GET Object Lock response")
|
||||
.to_bytes();
|
||||
let returned = parse_object_lock(&body).expect("get lock configuration");
|
||||
assert_eq!(returned, stored);
|
||||
let retention = returned
|
||||
.rule
|
||||
.expect("stored Object Lock rule")
|
||||
.default_retention
|
||||
.expect("stored default retention");
|
||||
assert_eq!(retention.mode.as_deref(), Some("GOVERNANCE"));
|
||||
assert_eq!(retention.days, Some(30));
|
||||
assert_eq!(retention.years, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -12,9 +12,7 @@ Applies to `rustfs/src/storage/`.
|
||||
|
||||
- Never log plaintext customer keys, decrypted key material, or sensitive SSE request payloads.
|
||||
- Keep SSE behavior aligned with KMS and admin handler integrations.
|
||||
- SSE key resolution lives in `crates/sse/`; `sse.rs` here only binds it to the running server (`RustfsSseHost`) and translates across the storage-engine boundary. Put new SSE logic in the crate unless it needs ecstore, IAM, or request types.
|
||||
- Coordinate related changes with:
|
||||
- `crates/sse/`
|
||||
- `crates/kms/`
|
||||
- `rustfs/src/admin/handlers/kms*.rs`
|
||||
- `crates/ecstore/`
|
||||
|
||||
+2
-1001
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user