From 2fd613157b56e862fb7566167e6a080e0df96aec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E5=B0=8F=E9=B8=AD?= Date: Wed, 25 Nov 2026 06:19:21 +0800 Subject: [PATCH] refactor(sse): extract SSE into the rustfs-sse crate and layer it (#9574) * refactor(sse): extract server-side encryption into rustfs-sse crate Move the SSE-S3 / SSE-KMS / SSE-C key resolution, metadata and authorization logic out of rustfs/src/storage/sse.rs into a new crates/sse (rustfs-sse) so its outward references are explicit. The crate depends only on rustfs-config, rustfs-kms, rustfs-policy, rustfs-s3-types and rustfs-utils. It does not reach the storage engine, IAM, the gateway or the server binary; scripts/check_architecture_migration_rules.sh now pins that dependency set. Everything the crate needs from the running server arrives through the SseHost port (current KMS service, KMS manager state, bucket default encryption, per-key authorization). The host is an explicit parameter on every entry point that needs it rather than a global, so a missing installation cannot silently fall back to the local key provider. The crate reports failures as SseError, which carries the S3 error code. The KMS-to-S3 error mapping moves with it and rustfs/src/error.rs reuses it, so response codes and messages are unchanged. The source of an SSE-internal error is no longer wrapped in StorageError::Io. rustfs/src/storage/sse.rs stays as the adapter: it implements the host, binds the entry points to this server and converts back to ApiError, and keeps the conversions that cross the engine boundary (read-side resolver, multipart completion gate, reader error mapping). Tests split with the code. Four provider round-trips over rio streams move to storage/sse_test.rs because the crate does not depend on rio. Cross-crate test seams sit behind the test-util feature, enabled only from the rustfs dev-dependencies. The rio-v2 CI lane and cache warm-up now include -p rustfs-sse so the rio-v2-only SSE tests keep running. * refactor(sse): remove three unused configuration helpers get_sse_type, sse_configuration_to_metadata and SseTypeV2::to_metadata have no caller in the crate, its tests, or the server. All three carried #[allow(unused)], which is what kept the compiler from reporting them. * refactor(sse): split the crate root into core and kms modules Move every item of the single-file crate into modules without changing any of them: - core/s3: what S3 defines for SSE (request headers, scheme selection, SSE-C validation, key-policy authorization) - core/keying: how RustFS seals and records object keys (key material, direct and object-key forms, stored metadata, encryption context) - core/{request,write,read,rewrap,audit}: the per-request entry points - kms: data-key providers (KMS-backed, local master key, MinIO builtin-KMS ciphertext) and the provider registry The rio-v2 only modules carry the feature gate at module level instead of on each item. Inline tests move to a crate-level tests module. The public surface is unchanged and is now an explicit re-export list in lib.rs; visibility is otherwise tightened to pub(crate) or private. Documentation that cited the old file now points at the module that holds the symbol. * refactor(sse): add an explicit startup step for process-level state Give rustfs-sse one entry point, `startup::init`, for the state that is fixed for the lifetime of the process. The server calls it where it used to log the SSE-KMS key policy mode. - Resolve the key policy enforcement switch once and log its mode. - Check `RUSTFS_SSE_S3_MASTER_KEY` at startup and report it through the `sse_local_master_key` event as `loaded`, `not_set`, or `invalid`. An unusable value is logged as an error; startup still succeeds and requests fail exactly as before. - Return a `StartupReport` so the caller can see both results. Repeated calls return the first report without logging again. Anything that follows the KMS service state stays resolved per request: the service follows configuration and can be started, restarted, or stopped from the admin API while the process runs. `get_local_sse_dek_provider` becomes synchronous, since it never awaited anything. The "Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3" line that was logged when the key was first used is replaced by the startup event. * refactor(sse): split the write path into S3 scheme and keying mode The write entry points mixed two questions: which SSE scheme S3 asks for, and how this build forms and stores the object key. Give each a home. - `core/s3/scheme.rs` gains `resolve_write_scheme`, which validates the headers and resolves the request, then the bucket default, to a `WriteScheme`. PutObject and CreateMultipartUpload now share it; the second copy of that decision (`SseTypeV2`, `prepare_sse_configuration_v2`) is removed. - `core/keying/` gains one constructor per key source (`new_key_under_customer_key`, `new_session_key_under_customer_key`, `new_key_under_data_key`) in each mode. `keying/mod.rs` is the only place that says which mode a build writes. - `core/write.rs` only orders the steps and no longer carries any `rio-v2` conditional compilation. No behavior change. A multipart session still validates the SSE-C key at creation only in the mode that seals the session key under it. `SseTypeV2` leaves the public surface; nothing outside the crate used it. * refactor(sse): split the read path into S3 scheme and keying mode The read entry points decided the scheme, authorized the key, and recovered the object key in one function, with the SSE-C preamble and the managed key resolution written out twice. Separate the steps. - `core/keying/stored.rs` (new) recognizes how a stored object was keyed (`recognize_stored_managed_key`) and recovers its key (`open_under_customer_key`, `open_under_stored_data_key`). The unwrap body moves there unchanged. - `core/s3/ssec.rs` gains `require_matching_ssec_key` and `stored_ssec_algorithm`, shared by the unwrap and the response-header paths. - `core/read.rs` orders the steps: recognize, name the key, authorize, recover. Both read entry points resolve the key through one helper, so authorization and the response header cannot name different keys. - `core/keying/` no longer imports from `core/s3/`: the request check `reject_kms_context_location_override` moves to `core/s3/headers.rs`, and the legacy SSE-C nonce hashes with `md5` directly. `rio-v2` conditional compilation is now confined to `core/keying/` and `kms/`. No behavior change: the order of checks on a read is preserved. * docs(sse): describe the module layout and its layer rules Record in the crate instructions what the split settled: where startup state, the entry points, the S3 layer, the keying layer, and the data-key providers live, and the rules that keep them apart. - `core/keying/` never imports from `core/s3/`; `core/s3/` reads stored metadata only through `core/keying/metadata.rs`. - `rio-v2` conditional compilation stays under `core/keying/` and `kms/`. - A new stored format is added under `core/keying/` without changes under `core/s3/`. * refactor(sse): let each keying mode own its stored record One function wrote the stored metadata of every keying mode, and one function read it back, each switching on the mode and the build inline. Give a mode both directions of its own record instead. - `core/keying/direct.rs` records and reads the Direct record (`record_customer_key_nonce`, `record_wrapped_data_key`, `read_wrapped_data_key`). - `core/keying/object.rs` records and reads the sealed-key record in MinIO's slots (`record_sealed_customer_key`, `record_data_key_in_minio_slots`, `read_sealed_data_key`). - `encryption_material_to_metadata` records the scheme and hands the key to the mode that formed it. - `core/keying/stored.rs` reads in three named steps: the recognition order of the modes (`read_stored_data_key`), the choice of the provider that unwraps the data key (`unwrap_stored_data_key`), and the opening of the object key. A stored key carries its mode as `StoredKeyMode` rather than as an optional sealed key. No behavior change. The stored metadata is identical for every combination of scheme, mode, sealed key, key id, context, and size in both builds, and the order of the read-side failures is preserved. * test(sse): add a black-box suite that compares two server binaries Unit tests cannot show that moving SSE into its own crate left what a client sees, and what lands on disk, unchanged. This suite drives a real server process and can compare two binaries. - 30 cases over six process configurations: no key source, a loaded and an invalid local master key, the Local KMS backend with per-key authorization off and enforced. They cover round trips and response headers, bucket default encryption, CopyObject, multipart uploads, run-time KMS stop and start, malformed requests and authorization. - Every HTTP exchange inside a case is recorded as an observation: status, error code and message, SSE headers, response header names, body hash, and the encryption metadata key names stored for the object. `diff` compares two runs field by field against a closed list of accepted differences. - `cross` has one binary write every stored form and another read the same data directory. - A registered binary is pinned by SHA-256, and a run fails when the stored form does not match the build the binary was registered as. Results for this branch against its base, default build: 93 verdicts and 252 exchanges equal, no blocking difference; the only accepted one is the new `sse_local_master_key` startup event. Cross reads pass in both directions, 42 objects each. The suite also pins two behaviors that predate this branch. Multipart responses for SSE-C uploads carry `x-amz-server-side-encryption: AES256` besides the customer-key headers; MP-03 records that as a known deviation. A `rio-v2` build cannot read back encrypted objects of roughly 64 to 128 KiB, or of 3 MiB and more, so under that build the comparison only shows that both binaries fail the same cases. * test(sse): stop the black-box suite from overlooking two regressions The known-deviation marker in MP-03 accepted any SSE headers that contained the expected ones, so an unrelated extra header, the raw customer key included, was still reported as the known deviation. It now tolerates exactly the one documented difference and fails on anything else. The observation of a result document kept only the set of element names. A wrong part size, a missing part or reordered parts in a listing changed nothing, so a comparison between two binaries could not see them. It now keeps every leaf with its value in document order and reduces only the elements that vary between runs: upload ids, timestamps, markers and ETags of encrypted objects. `suite.py selftest` checks both offline, together with the rules of the comparison. Against the previous observation code it fails on the three listing cases. The comparison of this branch with its base still shows no blocking difference in either build. * test(sse): prepare the black-box suite for P1 cases and more backends The suite could only run P0 cases on six built-in configurations with one shared site each. The next groups of cases need more than that: - `run --level p0|p1|all`, and a `skip` verdict for a case the backend's capability table rules out. - `register_config` lets a case module add a process configuration with what it needs before the process starts, once it answers, and at the end of the run. The two Local KMS configurations now use the same mechanism instead of special cases in the driver. - `isolated` cases get a site of their own on a fresh data directory and may restart it with another configuration or environment. - Exchange hooks and post-run checks, for modules that keep everything a run saw and judge it as a whole. - Case modules are discovered by file name, and the binary registry can be shared between state directories. The P0 results and the comparison with the base are unchanged. * test(sse): cover run-time state, authorization, leaks and stored form Three groups of cases are added to the black-box suite, with what they need to run. Run-time state (14 cases). A write follows the state the process is in now, a read follows what the object recorded: the master key across restarts, KMS stopped, started and configured at run time, a deployment moving between key sources, a changed backend, and keys disabled, destroyed and rotated. New configurations: Local KMS with a master key, Vault Transit, Vault KV2 and the Static backend. Vault is a development server started by the driver with a token generated per run; when it cannot be started its cases report an environment error. Authorization and leaks (18 cases). Per-key authorization on bucket defaults, both ends of a copy, multipart uploads, every read entry point, anonymous access, internal work and audit entries. Every exchange of a run is archived with secrets redacted, and four checks over the whole run look for key material in responses and server logs, for internal headers, and for unexpected internal-error messages. Stored form (8 cases). What an encrypted object looks like on disk is read with the repository's `dump_fileinfo` tool and held to one manifest per build: every metadata key with its exact value or, for random values, its shape. The cases also search the drives for plaintext, customer keys and unwrapped data keys. `cross` records the stored form of everything the writer stored. Compared with the base on the default build, all levels: 382 verdicts and 887 exchanges equal, no blocking difference; 86 case runs pass on each side. Three cases report a known deviation that predates this branch: the multipart SSE-C response header (MP-03), an SSE-KMS write that turns from 400 into 503 after a refused KMS start (KS-09), and a read by a caller without a grant that reveals whether the key was destroyed or KMS is stopped (SEC-05). The manifests were written from the base binaries and the branch stores the same form in both builds. Each group was shown to fail when it should: Vault unavailable gives environment errors, the two authorization configurations swapped fail the matrix both ways, a planted key is found in a log and in a response, a `rio-v2` binary registered as the default build fails the manifest and the build check. * test(sse): expect only customer-key headers on SSE-C multipart replies MP-03 recorded the extra `x-amz-server-side-encryption: AES256` header on SSE-C CreateMultipartUpload and CompleteMultipartUpload responses as a known deviation. The header is gone on main, so the case now checks the intended headers directly; left as a marker it would report the deviation as fixed and fail the run. On both builds the base and this branch pass the case. * test(sse): take the black-box suite out of this repository The suite under `scripts/test/sse_blackbox/` drives a server binary from the outside and compares two binaries. It is a product-level test harness, not part of the server's own tests, and belongs with the other external test suites rather than in this repository. The directory is removed, with the paragraph in `crates/sse/AGENTS.md` that pointed to it. No server code changes. --------- Co-authored-by: Cursor Agent Co-authored-by: Hauser Zhi --- .config/test-count-baseline.txt | 1 + .github/workflows/cache-warm.yml | 2 +- .github/workflows/ci.yml | 4 +- ARCHITECTURE.md | 2 +- CHANGELOG.md | 1 + Cargo.lock | 28 + Cargo.toml | 2 + crates/kms/AGENTS.md | 3 +- crates/sse/AGENTS.md | 55 + crates/sse/Cargo.toml | 70 + crates/sse/src/core/audit.rs | 292 + crates/sse/src/core/keying/context.rs | 67 + crates/sse/src/core/keying/direct.rs | 212 + crates/sse/src/core/keying/material.rs | 115 + crates/sse/src/core/keying/metadata.rs | 270 + crates/sse/src/core/keying/mod.rs | 67 + crates/sse/src/core/keying/object.rs | 436 + crates/sse/src/core/keying/stored.rs | 253 + crates/sse/src/core/mod.rs | 23 + crates/sse/src/core/read.rs | 303 + crates/sse/src/core/request.rs | 148 + crates/sse/src/core/rewrap.rs | 144 + crates/sse/src/core/s3/authorization.rs | 177 + crates/sse/src/core/s3/headers.rs | 454 + crates/sse/src/core/s3/mod.rs | 20 + crates/sse/src/core/s3/scheme.rs | 288 + crates/sse/src/core/s3/ssec.rs | 217 + crates/sse/src/core/write.rs | 550 + crates/sse/src/error.rs | 176 + crates/sse/src/host.rs | 85 + crates/sse/src/kms/kms_backed.rs | 180 + crates/sse/src/kms/local.rs | 323 + crates/sse/src/kms/minio.rs | 151 + crates/sse/src/kms/mod.rs | 21 + crates/sse/src/kms/provider.rs | 288 + crates/sse/src/lib.rs | 110 + crates/sse/src/startup.rs | 250 + crates/sse/src/testing.rs | 70 + crates/sse/src/tests.rs | 4772 ++++++++ docs/architecture/crate-boundaries.md | 2 + docs/architecture/global-state-inventory.md | 2 +- docs/architecture/kms-bulk-rekey-contract.md | 6 +- docs/architecture/minio-file-format-compat.md | 10 +- docs/operations/kms-aws-backend-guide.md | 2 +- .../operations/kms-aws-backend-guide.zh-CN.md | 2 +- rustfs/Cargo.toml | 4 +- rustfs/src/app/multipart_usecase.rs | 2 +- .../src/app/multipart_usecase/upload_part.rs | 3 +- .../app/multipart_usecase/upload_part_copy.rs | 3 +- rustfs/src/app/object/mod.rs | 10 +- rustfs/src/app/owned_audit_test.rs | 2 +- rustfs/src/app/select_object.rs | 4 +- rustfs/src/app/storage_api.rs | 6 +- rustfs/src/error.rs | 85 +- rustfs/src/init.rs | 6 +- rustfs/src/storage/AGENTS.md | 2 + rustfs/src/storage/sse.rs | 9878 ++--------------- rustfs/src/storage/sse_test.rs | 233 + rustfs/src/storage/storage_api.rs | 7 +- rustfs/src/storage_api.rs | 2 +- scripts/check_architecture_migration_rules.sh | 12 +- 61 files changed, 11546 insertions(+), 9367 deletions(-) create mode 100644 crates/sse/AGENTS.md create mode 100644 crates/sse/Cargo.toml create mode 100644 crates/sse/src/core/audit.rs create mode 100644 crates/sse/src/core/keying/context.rs create mode 100644 crates/sse/src/core/keying/direct.rs create mode 100644 crates/sse/src/core/keying/material.rs create mode 100644 crates/sse/src/core/keying/metadata.rs create mode 100644 crates/sse/src/core/keying/mod.rs create mode 100644 crates/sse/src/core/keying/object.rs create mode 100644 crates/sse/src/core/keying/stored.rs create mode 100644 crates/sse/src/core/mod.rs create mode 100644 crates/sse/src/core/read.rs create mode 100644 crates/sse/src/core/request.rs create mode 100644 crates/sse/src/core/rewrap.rs create mode 100644 crates/sse/src/core/s3/authorization.rs create mode 100644 crates/sse/src/core/s3/headers.rs create mode 100644 crates/sse/src/core/s3/mod.rs create mode 100644 crates/sse/src/core/s3/scheme.rs create mode 100644 crates/sse/src/core/s3/ssec.rs create mode 100644 crates/sse/src/core/write.rs create mode 100644 crates/sse/src/error.rs create mode 100644 crates/sse/src/host.rs create mode 100644 crates/sse/src/kms/kms_backed.rs create mode 100644 crates/sse/src/kms/local.rs create mode 100644 crates/sse/src/kms/minio.rs create mode 100644 crates/sse/src/kms/mod.rs create mode 100644 crates/sse/src/kms/provider.rs create mode 100644 crates/sse/src/lib.rs create mode 100644 crates/sse/src/startup.rs create mode 100644 crates/sse/src/testing.rs create mode 100644 crates/sse/src/tests.rs diff --git a/.config/test-count-baseline.txt b/.config/test-count-baseline.txt index 3752eee865..df4bdfb13d 100644 --- a/.config/test-count-baseline.txt +++ b/.config/test-count-baseline.txt @@ -57,6 +57,7 @@ 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 diff --git a/.github/workflows/cache-warm.yml b/.github/workflows/cache-warm.yml index 0cdf5f47af..0606751b5c 100644 --- a/.github/workflows/cache-warm.yml +++ b/.github/workflows/cache-warm.yml @@ -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 --all-targets --features rio-v2 + cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30231221a6..a76f0296ed 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 --all-targets --features rio-v2 -- -D warnings + run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --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 --features rio-v2 \ + cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \ 2>&1 | tee artifacts/workspace/nextest.log cargo test -p rustfs --doc --features rio-v2 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8c3c753268..342cc1408a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -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`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, TLS, and security contracts. | +| 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. | | 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. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 631150c109..de80f697f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -118,6 +118,7 @@ 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. diff --git a/Cargo.lock b/Cargo.lock index b155a30e87..b32e6c04dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10059,6 +10059,7 @@ dependencies = [ "rustfs-scanner-metrics", "rustfs-security-governance", "rustfs-signer", + "rustfs-sse", "rustfs-storage-api", "rustfs-targets", "rustfs-test-utils", @@ -11573,6 +11574,33 @@ 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" diff --git a/Cargo.toml b/Cargo.toml index 8b06ebf631..b0f3e74ab1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,6 +61,7 @@ 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 @@ -142,6 +143,7 @@ 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" } diff --git a/crates/kms/AGENTS.md b/crates/kms/AGENTS.md index ea9caf00b2..eec22319ea 100644 --- a/crates/kms/AGENTS.md +++ b/crates/kms/AGENTS.md @@ -6,7 +6,8 @@ Applies to `crates/kms/`. When changing key-management behavior, verify compatibility with: -- `rustfs/src/storage/sse.rs` +- `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/admin/handlers/kms.rs` - `rustfs/src/admin/handlers/kms_dynamic.rs` - `rustfs/src/admin/handlers/kms_keys.rs` diff --git a/crates/sse/AGENTS.md b/crates/sse/AGENTS.md new file mode 100644 index 0000000000..773d13d62d --- /dev/null +++ b/crates/sse/AGENTS.md @@ -0,0 +1,55 @@ +# 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::/)' +``` diff --git a/crates/sse/Cargo.toml b/crates/sse/Cargo.toml new file mode 100644 index 0000000000..072e9fadeb --- /dev/null +++ b/crates/sse/Cargo.toml @@ -0,0 +1,70 @@ +# 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 diff --git a/crates/sse/src/core/audit.rs b/crates/sse/src/core/audit.rs new file mode 100644 index 0000000000..f1a3455904 --- /dev/null +++ b/crates/sse/src/core/audit.rs @@ -0,0 +1,292 @@ +// 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, + key_versions: BTreeSet, + /// 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); + +impl KmsRequestAudit { + pub(crate) fn record( + &self, + sse_type: SSEType, + key_id: Option<&str>, + key_version: Option, + 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>) -> Value { + let joined = values.map(|value| value.as_ref().to_string()).collect::>(); + 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>>> = 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, +} + +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> { + 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::()) + { + 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>, +} + +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, + 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 { + if !is_data_key_envelope(envelope_bytes) { + return None; + } + u32::try_from( + serde_json::from_slice::(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) -> Option { + // 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) +} diff --git a/crates/sse/src/core/keying/context.rs b/crates/sse/src/core/keying/context.rs new file mode 100644 index 0000000000..ca429d279a --- /dev/null +++ b/crates/sse/src/core/keying/context.rs @@ -0,0 +1,67 @@ +// 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>, +) -> HashMap { + 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>, +) -> 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) -> Result { + 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) -> Result>, 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}"))) +} diff --git a/crates/sse/src/core/keying/direct.rs b/crates/sse/src/core/keying/direct.rs new file mode 100644 index 0000000000..91cf3606ac --- /dev/null +++ b/crates/sse/src/core/keying/direct.rs @@ -0,0 +1,212 @@ +// 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, 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, + 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, +) -> Result { + 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, 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 { + 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 { + Ok(NewObjectKey { + key_bytes: [0; 32], + base_nonce: random_base_nonce(), + key_kind: EncryptionKeyKind::Direct, + sealed_key: None, + }) +} + +/// Managed SSE: the data key encrypts the object itself, under the nonce issued with it. +#[cfg(not(feature = "rio-v2"))] +pub(crate) fn new_key_under_data_key( + data_key: &DataKey, + _sse_type: SSEType, + _bucket: &str, + _key: &str, +) -> Result { + Ok(NewObjectKey { + key_bytes: data_key.plaintext_key, + base_nonce: data_key.nonce, + key_kind: EncryptionKeyKind::Direct, + sealed_key: None, + }) +} diff --git a/crates/sse/src/core/keying/material.rs b/crates/sse/src/core/keying/material.rs new file mode 100644 index 0000000000..35af1ca08c --- /dev/null +++ b/crates/sse/src/core/keying/material.rs @@ -0,0 +1,115 @@ +// 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, + + #[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>, + /// SSE-C key MD5 if customer-managed encryption is in use. + pub customer_key_md5: Option, + /// Original plaintext size when it should be persisted alongside metadata. + pub original_size: Option, + /// 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>, + /// 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, +} + +/// 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, + #[allow(unused)] + pub algorithm: String, + pub customer_key_md5: Option, // 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 { + matches!(self.sse_type, SSEType::SseKms) + .then(|| self.kms_key_id.clone()) + .flatten() + } +} diff --git a/crates/sse/src/core/keying/metadata.rs b/crates/sse/src/core/keying/metadata.rs new file mode 100644 index 0000000000..f7209f75d6 --- /dev/null +++ b/crates/sse/src/core/keying/metadata.rs @@ -0,0 +1,270 @@ +// 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, +) -> Result>, 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, 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, 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, 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) { + 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) { + 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) -> 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) -> 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 { + let decoded = BASE64_STANDARD.decode_to_vec(value).ok()?; + let context = serde_json::from_slice::>(&decoded).ok()?; + serde_json::to_string(&context).ok() +} diff --git a/crates/sse/src/core/keying/mod.rs b/crates/sse/src/core/keying/mod.rs new file mode 100644 index 0000000000..196740270c --- /dev/null +++ b/crates/sse/src/core/keying/mod.rs @@ -0,0 +1,67 @@ +// 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, +} + +/// 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, + /// 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, +}; diff --git a/crates/sse/src/core/keying/object.rs b/crates/sse/src/core/keying/object.rs new file mode 100644 index 0000000000..3797645e60 --- /dev/null +++ b/crates/sse/src/core/keying/object.rs @@ -0,0 +1,436 @@ +// 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; + +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, 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 { + 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, 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, 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) -> 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) -> Option { + 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, + sse_type: SSEType, +) -> Result, 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, 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, + 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, + normalized_metadata: &HashMap, + sealed_key: ManagedSealedKey, +) -> Result { + 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 { + let object_key = derive_object_key(external_key)?; + let sealed_key = seal_object_key(object_key, external_key, sse_type, bucket, key)?; + Ok(NewObjectKey { + key_bytes: object_key, + base_nonce: [0; 12], + key_kind: EncryptionKeyKind::Object, + sealed_key: Some(sealed_key), + }) +} + +/// SSE-C object: an object key sealed under the customer key. +pub(crate) fn new_key_under_customer_key(customer_key: [u8; 32], bucket: &str, key: &str) -> Result { + new_sealed_object_key(customer_key, SSEType::SseC, bucket, key) +} + +/// SSE-C multipart session: an object key sealed under the customer key. +/// +/// A session created without its customer key has nothing to seal and records a +/// placeholder instead. +pub(crate) fn new_session_key_under_customer_key( + customer_key: Option<[u8; 32]>, + bucket: &str, + key: &str, +) -> Result { + match customer_key { + Some(customer_key) => new_sealed_object_key(customer_key, SSEType::SseC, bucket, key), + None => Ok(NewObjectKey { + key_bytes: [0; 32], + base_nonce: [0; 12], + key_kind: EncryptionKeyKind::Direct, + sealed_key: None, + }), + } +} + +/// Managed SSE: an object key sealed under the data key. +pub(crate) fn new_key_under_data_key( + data_key: &DataKey, + sse_type: SSEType, + bucket: &str, + key: &str, +) -> Result { + new_sealed_object_key(data_key.plaintext_key, sse_type, bucket, key) +} diff --git a/crates/sse/src/core/keying/stored.rs b/crates/sse/src/core/keying/stored.rs new file mode 100644 index 0000000000..c581185501 --- /dev/null +++ b/crates/sse/src/core/keying/stored.rs @@ -0,0 +1,253 @@ +// 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) -> Option { + 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, + customer_key: [u8; 32], + bucket: &str, + key: &str, +) -> Result { + #[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, + /// The same metadata with the managed keys normalized. + normalized_metadata: HashMap, + /// 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, +} + +/// 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) -> Option> { + 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 { + #[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 = 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 +} diff --git a/crates/sse/src/core/mod.rs b/crates/sse/src/core/mod.rs new file mode 100644 index 0000000000..5bb7d6b3cb --- /dev/null +++ b/crates/sse/src/core/mod.rs @@ -0,0 +1,23 @@ +// 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; diff --git a/crates/sse/src/core/read.rs b/crates/sse/src/core/read.rs new file mode 100644 index 0000000000..76443cb6f8 --- /dev/null +++ b/crates/sse/src/core/read.rs @@ -0,0 +1,303 @@ +// 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, + /// 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, 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, 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, +) -> 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, + sse_key: &str, + sse_key_md5: &str, +) -> Result { + // 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, + principal: Option<&SseKmsPrincipal>, +) -> Result, 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, + principal: Option<&SseKmsPrincipal>, +) -> Result, 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, + })) +} diff --git a/crates/sse/src/core/request.rs b/crates/sse/src/core/request.rs new file mode 100644 index 0000000000..dd33d64ecd --- /dev/null +++ b/crates/sse/src/core/request.rs @@ -0,0 +1,148 @@ +// 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>, + is_owner: bool, + claims: HashMap, + conditions: HashMap>, + /// 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>, + /// 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, +} + +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>, + is_owner: bool, + claims: HashMap, + conditions: HashMap>, + ) -> 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> { + &self.groups + } + + pub fn is_owner(&self) -> bool { + self.is_owner + } + + pub fn claims(&self) -> &HashMap { + &self.claims + } + + /// Policy condition values of the request that do not depend on the resource. + pub fn conditions(&self) -> &HashMap> { + &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) -> Self { + self.test_hooks = hooks; + self + } + + #[cfg(test)] + pub(crate) fn for_test(account: &str, enforced: bool, authorizer: Arc) -> 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) -> 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, +} + +#[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() + } +} diff --git a/crates/sse/src/core/rewrap.rs b/crates/sse/src/core/rewrap.rs new file mode 100644 index 0000000000..816badf374 --- /dev/null +++ b/crates/sse/src/core/rewrap.rs @@ -0,0 +1,144 @@ +// 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 }, +} + +/// 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, +) -> Result { + 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 }) +} diff --git a/crates/sse/src/core/s3/authorization.rs b/crates/sse/src/core/s3/authorization.rs new file mode 100644 index 0000000000..9067348b37 --- /dev/null +++ b/crates/sse/src/core/s3/authorization.rs @@ -0,0 +1,177 @@ +// 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 { + #[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, +) -> 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, +) -> 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 +} diff --git a/crates/sse/src/core/s3/headers.rs b/crates/sse/src/core/s3/headers.rs new file mode 100644 index 0000000000..0c9bf565f3 --- /dev/null +++ b/crates/sse/src/core/s3/headers.rs @@ -0,0 +1,454 @@ +// 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, Option, Option); + +/// 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 { + 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, 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>, 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>, +) -> 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>, + 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, 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, + pub sse_customer_key_md5: Option, + pub ssekms_key_id: Option, +} + +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, + sse_customer_algorithm: Option<&String>, + sse_customer_key_md5: Option<&String>, +) -> Result { + 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::>(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) +} diff --git a/crates/sse/src/core/s3/mod.rs b/crates/sse/src/core/s3/mod.rs new file mode 100644 index 0000000000..be544f0d6b --- /dev/null +++ b/crates/sse/src/core/s3/mod.rs @@ -0,0 +1,20 @@ +// 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; diff --git a/crates/sse/src/core/s3/scheme.rs b/crates/sse/src/core/s3/scheme.rs new file mode 100644 index 0000000000..e270ee3597 --- /dev/null +++ b/crates/sse/src/core/s3/scheme.rs @@ -0,0 +1,288 @@ +// 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, +} + +/// 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, + ssekms_key_id: Option, +) -> Result, 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( + effective_sse: Option<&str>, + requested_kms_key_id: Option, + bucket_default_kms_key_id: F, +) -> Option +where + F: FnOnce() -> Option, +{ + 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, + pub(crate) ssekms_key_id: Option, + pub(crate) ssekms_context: Option<&'a HashMap>, + pub(crate) sse_customer_algorithm: Option, + pub(crate) sse_customer_key: Option, + pub(crate) sse_customer_key_md5: Option, +} + +/// The scheme a write resolved to, in S3's terms. +#[derive(Clone)] +pub(crate) enum WriteScheme { + /// `AES256`: the server chooses the wrapping key and the caller names none. + SseS3, + /// `aws:kms`, under the key the request or the bucket default named, if either did. + SseKms { key_id: Option }, + /// A key the client supplies; only its MD5 is ever stored. + SseC { + algorithm: String, + key: String, + key_md5: String, + }, +} + +impl std::fmt::Debug for WriteScheme { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::SseS3 => "SseS3", + Self::SseKms { .. } => "SseKms(..)", + Self::SseC { .. } => "SseC(..)", + }) + } +} + +/// 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, 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 { + 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") +} diff --git a/crates/sse/src/core/s3/ssec.rs b/crates/sse/src/core/s3/ssec.rs new file mode 100644 index 0000000000..542fdd61fc --- /dev/null +++ b/crates/sse/src/core/s3/ssec.rs @@ -0,0 +1,217 @@ +// 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 { + 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) -> &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, + 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, + 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, + } +} diff --git a/crates/sse/src/core/write.rs b/crates/sse/src/core/write.rs new file mode 100644 index 0000000000..f1442d95e2 --- /dev/null +++ b/crates/sse/src/core/write.rs @@ -0,0 +1,550 @@ +// 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, + /// KMS key ID (for SSE-KMS) + pub ssekms_key_id: Option, + /// Optional client-provided KMS context for SSE-KMS. + pub ssekms_context: Option>, + /// SSE-C algorithm (customer-provided key) + pub sse_customer_algorithm: Option, + /// SSE-C key (Base64-encoded) + pub sse_customer_key: Option, + /// SSE-C key MD5 (Base64-encoded) + pub sse_customer_key_md5: Option, + /// 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) -> 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) -> 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, 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, + /// KMS key ID (for SSE-KMS) + pub ssekms_key_id: Option, + /// Optional client-provided KMS context for SSE-KMS. + pub ssekms_context: Option>, + /// SSE-C algorithm (customer-provided key) + pub sse_customer_algorithm: Option, + /// SSE-C key (Base64-encoded) + pub sse_customer_key: Option, + /// SSE-C key MD5 (Base64-encoded) + pub sse_customer_key_md5: Option, + /// 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, 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, + sse_key_md5: String, +) -> Result { + // 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 { + 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, + pub(crate) ssekms_context: Option>, + 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 { + // 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 { + 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, + } +} diff --git a/crates/sse/src/error.rs b/crates/sse/src/error.rs new file mode 100644 index 0000000000..092853216d --- /dev/null +++ b/crates/sse/src/error.rs @@ -0,0 +1,176 @@ +// 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; + +/// 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, +} + +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) -> Self { + let source = error.into(); + let (code, message) = if source.downcast_ref::().is_some() { + (S3ErrorCode::ServiceUnavailable, SERVICE_UNAVAILABLE_MESSAGE.to_string()) + } else if let Some(classified) = source.downcast_ref::().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); + } +} diff --git a/crates/sse/src/host.rs b/crates/sse/src/host.rs new file mode 100644 index 0000000000..821df7b3db --- /dev/null +++ b/crates/sse/src/host.rs @@ -0,0 +1,85 @@ +// 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>; + + /// 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>; + + /// 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, 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, +} + +/// 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, +} + +/// 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; +} diff --git a/crates/sse/src/kms/kms_backed.rs b/crates/sse/src/kms/kms_backed.rs new file mode 100644 index 0000000000..414b45b882 --- /dev/null +++ b/crates/sse/src/kms/kms_backed.rs @@ -0,0 +1,180 @@ +// 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), +} + +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 { + 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) -> Result { + 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> { + 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), 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 { + 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) + } +} diff --git a/crates/sse/src/kms/local.rs b/crates/sse/src/kms/local.rs new file mode 100644 index 0000000000..b6ee4b3fb1 --- /dev/null +++ b/crates/sse/src/kms/local.rs @@ -0,0 +1,323 @@ +// 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= +/// ``` +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 { + 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::>(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| { + 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 { + 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 { + fn sse_not_configured(message: impl Into) -> 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 { + // Use AES-256-GCM to encrypt DEK + let key = Key::::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::>(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::::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), 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) + } +} diff --git a/crates/sse/src/kms/minio.rs b/crates/sse/src/kms/minio.rs new file mode 100644 index 0000000000..4f9f7c69cf --- /dev/null +++ b/crates/sse/src/kms/minio.rs @@ -0,0 +1,151 @@ +// 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, 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::(text) => + { + let decode = |what: &str, value: &str| -> Result, 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| SseError::internal(format!("MinIO KMS data key must be 32 bytes, got {}", value.len()))) +} diff --git a/crates/sse/src/kms/mod.rs b/crates/sse/src/kms/mod.rs new file mode 100644 index 0000000000..931d12d34f --- /dev/null +++ b/crates/sse/src/kms/mod.rs @@ -0,0 +1,21 @@ +// 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; diff --git a/crates/sse/src/kms/provider.rs b/crates/sse/src/kms/provider.rs new file mode 100644 index 0000000000..bbd7ac4553 --- /dev/null +++ b/crates/sse/src/kms/provider.rs @@ -0,0 +1,288 @@ +// 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), 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 { + 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>, + local: Result, 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, 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> { + 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>>> = + 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>>> = 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, 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, 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 = 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 = 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) { + 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> { + GLOBAL_KMS_DEK_PROVIDER.read().ok().and_then(|guard| guard.as_ref().cloned()) +} diff --git a/crates/sse/src/lib.rs b/crates/sse/src/lib.rs new file mode 100644 index 0000000000..d77cb5fc86 --- /dev/null +++ b/crates/sse/src/lib.rs @@ -0,0 +1,110 @@ +// 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"; diff --git a/crates/sse/src/startup.rs b/crates/sse/src/startup.rs new file mode 100644 index 0000000000..c882f749aa --- /dev/null +++ b/crates/sse/src/startup.rs @@ -0,0 +1,250 @@ +// 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 = 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 = + 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 { + 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) { + 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(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); + } +} diff --git a/crates/sse/src/testing.rs b/crates/sse/src/testing.rs new file mode 100644 index 0000000000..f7d0d87f82 --- /dev/null +++ b/crates/sse/src/testing.rs @@ -0,0 +1,70 @@ +// 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>, +} + +impl RecordingKmsKeyAuthorizer { + pub fn new(allowed: bool) -> Arc { + 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 { + 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 { + 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()), + ]) +} diff --git a/crates/sse/src/tests.rs b/crates/sse/src/tests.rs new file mode 100644 index 0000000000..2037cb7a26 --- /dev/null +++ b/crates/sse/src/tests.rs @@ -0,0 +1,4772 @@ +// 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 crate::core::keying::context::{build_kms_request_context, encode_minio_kms_context}; +use crate::core::keying::direct::generate_ssec_nonce; +use crate::core::keying::material::{DecryptionMaterial, EncryptionKeyKind, EncryptionMaterial}; +use crate::core::keying::metadata::{ + encryption_material_to_metadata, mark_encrypted_multipart_metadata, recode_minio_kms_context, + strip_managed_encryption_metadata, +}; +#[cfg(feature = "rio-v2")] +use crate::core::keying::object::{ + DARE_CIPHER_AES_256_GCM, DARE_CIPHER_CHACHA20_POLY1305, MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM, SEALED_KEY_IV_SIZE, + SEALED_KEY_SIZE, is_legacy_rustfs_managed_metadata, is_supported_sealed_object_key_cipher, +}; +use crate::core::read::{DecryptionRequest, apply_managed_decryption_material, classify_sse_read_response, sse_decryption}; +use crate::core::request::SseKmsPrincipal; +use crate::core::rewrap::{ObjectDekRewrapOutcome, rewrap_object_encryption_metadata}; +use crate::core::s3::authorization::authorize_sse_kms_object_read; +use crate::core::s3::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, +}; +use crate::core::s3::scheme::{is_managed_sse, resolve_effective_kms_key_id, resolve_stored_kms_key_id}; +use crate::core::s3::ssec::{SsecParams, md5_base64, validate_ssec_for_read, validate_ssec_params, verify_ssec_key_match}; +use crate::core::write::ManagedEncryptionRequest; +use crate::core::write::{ + EncryptionRequest, PrepareEncryptionRequest, apply_managed_encryption_material, apply_managed_encryption_material_inner, + sse_encryption, sse_prepare_encryption, +}; +use crate::error::INTERNAL_ERROR_MESSAGE; +use crate::error::{KMS_KEY_NOT_FOUND_ERROR_CODE, SseError}; +use crate::host::KmsKeyAuthorizer; +use crate::kms::kms_backed::{KmsSseDekProvider, kms_operation_error}; +use crate::kms::local::TestSseDekProvider; +use crate::kms::provider::{SseDekProvider, reset_sse_dek_provider}; +use crate::testing::{RecordingKmsKeyAuthorizer, sse_kms_object_metadata}; +use rustfs_kms::{DataKey, KmsUnavailableError}; +use rustfs_policy::policy::action::KmsAction; +use rustfs_utils::http::headers::SSEC_ALGORITHM_HEADER; +use rustfs_utils::http::object_encryption_keys::{ + INTERNAL_ENCRYPTION_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER, + INTERNAL_ENCRYPTION_KEY_ID_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, normalize_managed_metadata, +}; + +/// The server these tests run in: none. +/// +/// No KMS is serving, bucket metadata cannot be read, and no policy subsystem +/// can decide a key permission — the state of a process in which no server +/// component has started. A test that needs a KMS injects a provider; a test +/// that needs an authorization decision attaches hooks to its principal. +struct DetachedHost; + +static HOST: DetachedHost = DetachedHost; + +struct NoPolicySubsystem; + +#[async_trait] +impl KmsKeyAuthorizer for NoPolicySubsystem { + async fn is_allowed(&self, _principal: &SseKmsPrincipal, _action: KmsAction, _key_id: &str) -> Result { + Err(SseError::internal("KMS key authorization requires IAM: no policy subsystem is running")) + } +} + +#[async_trait] +impl crate::host::SseHost for DetachedHost { + async fn encryption_service(&self) -> Option> { + None + } + + fn kms_service_manager(&self) -> Option> { + None + } + + async fn bucket_encryption(&self, _bucket: &str) -> Result, SseError> { + Err(SseError::internal("bucket metadata sys not initialized for this instance")) + } + + fn kms_key_authorizer(&self) -> &dyn KmsKeyAuthorizer { + &NoPolicySubsystem + } +} + +/// backlog#1643 PR-B0 acceptance guard: the managed-SSE classifier must +/// have exactly one definition — in the shared encryption-keys module — +/// so the scanner and the S3 layer can never disagree on attribution. +/// This module may only re-export or call it. +#[test] +fn managed_sse_classifier_has_exactly_one_definition() { + let classifier_fns = [ + "contains_managed_encryption_metadata", + "normalize_managed_metadata", + "stored_managed_encryption_key", + ]; + + let sse_src = include_str!("lib.rs"); + let shared_src = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../utils/src/http/object_encryption_keys.rs")) + .expect("shared encryption-keys module should be readable"); + + for name in classifier_fns { + // Built at runtime so this test's own source cannot satisfy the scan. + let definition = format!("fn {name}("); + assert!( + !sse_src.contains(&definition), + "{name} must not be redefined in this crate; call the shared rustfs_utils::http::object_encryption_keys implementation instead" + ); + assert_eq!( + shared_src.matches(&definition).count(), + 1, + "{name} must be defined exactly once, in the shared encryption-keys module" + ); + } +} + +#[test] +fn ssec_read_headers_are_sensitive() { + let headers = crate::core::s3::headers::build_ssec_read_headers( + Some(&"AES256".to_string()), + Some(&"dHJhbnNwb3J0LXNlY3JldA==".to_string()), + Some(&"bWQ1LXNlY3JldA==".to_string()), + ); + + assert_eq!(headers.len(), 3); + assert!(headers.values().all(HeaderValue::is_sensitive)); + let debug = format!("{headers:?}"); + assert!(!debug.contains("dHJhbnNwb3J0LXNlY3JldA==")); + assert!(!debug.contains("bWQ1LXNlY3JldA==")); +} + +#[test] +fn parse_simple_sse_cmk_rejects_bad_keys_without_crashing() { + // Empty / whitespace-only. + assert!(crate::kms::local::parse_simple_sse_cmk("").is_err()); + assert!(crate::kms::local::parse_simple_sse_cmk(" ").is_err()); + // Not valid base64. + assert!(crate::kms::local::parse_simple_sse_cmk("@@@not-base64@@@").is_err()); + // Valid base64 but wrong length (16 bytes). + let short = BASE64_STANDARD.encode_to_string([1u8; 16]); + assert!(crate::kms::local::parse_simple_sse_cmk(&short).is_err()); + // All-zero 32-byte key is rejected. + let zero = BASE64_STANDARD.encode_to_string([0u8; 32]); + assert!(crate::kms::local::parse_simple_sse_cmk(&zero).is_err()); +} + +#[test] +fn kms_operation_errors_preserve_retryability_classification() { + let unavailable = kms_operation_error(rustfs_kms::KmsError::backend_error("connection refused")); + let corrupt = kms_operation_error(rustfs_kms::KmsError::cryptographic_error("decrypt", "authentication failed")); + let missing = kms_operation_error(rustfs_kms::KmsError::key_not_found("no-such-key")); + + assert_eq!(unavailable.code, S3ErrorCode::ServiceUnavailable); + assert_eq!(corrupt.code, S3ErrorCode::InternalError); + assert_eq!(missing.code, S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into())); + assert_eq!(crate::core::audit::kms_data_plane_error_class(&missing), "key_not_found"); +} + +/// An unwrap the backend rejects stays an internal error, but says why in +/// words an operator can act on rather than the generic 500 text. +#[test] +fn kms_unwrap_error_keeps_500_but_names_the_envelope_mismatch() { + let rejected = + crate::kms::kms_backed::kms_unwrap_error(rustfs_kms::KmsError::cryptographic_error("decrypt", "authentication failed")); + assert_eq!(rejected.code, S3ErrorCode::InternalError); + assert!(rejected.message.contains("could not be unwrapped"), "message was {}", rejected.message); + assert_eq!(crate::core::audit::kms_data_plane_error_class(&rejected), "cryptographic"); + + let missing = crate::kms::kms_backed::kms_unwrap_error(rustfs_kms::KmsError::key_not_found("no-such-key")); + assert_eq!(missing.code, S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into())); + assert_eq!(missing.message, "KMS key not found: no-such-key"); +} + +#[test] +fn sse_kms_never_falls_back_to_the_local_sse_s3_provider() { + let unconfigured = crate::core::write::sse_kms_unavailable_error(false); + assert_eq!(unconfigured.code, S3ErrorCode::InvalidRequest); + assert!(unconfigured.message.contains("SSE-KMS requires")); + + let stopped = crate::core::write::sse_kms_unavailable_error(true); + assert_eq!(stopped.code, S3ErrorCode::ServiceUnavailable); +} + +fn managed_write(algorithm: &'static str, kms_key_id: Option<&str>) -> EncryptionRequest<'static> { + EncryptionRequest { + bucket: "finance", + key: "ledger.csv", + server_side_encryption: Some(String::from(algorithm)), + ssekms_key_id: kms_key_id.map(str::to_string), + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 128, + principal: None, + } +} + +/// A bucket default naming a KMS key, on a node with no KMS, used to write +/// the object under the local master key while stamping `aws:kms` and that +/// never-consulted key id into the metadata (backlog#2368 B4). +#[tokio::test] +async fn sse_kms_write_is_refused_when_only_a_local_master_key_is_available() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::), + ("RUSTFS_SSE_S3_MASTER_KEY", Some(BASE64_STANDARD.encode_to_string([9u8; 32]))), + ], + async { + let error = sse_encryption( + &HOST, + managed_write(AMZ_ENCRYPTION_KMS, Some("arn:aws:kms:us-east-1:123:key/nonexistent")), + ) + .await + .expect_err("SSE-KMS must not be served by the local master key"); + + assert_eq!(error.code, S3ErrorCode::InvalidRequest); + assert!(error.message.contains("SSE-KMS requires"), "message was {}", error.message); + }, + ) + .await; + + reset_sse_dek_provider(); +} + +/// Without a master key the local fallback fails with an SSE-S3-worded +/// configuration error. An SSE-KMS request must not be told to set +/// `RUSTFS_SSE_S3_MASTER_KEY`. +#[tokio::test] +async fn sse_kms_refusal_names_sse_kms_rather_than_the_sse_s3_master_key() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::), + ("RUSTFS_SSE_S3_MASTER_KEY", None::), + ], + async { + let error = sse_encryption(&HOST, managed_write(AMZ_ENCRYPTION_KMS, Some("finance-key"))) + .await + .expect_err("SSE-KMS must be refused when no KMS is configured"); + + assert_eq!(error.code, S3ErrorCode::InvalidRequest); + assert!(error.message.contains("SSE-KMS requires"), "message was {}", error.message); + assert!( + !error.message.contains("RUSTFS_SSE_S3_MASTER_KEY"), + "an SSE-KMS refusal must not name the SSE-S3 master key: {}", + error.message + ); + }, + ) + .await; + + reset_sse_dek_provider(); +} + +/// A bare `aws:kms` request (no key id, no bucket default) on a node with +/// no KMS has no key to resolve. It must get the same configuration +/// refusal as the keyed form, whether or not the SSE-S3 master key is +/// set, rather than an untyped internal error (backlog#2368 B4). +#[tokio::test] +async fn sse_kms_write_without_a_key_id_is_refused_like_the_keyed_form() { + let _guard = lock_sse_test_state().await; + + for master_key in [None, Some(BASE64_STANDARD.encode_to_string([9u8; 32]))] { + reset_sse_dek_provider(); + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::), + ("RUSTFS_SSE_S3_MASTER_KEY", master_key.clone()), + ], + async { + // Entered directly: `sse_encryption` consults the bucket + // default first, which needs a bucket metadata store. + let error = apply_managed_encryption_material( + &HOST, + ManagedEncryptionRequest { + bucket: "finance", + key: "ledger.csv", + server_side_encryption: String::from(AMZ_ENCRYPTION_KMS), + kms_key_id: None, + ssekms_context: None, + content_size: 128, + principal: None, + }, + ) + .await + .expect_err("SSE-KMS without a key id must be refused when no KMS is running"); + + assert_eq!( + error.code, + S3ErrorCode::InvalidRequest, + "master_key={master_key:?}: message was {}", + error.message + ); + assert!(error.message.contains("SSE-KMS requires"), "message was {}", error.message); + assert!( + !error.message.contains("RUSTFS_SSE_S3_MASTER_KEY"), + "an SSE-KMS refusal must not name the SSE-S3 master key: {}", + error.message + ); + }, + ) + .await; + } + + reset_sse_dek_provider(); +} + +/// The SSE-S3 local fallback itself is unchanged: refusing SSE-KMS must not +/// take the documented no-KMS deployment down with it. +#[tokio::test] +async fn sse_s3_write_still_uses_the_local_master_key_fallback() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::), + ("RUSTFS_SSE_S3_MASTER_KEY", Some(BASE64_STANDARD.encode_to_string([9u8; 32]))), + ], + async { + let material = sse_encryption(&HOST, managed_write(AMZ_ENCRYPTION_AES, None)) + .await + .expect("SSE-S3 keeps its local master key fallback") + .expect("managed sse-s3 material"); + + assert_eq!(material.sse_type, SSEType::SseS3); + assert_eq!(material.algorithm, AMZ_ENCRYPTION_AES); + + // No object may claim aws:kms while its DEK is wrapped locally. + let metadata = encryption_material_to_metadata(&material).expect("sse-s3 metadata should serialize"); + assert!( + !metadata.iter().any(|(_, value)| value == AMZ_ENCRYPTION_KMS), + "local-master-key material must never be stamped aws:kms: {metadata:?}" + ); + }, + ) + .await; + + reset_sse_dek_provider(); +} + +#[test] +fn parse_simple_sse_cmk_accepts_valid_32_byte_key() { + let mut key = [0u8; 32]; + key[0] = 7; + let encoded = BASE64_STANDARD.encode_to_string(key); + let got = crate::kms::local::parse_simple_sse_cmk(&encoded).expect("valid 32-byte key must parse"); + assert_eq!(got, key); +} +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 http::{HeaderMap, HeaderValue}; +use rustfs_kms::types::ObjectEncryptionContext; +use rustfs_s3_types::S3ErrorCode; +use rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT; +use rustfs_utils::http::headers::{AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS}; +use std::collections::HashMap; +use std::sync::{Arc, OnceLock}; +use temp_env::async_with_vars; +use tokio::sync::Mutex; + +static SSE_TEST_LOCK: OnceLock> = OnceLock::new(); +static SSE_TEST_KMS_KEY_DIR: OnceLock = OnceLock::new(); + +pub(crate) async fn lock_sse_test_state() -> tokio::sync::MutexGuard<'static, ()> { + SSE_TEST_LOCK.get_or_init(|| Mutex::new(())).lock().await +} + +async fn configure_test_global_local_kms() -> Arc { + let key_dir = SSE_TEST_KMS_KEY_DIR.get_or_init(|| tempfile::TempDir::new().expect("create KMS key directory")); + let manager = rustfs_kms::init_global_kms_service_manager(); + manager + .reconfigure(rustfs_kms::KmsConfig::local(key_dir.path().to_path_buf()).with_insecure_development_defaults()) + .await + .expect("configure test KMS service"); + manager +} + +#[tokio::test] +async fn resolve_stored_kms_key_id_prefers_the_stored_id() { + assert_eq!(resolve_stored_kms_key_id(&HOST, Some("app-key".to_string())).await, "app-key"); +} + +#[test] +fn normalize_encryption_metadata_case_accepts_lowercase_minio_internal_keys() { + let lowercase_key = MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_ascii_lowercase(); + let metadata = HashMap::from([(lowercase_key, "sealed-key".to_string())]); + + let normalized = + crate::core::keying::metadata::normalize_encryption_metadata_case(&metadata).expect("metadata aliases should normalize"); + + assert_eq!( + normalized.get(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER), + Some(&"sealed-key".to_string()) + ); +} + +struct UnavailableSseDekProvider; + +#[async_trait::async_trait] +impl SseDekProvider for UnavailableSseDekProvider { + async fn generate_sse_dek( + &self, + _context: &ObjectEncryptionContext, + _kms_key_id: &str, + ) -> Result<(DataKey, Vec), SseError> { + Err(SseError::internal(KmsUnavailableError)) + } + + async fn decrypt_sse_dek( + &self, + _encrypted_dek: &[u8], + _kms_key_id: &str, + _context: &ObjectEncryptionContext, + ) -> Result<[u8; 32], SseError> { + Err(SseError::internal(KmsUnavailableError)) + } +} + +fn local_sse_master_key_b64() -> String { + BASE64_STANDARD.encode_to_string([0x24u8; 32]) +} + +#[test] +fn test_extract_ssec_params_from_headers() { + let mut headers = http::HeaderMap::new(); + let (algo, key, md5) = extract_ssec_params_from_headers(&headers).unwrap(); + assert!(algo.is_none()); + assert!(key.is_none()); + assert!(md5.is_none()); + + headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static("AES256")); + let (algo, key, md5) = extract_ssec_params_from_headers(&headers).unwrap(); + assert_eq!(algo.as_deref(), Some("AES256")); + assert!(key.is_none()); + assert!(md5.is_none()); + + headers.insert( + "x-amz-server-side-encryption-customer-key", + HeaderValue::from_static("pO3upElrwuEXSoFwCfnZPdSsmt/xWeFa0N9KgDijwVs="), + ); + headers.insert( + "x-amz-server-side-encryption-customer-key-md5", + HeaderValue::from_static("DWygnHRtgiJ77HCm+1rvHw=="), + ); + let (algo, key, md5) = extract_ssec_params_from_headers(&headers).unwrap(); + assert_eq!(algo.as_deref(), Some("AES256")); + assert!(key.is_some()); + assert!(md5.is_some()); +} + +#[test] +fn test_extract_ssec_params_from_headers_rejects_invalid_utf8() { + let mut headers = http::HeaderMap::new(); + // Header value with invalid UTF-8; to_str() will fail + let invalid_utf8 = HeaderValue::from_bytes(b"invalid-\x80-utf8").unwrap(); + headers.insert("x-amz-server-side-encryption-customer-algorithm", invalid_utf8); + let result = extract_ssec_params_from_headers(&headers); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[test] +fn test_extract_server_side_encryption_from_headers_rejects_invalid_utf8() { + let mut headers = http::HeaderMap::new(); + let invalid_utf8 = HeaderValue::from_bytes(b"aes:kms-\x80-invalid").unwrap(); + headers.insert("x-amz-server-side-encryption", invalid_utf8); + let result = extract_server_side_encryption_from_headers(&headers); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[test] +fn test_extract_ssekms_context_from_headers_decodes_base64_json() { + let mut headers = http::HeaderMap::new(); + let encoded = BASE64_STANDARD + .encode_to_string(serde_json::to_vec(&HashMap::from([("tenant".to_string(), "alpha".to_string())])).unwrap()); + headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT, HeaderValue::from_str(&encoded).unwrap()); + + let context = extract_ssekms_context_from_headers(&headers) + .expect("kms context header should parse") + .expect("kms context should exist"); + assert_eq!(context.get("tenant").map(String::as_str), Some("alpha")); +} + +#[test] +fn test_validate_sse_headers_for_write_rejects_algorithm_without_key() { + let algorithm = "AES256".to_string(); + let result = validate_sse_headers_for_write( + None, + None, + None, + Some(&algorithm), + None, + None, + true, // PutObject requires all three + ); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_sse_headers_for_write_rejects_algorithm_and_key_without_md5() { + let algorithm = "AES256".to_string(); + let key = "pO3upElrwuEXSoFwCfnZPdSsmt/xWeFa0N9KgDijwVs=".to_string(); + let result = validate_sse_headers_for_write( + None, + None, + None, + Some(&algorithm), + Some(&key), + None, + true, // PutObject requires all three + ); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_sse_headers_for_write_rejects_invalid_sse_algorithm() { + let bad_sse = String::from("aes:kms"); + let result = validate_sse_headers_for_write(Some(&bad_sse), None, None, None, None, None, true); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[test] +fn test_validate_sse_headers_for_write_rejects_ssec_with_managed_sse() { + let algorithm = "AES256".to_string(); + let key = "pO3upElrwuEXSoFwCfnZPdSsmt/xWeFa0N9KgDijwVs=".to_string(); + let key_md5 = "DWygnHRtgiJ77HCm+1rvHw==".to_string(); + let server_side_encryption = String::from(AMZ_ENCRYPTION_AES); + let result = validate_sse_headers_for_write( + Some(&server_side_encryption), + None, + None, + Some(&algorithm), + Some(&key), + Some(&key_md5), + true, + ); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[test] +fn test_is_managed_sse() { + assert!(is_managed_sse(&String::from("AES256"))); + assert!(is_managed_sse(&String::from("aws:kms"))); +} + +#[test] +fn test_generate_ssec_nonce() { + let nonce1 = generate_ssec_nonce("bucket1", "key1"); + let nonce2 = generate_ssec_nonce("bucket1", "key1"); + let nonce3 = generate_ssec_nonce("bucket1", "key2"); + + // Same inputs should produce same nonce + assert_eq!(nonce1, nonce2); + + // Different inputs should produce different nonce + assert_ne!(nonce1, nonce3); + + // Nonce should be exactly 12 bytes + assert_eq!(nonce1.len(), 12); +} + +#[test] +fn test_validate_ssec_params_success() { + let key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let key_md5 = md5_base64([42u8; 32]); + + let params = SsecParams { + algorithm: "AES256".to_string(), + key, + key_md5, + }; + + let result = validate_ssec_params(params); + assert!(result.is_ok()); + let validated = result.unwrap(); + assert_eq!(validated.key_bytes, [42u8; 32]); +} + +#[test] +fn test_validate_ssec_params_wrong_algorithm() { + let key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let key_md5 = md5_base64([42u8; 32]); + + let params = SsecParams { + algorithm: "AES128".to_string(), // Wrong algorithm + key, + key_md5, + }; + + let result = validate_ssec_params(params); + assert!(result.is_err()); +} + +#[test] +fn test_validate_ssec_params_wrong_key_length() { + let key = BASE64_STANDARD.encode_to_string([42u8; 16]); // Only 16 bytes + let key_md5 = md5_base64([42u8; 16]); + + let params = SsecParams { + algorithm: "AES256".to_string(), + key, + key_md5, + }; + + let result = validate_ssec_params(params); + assert!(result.is_err()); +} + +#[test] +fn test_validate_ssec_params_wrong_md5() { + let key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let key_md5 = BASE64_STANDARD.encode_to_string([99u8; 16]); // Wrong MD5 + + let params = SsecParams { + algorithm: "AES256".to_string(), + key, + key_md5, + }; + + let result = validate_ssec_params(params); + assert!(result.is_err()); +} + +#[tokio::test] +async fn test_sse_encryption_rejects_partial_ssec_headers() { + let bucket = "test-bucket"; + let key = "test-key"; + let sse_key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let sse_key_md5 = md5_base64([42u8; 32]); + let content_size = 1024; + + let request_missing_md5 = EncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(sse_key.clone()), + sse_customer_key_md5: None, + content_size, + principal: None, + }; + + let err = sse_encryption(&HOST, request_missing_md5).await.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); + + let request_missing_key = EncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: None, + sse_customer_key_md5: Some(sse_key_md5.clone()), + content_size, + principal: None, + }; + + let err = sse_encryption(&HOST, request_missing_key).await.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); + + let request_missing_algorithm = EncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: Some(sse_key), + sse_customer_key_md5: Some(sse_key_md5), + content_size, + principal: None, + }; + + let err = sse_encryption(&HOST, request_missing_algorithm).await.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[tokio::test] +async fn test_sse_prepare_encryption_rejects_partial_ssec_headers() { + let bucket = "test-bucket"; + let key = "test-key"; + let sse_key_md5 = md5_base64([42u8; 32]); + + let request_missing_algorithm = PrepareEncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: Some(sse_key_md5), + principal: None, + }; + + let err = sse_prepare_encryption(&HOST, request_missing_algorithm).await.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_sse_headers_for_write_allows_aws_kms_without_key_id() { + let server_side_encryption: String = "aws:kms".to_string(); + + let result = validate_sse_headers_for_write(Some(&server_side_encryption), None, None, None, None, None, true); + + assert!(result.is_ok()); +} + +#[tokio::test] +async fn test_sse_prepare_encryption_rejects_ssec_headers_without_customer_key() { + let bucket = "test-bucket"; + let key = "test-key"; + let sse_key_md5 = md5_base64([42u8; 32]); + + let request = PrepareEncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: None, + sse_customer_key_md5: Some(sse_key_md5), + principal: None, + }; + + let error = sse_prepare_encryption(&HOST, request) + .await + .expect_err("multipart preparation must require possession of the customer key"); + assert_eq!(error.code, S3ErrorCode::InvalidRequest); +} + +// ------------------------------------------------------------------------ +// SSE-C Direct (default, non-`rio-v2` build) random-nonce persistence +// ------------------------------------------------------------------------ + +#[cfg(not(feature = "rio-v2"))] +async fn ssec_direct_put_metadata( + bucket: &str, + key: &str, + customer_key: &str, + customer_key_md5: &str, +) -> HashMap { + let material = sse_encryption( + &HOST, + EncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(customer_key.to_string()), + sse_customer_key_md5: Some(customer_key_md5.to_string()), + content_size: 128, + principal: None, + }, + ) + .await + .expect("sse-c encryption") + .expect("sse-c material"); + assert_eq!(material.key_kind, EncryptionKeyKind::Direct); + encryption_material_to_metadata(&material).expect("sse-c metadata should serialize") +} + +// (a) Overwriting the same bucket/key under the same SSE-C key must persist a DIFFERENT +// random IV each time, and each stored IV must be read back on decrypt. This is the core +// of the fix: no (key, nonce) reuse across overwrites. +#[cfg(not(feature = "rio-v2"))] +#[tokio::test] +async fn test_ssec_direct_random_nonce_is_unique_per_put_and_read_back() { + let bucket = "bucket"; + let key = "object"; + let customer_key_bytes = [0x24u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); + + let metadata_one = ssec_direct_put_metadata(bucket, key, &customer_key, &customer_key_md5).await; + let metadata_two = ssec_direct_put_metadata(bucket, key, &customer_key, &customer_key_md5).await; + + let iv_one = metadata_one + .get(INTERNAL_ENCRYPTION_IV_HEADER) + .expect("first put persists a random IV"); + let iv_two = metadata_two + .get(INTERNAL_ENCRYPTION_IV_HEADER) + .expect("second put persists a random IV"); + + assert_ne!(iv_one, iv_two, "overwriting the same object must not reuse the nonce"); + + // Dual-key persistence for MinIO interop: both headers carry the same value. + assert_eq!(metadata_one.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER), Some(iv_one)); + assert_eq!(metadata_two.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER), Some(iv_two)); + + for (metadata, iv) in [(&metadata_one, iv_one), (&metadata_two, iv_two)] { + let decrypted = + crate::core::read::apply_ssec_decryption_material(bucket, key, metadata, &customer_key, &customer_key_md5) + .await + .expect("sse-c decryption material"); + assert_eq!( + BASE64_STANDARD.encode_to_string(decrypted.base_nonce), + *iv, + "decrypt must read the persisted random nonce back" + ); + assert_eq!(decrypted.key_bytes, customer_key_bytes); + } +} + +// (b) Legacy compatibility: objects encrypted before this change carry no IV header. Decrypt +// must fall back to the deterministic `generate_ssec_nonce(bucket, key)` they were encrypted +// with, so previously stored objects keep decrypting. +#[cfg(not(feature = "rio-v2"))] +#[tokio::test] +async fn test_ssec_direct_legacy_object_without_iv_falls_back_to_deterministic_nonce() { + let bucket = "bucket"; + let key = "object"; + let customer_key_bytes = [0x24u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); + + let mut metadata = HashMap::new(); + metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); + assert!(!metadata.contains_key(INTERNAL_ENCRYPTION_IV_HEADER)); + assert!(!metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_IV_HEADER)); + + let decrypted = crate::core::read::apply_ssec_decryption_material(bucket, key, &metadata, &customer_key, &customer_key_md5) + .await + .expect("sse-c decryption material"); + + assert_eq!( + decrypted.base_nonce, + generate_ssec_nonce(bucket, key), + "legacy objects must decrypt via the deterministic nonce fallback" + ); +} + +// (c) Byte-level round trip: data encrypted with the material's key + persisted nonce must +// decrypt with the key + nonce resolved from the stored metadata. +#[cfg(not(feature = "rio-v2"))] +#[tokio::test] +async fn test_ssec_direct_persisted_nonce_round_trips_plaintext() { + use aes_gcm::{ + Aes256Gcm, Nonce, + aead::{Aead, KeyInit}, + }; + + let bucket = "bucket"; + let key = "object"; + let customer_key_bytes = [0x51u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); + let plaintext = b"attack at dawn - sse-c round trip".to_vec(); + + let metadata = ssec_direct_put_metadata(bucket, key, &customer_key, &customer_key_md5).await; + + // Encrypt with the key + nonce that were persisted at PUT time. + let enc_iv = BASE64_STANDARD + .decode_to_vec(metadata.get(INTERNAL_ENCRYPTION_IV_HEADER).expect("persisted IV")) + .expect("valid base64 IV"); + let cipher = Aes256Gcm::new_from_slice(&customer_key_bytes).expect("cipher"); + let ciphertext = cipher + .encrypt(&Nonce::try_from(enc_iv.as_slice()).expect("nonce"), plaintext.as_ref()) + .expect("encrypt"); + + // Resolve key + nonce purely from stored metadata (as decrypt does in production). + let decrypted_material = + crate::core::read::apply_ssec_decryption_material(bucket, key, &metadata, &customer_key, &customer_key_md5) + .await + .expect("sse-c decryption material"); + let dec_cipher = Aes256Gcm::new_from_slice(&decrypted_material.key_bytes).expect("cipher"); + let recovered = dec_cipher + .decrypt( + &Nonce::try_from(decrypted_material.base_nonce.as_slice()).expect("nonce"), + ciphertext.as_ref(), + ) + .expect("decrypt with resolved key + nonce"); + + assert_eq!(recovered, plaintext); +} + +// (d) Multipart: the random nonce generated at CreateMultipartUpload is persisted in the +// session metadata, and every part resolves the SAME nonce via `sse_decryption` on that +// session metadata. Parts must never diverge, and the value must not be deterministic. +#[cfg(not(feature = "rio-v2"))] +#[tokio::test] +async fn test_ssec_direct_multipart_all_parts_share_one_persisted_nonce() { + let bucket = "bucket"; + let key = "object"; + let customer_key_bytes = [0x33u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); + + let material = sse_prepare_encryption( + &HOST, + PrepareEncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(customer_key.clone()), + sse_customer_key_md5: Some(customer_key_md5.clone()), + principal: None, + }, + ) + .await + .expect("prepare ssec") + .expect("prepare material"); + assert_eq!(material.key_kind, EncryptionKeyKind::Direct); + + let session_metadata = encryption_material_to_metadata(&material).expect("session metadata should serialize"); + let session_iv = session_metadata + .get(INTERNAL_ENCRYPTION_IV_HEADER) + .expect("multipart session persists a random IV") + .clone(); + // Random, not the deterministic bucket/key derivation. + assert_ne!( + BASE64_STANDARD.decode_to_vec(&session_iv).expect("valid IV")[..], + generate_ssec_nonce(bucket, key)[..] + ); + + let resolve_part_nonce = |part_number: usize| { + let session_metadata = session_metadata.clone(); + let customer_key = customer_key.clone(); + let customer_key_md5 = customer_key_md5.clone(); + async move { + let _ = part_number; + sse_decryption( + &HOST, + DecryptionRequest { + bucket, + key, + metadata: &session_metadata, + sse_customer_key: Some(&customer_key), + sse_customer_key_md5: Some(&customer_key_md5), + principal: None, + }, + ) + .await + .expect("part decryption") + .expect("part material") + .base_nonce + } + }; + + let part_one_nonce = resolve_part_nonce(1).await; + let part_two_nonce = resolve_part_nonce(2).await; + + assert_eq!(part_one_nonce, part_two_nonce, "all parts of one upload must share the persisted nonce"); + assert_eq!(BASE64_STANDARD.encode_to_string(part_one_nonce), session_iv); +} + +#[cfg(feature = "rio-v2")] +#[tokio::test] +async fn test_sse_prepare_encryption_ssec_with_customer_key_stores_sealed_key_metadata() { + let bucket = "test-bucket"; + let key = "test-key"; + let customer_key_bytes = [0x24u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let sse_key_md5 = md5_base64(customer_key_bytes); + + let request = PrepareEncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(customer_key), + sse_customer_key_md5: Some(sse_key_md5), + principal: None, + }; + + let material = sse_prepare_encryption(&HOST, request) + .await + .expect("prepare should accept full ssec headers") + .expect("ssec metadata should be generated"); + assert_eq!(material.key_kind, EncryptionKeyKind::Object); + + let metadata = encryption_material_to_metadata(&material).expect("ssec metadata should serialize"); + assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_IV_HEADER)); + assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)); +} + +#[test] +fn test_encryption_material_to_metadata_persists_ssec_original_size() { + let metadata = encryption_material_to_metadata(&EncryptionMaterial { + sse_type: SSEType::SseC, + server_side_encryption: String::from(AMZ_ENCRYPTION_AES), + kms_key_id: None, + algorithm: "AES256".to_string(), + key_bytes: [0u8; 32], + base_nonce: [0u8; 12], + encrypted_data_key: None, + customer_key_md5: Some("d41d8cd98f00b204e9800998ecf8427e".to_string()), + original_size: Some(1024), + key_kind: EncryptionKeyKind::Direct, + managed_kms_context: None, + managed_sealed_key: None, + }) + .expect("ssec original-size metadata should serialize"); + + assert_eq!(metadata.get(SSEC_ORIGINAL_SIZE_HEADER).map(String::as_str), Some("1024")); +} + +fn material_variant(sse_type: SSEType, key_kind: EncryptionKeyKind) -> EncryptionMaterial { + let (server_side_encryption, kms_key_id, encrypted_data_key, customer_key_md5, managed_kms_context) = match sse_type { + SSEType::SseC => ( + String::from(AMZ_ENCRYPTION_AES), + None, + None, + Some("d41d8cd98f00b204e9800998ecf8427e".to_string()), + None, + ), + SSEType::SseS3 => (String::from(AMZ_ENCRYPTION_AES), None, Some(vec![0u8; 32]), None, None), + SSEType::SseKms => ( + String::from(AMZ_ENCRYPTION_KMS), + Some("kms-key-1".to_string()), + Some(vec![0u8; 32]), + None, + Some(HashMap::from([("app".to_string(), "test".to_string())])), + ), + }; + EncryptionMaterial { + sse_type, + server_side_encryption, + kms_key_id, + algorithm: "AES256".to_string(), + key_bytes: [0u8; 32], + base_nonce: [0u8; 12], + encrypted_data_key, + customer_key_md5, + original_size: Some(1024), + key_kind, + managed_kms_context, + managed_sealed_key: None, + } +} + +#[test] +fn native_request_debug_withholds_encryption_customer_key() { + let mut request = managed_write(AMZ_ENCRYPTION_AES, None); + request.sse_customer_key = Some("fixture-key-must-stay-private".to_owned()); + let diagnostic = format!("{request:?}"); + assert!(!diagnostic.contains("sse_customer_key"), "customer keys must not be debug fields"); +} + +#[test] +fn native_request_debug_withholds_decryption_customer_key() { + let metadata = HashMap::new(); + let key = "fixture-key-must-stay-private".to_owned(); + let request = DecryptionRequest { + bucket: "bucket", + key: "object", + metadata: &metadata, + sse_customer_key: Some(&key), + sse_customer_key_md5: None, + principal: None, + }; + let diagnostic = format!("{request:?}"); + assert!(!diagnostic.contains("sse_customer_key"), "customer keys must not be debug fields"); +} + +#[test] +fn native_material_debug_withholds_encryption_keys() { + let material = material_variant(SSEType::SseC, EncryptionKeyKind::Direct); + let diagnostic = format!("{material:?}"); + assert!( + !diagnostic.contains("key_bytes") + && !diagnostic.contains("encrypted_data_key") + && !diagnostic.contains("managed_sealed_key"), + "encryption keys must not be debug fields" + ); +} + +#[test] +fn native_material_debug_withholds_decryption_keys() { + let material = DecryptionMaterial { + sse_type: SSEType::SseC, + server_side_encryption: String::from(AMZ_ENCRYPTION_AES), + kms_key_id: None, + algorithm: "AES256".to_owned(), + customer_key_md5: None, + key_bytes: [0; 32], + base_nonce: [0; 12], + key_kind: EncryptionKeyKind::Direct, + }; + let diagnostic = format!("{material:?}"); + assert!(!diagnostic.contains("key_bytes"), "decryption keys must not be debug fields"); +} + +#[test] +fn native_material_debug_withholds_customer_key() { + let material = crate::core::s3::scheme::WriteScheme::SseC { + algorithm: "AES256".to_owned(), + key: "fixture-key-must-stay-private".to_owned(), + key_md5: "fixture-md5".to_owned(), + }; + let diagnostic = format!("{material:?}"); + assert!( + !diagnostic.contains("fixture-key-must-stay-private"), + "customer keys must not appear in diagnostics" + ); +} + +/// Reconciliation contract with the replication boundary (backlog#1783): +/// every metadata key this module persists must either be remapped by the +/// SSE-C transport table or be caught by the replication strip predicate. +/// A new stored key that is in neither turns this test red before it can +/// silently leak through outbound replication metadata. +#[test] +fn test_encryption_metadata_keys_reconcile_with_replication_transport_and_strip() { + use rustfs_utils::http::object_encryption_keys::{is_replication_stripped_encryption_key, ssec_replication_transport_header}; + + let variants = [ + (SSEType::SseC, EncryptionKeyKind::Direct), + (SSEType::SseS3, EncryptionKeyKind::Direct), + (SSEType::SseKms, EncryptionKeyKind::Direct), + ]; + + for (sse_type, key_kind) in variants { + let metadata = + encryption_material_to_metadata(&material_variant(sse_type, key_kind)).expect("encryption material should serialize"); + assert!(!metadata.is_empty()); + + for key in metadata.keys() { + assert!( + ssec_replication_transport_header(key).is_some() || is_replication_stripped_encryption_key(key), + "stored key {key} ({sse_type:?}/{key_kind:?}) is neither transport-mapped nor stripped for replication" + ); + if !matches!(sse_type, SSEType::SseC) { + // Managed SSE never takes the transport mapping; every key + // must be structurally stripped so envelopes cannot leave + // the source site. + assert!( + is_replication_stripped_encryption_key(key), + "managed-SSE stored key {key} ({sse_type:?}) escapes the replication strip predicate" + ); + } + } + } +} + +#[tokio::test] +async fn test_sse_encryption_rejects_kms_key_with_invalid_algorithm() { + let bucket = "test-bucket"; + let key = "test-key"; + let content_size = 1024; + + let request = EncryptionRequest { + bucket, + key, + server_side_encryption: Some("AES256".to_string()), + ssekms_key_id: Some("test-key".to_string()), + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size, + principal: None, + }; + + let err = sse_encryption(&HOST, request).await.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[tokio::test] +async fn test_sse_encryption_rejects_kms_key_without_algorithm() { + let bucket = "test-bucket"; + let key = "test-key"; + let content_size = 1024; + + let request = EncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: Some("test-key".to_string()), + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size, + principal: None, + }; + + let err = sse_encryption(&HOST, request).await.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[tokio::test] +async fn test_sse_encryption_rejects_conflict_between_kms_and_ssec() { + let bucket = "test-bucket"; + let key = "test-key"; + let content_size = 1024; + let sse_key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let sse_key_md5 = md5_base64([42u8; 32]); + + let request = EncryptionRequest { + bucket, + key, + server_side_encryption: Some("aws:kms".to_string()), + ssekms_key_id: Some("test-key".to_string()), + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(sse_key), + sse_customer_key_md5: Some(sse_key_md5), + content_size, + principal: None, + }; + + let err = sse_encryption(&HOST, request).await.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[test] +fn test_resolve_effective_kms_key_id_ignores_bucket_default_for_explicit_sse_s3() { + let effective_sse = String::from(AMZ_ENCRYPTION_AES); + + let kms_key_id = resolve_effective_kms_key_id(Some(&effective_sse), None, || Some("bucket-default".to_string())); + + assert_eq!(kms_key_id, None); +} + +#[test] +fn test_resolve_effective_kms_key_id_uses_bucket_default_for_sse_kms() { + let effective_sse = String::from(AMZ_ENCRYPTION_KMS); + + let kms_key_id = resolve_effective_kms_key_id(Some(&effective_sse), None, || Some("bucket-default".to_string())); + + assert_eq!(kms_key_id.as_deref(), Some("bucket-default")); +} + +/// One recorded rewrap call: (envelope bytes, bucket, object key, context). +type RecordedRewrapCall = (Vec, String, String, HashMap); + +/// Test double for the rewrap seam: records what it was asked to rewrap +/// and answers with a canned response. +struct RewrapProbeProvider { + rewrapped: bool, + new_ciphertext: Vec, + calls: std::sync::Mutex>, +} + +#[async_trait] +impl SseDekProvider for RewrapProbeProvider { + async fn generate_sse_dek( + &self, + _context: &ObjectEncryptionContext, + _kms_key_id: &str, + ) -> Result<(DataKey, Vec), SseError> { + unreachable!("rewrap tests never generate keys") + } + + async fn decrypt_sse_dek( + &self, + _encrypted_dek: &[u8], + _kms_key_id: &str, + _context: &ObjectEncryptionContext, + ) -> Result<[u8; 32], SseError> { + unreachable!("rewrap tests never decrypt keys") + } + + async fn rewrap_sse_dek( + &self, + encrypted_dek: &[u8], + context: &ObjectEncryptionContext, + ) -> Result { + self.calls.lock().expect("probe lock").push(( + encrypted_dek.to_vec(), + context.bucket.clone(), + context.object_key.clone(), + context.encryption_context.clone(), + )); + Ok(rustfs_kms::types::RewrapDataKeyResponse { + ciphertext: if self.rewrapped { + self.new_ciphertext.clone() + } else { + encrypted_dek.to_vec() + }, + key_id: "probe-key".to_string(), + source_key_version: Some(1), + destination_key_version: Some(2), + rewrapped: self.rewrapped, + }) + } +} + +/// A minimal but well-formed data-key envelope, the shape +/// `is_data_key_envelope` recognizes. +fn probe_envelope_json() -> Vec { + serde_json::to_vec(&serde_json::json!({ + "key_id": "dek-id", + "master_key_id": "master-key", + "key_spec": "AES_256", + "encrypted_key": [1, 2, 3, 4], + "nonce": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + "encryption_context": {"bucket": "bucket/dir/object"}, + "created_at": "2024-01-01T00:00:00+00:00" + })) + .expect("serialize probe envelope") +} + +/// The adapter must replace every stored copy of the old envelope — under +/// whatever key casing the storage layer preserved — and leave slots +/// holding different bytes (a sealed object key) untouched. Its context +/// must be rebuilt exactly as the managed decrypt path rebuilds it. +#[tokio::test] +async fn rewrap_object_metadata_replaces_every_stored_envelope_copy() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + let envelope = probe_envelope_json(); + let envelope_b64 = BASE64_STANDARD.encode_to_string(&envelope); + let client_context = HashMap::from([("tenant".to_string(), "alpha".to_string())]); + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()), + // Mixed casing on the internal header, exactly as the storage layer + // can hand it back. + ("X-Rustfs-Encryption-Key".to_string(), envelope_b64.clone()), + (MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), envelope_b64.clone()), + // A sealed object key: different bytes, must not be rewritten. + ( + MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), + BASE64_STANDARD.encode_to_string(b"sealed-object-key-not-the-envelope"), + ), + ( + MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), + encode_minio_kms_context(&client_context).expect("encode context"), + ), + ]); + + let new_ciphertext = b"rewrapped-envelope-bytes".to_vec(); + let provider = Arc::new(RewrapProbeProvider { + rewrapped: true, + new_ciphertext: new_ciphertext.clone(), + calls: std::sync::Mutex::new(Vec::new()), + }); + crate::kms::provider::set_sse_dek_provider_for_test(provider.clone()); + + let outcome = rewrap_object_encryption_metadata(&HOST, "bucket", "dir/object", &metadata) + .await + .expect("rewrap must succeed"); + let ObjectDekRewrapOutcome::Rewrapped { metadata: overrides } = outcome else { + panic!("expected a rewrapped outcome, got {outcome:?}"); + }; + + let new_b64 = BASE64_STANDARD.encode_to_string(&new_ciphertext); + assert_eq!( + overrides, + HashMap::from([ + ("X-Rustfs-Encryption-Key".to_string(), new_b64.clone()), + (MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), new_b64), + ]), + "every envelope copy must be replaced under its stored name and nothing else touched" + ); + + let calls = provider.calls.lock().expect("probe lock"); + let (sent_envelope, bucket, object_key, sent_context) = calls.first().expect("the provider must be called"); + assert_eq!(*sent_envelope, envelope, "the decoded stored envelope must reach the provider"); + assert_eq!(bucket, "bucket"); + assert_eq!(object_key, "dir/object"); + assert_eq!( + *sent_context, + build_kms_request_context("bucket", "dir/object", Some(&client_context)), + "the context must be rebuilt exactly as the managed decrypt path rebuilds it" + ); + + reset_sse_dek_provider(); +} + +/// `rewrapped: false` from the backend means nothing to persist; the +/// adapter must answer AlreadyCurrent so a sweep re-run converges. +#[tokio::test] +async fn rewrap_object_metadata_converges_when_already_current() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + let envelope_b64 = BASE64_STANDARD.encode_to_string(probe_envelope_json()); + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), "AES256".to_string()), + (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), envelope_b64), + ]); + let provider = Arc::new(RewrapProbeProvider { + rewrapped: false, + new_ciphertext: Vec::new(), + calls: std::sync::Mutex::new(Vec::new()), + }); + crate::kms::provider::set_sse_dek_provider_for_test(provider.clone()); + + let outcome = rewrap_object_encryption_metadata(&HOST, "bucket", "object", &metadata) + .await + .expect("rewrap must succeed"); + assert!(matches!(outcome, ObjectDekRewrapOutcome::AlreadyCurrent), "got {outcome:?}"); + assert_eq!(provider.calls.lock().expect("probe lock").len(), 1); + + reset_sse_dek_provider(); +} + +/// The KMS-backed provider's rewrap threads through the encryption +/// service to the backend. The Local test backend has no rewrap support, +/// so the capability refusal coming back proves the whole chain is wired — +/// a stub that silently succeeded would return Ok here. +#[tokio::test] +async fn kms_provider_rewrap_reaches_the_backend_through_the_service() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + let manager = configure_test_global_local_kms().await; + let provider = KmsSseDekProvider::new_with_service_manager(manager) + .await + .expect("kms provider should initialize from the configured test manager"); + + let context = crate::core::keying::context::build_object_encryption_context("bucket", "object", None); + let error = provider + .rewrap_sse_dek(b"{}", &context) + .await + .expect_err("the Local backend must refuse rewrap through the full chain"); + assert!( + error.to_string().contains("rewrap") || format!("{:?}", error.source).contains("rewrap_data_key"), + "the refusal must come from the backend capability gate: {error:?}" + ); + + reset_sse_dek_provider(); +} + +/// A write whose resolved key — from the request header or a bucket +/// default rule — is unknown to the KMS must come back as the client +/// error S3 uses for it, all the way from the backend lookup. Answering +/// 500 here made a bucket default pointing at a deleted or mistyped key +/// look like a server outage (rustfs/backlog#2330, KMS-312). +#[tokio::test] +async fn kms_provider_reports_an_unknown_key_as_kms_not_found() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + let manager = configure_test_global_local_kms().await; + let provider = KmsSseDekProvider::new_with_service_manager(manager) + .await + .expect("kms provider should initialize from the configured test manager"); + + let context = crate::core::keying::context::build_object_encryption_context("bucket", "object", None); + let error = provider + .generate_sse_dek(&context, "no-such-key") + .await + .expect_err("the Local backend must refuse a key it does not hold"); + assert_eq!(error.code, S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()), "got {error:?}"); + assert!(error.message.contains("no-such-key"), "the missing key must be named: {error:?}"); + assert_eq!(crate::core::audit::kms_data_plane_error_class(&error), "key_not_found"); + + reset_sse_dek_provider(); +} + +/// Objects without a rewrappable envelope — plaintext, SSE-C, or a +/// MinIO-sealed opaque data key — are reported NotApplicable without any +/// provider call. +#[tokio::test] +async fn rewrap_object_metadata_skips_objects_without_a_rustfs_envelope() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + let provider = Arc::new(RewrapProbeProvider { + rewrapped: true, + new_ciphertext: b"never-used".to_vec(), + calls: std::sync::Mutex::new(Vec::new()), + }); + crate::kms::provider::set_sse_dek_provider_for_test(provider.clone()); + + // Plaintext object. + let outcome = rewrap_object_encryption_metadata(&HOST, "bucket", "object", &HashMap::new()) + .await + .expect("plaintext objects must not error"); + assert!(matches!(outcome, ObjectDekRewrapOutcome::NotApplicable), "got {outcome:?}"); + + // SSE-C object: customer-key encryption never reaches KMS. + let ssec = HashMap::from([ + ("X-Amz-Server-Side-Encryption-Customer-Algorithm".to_string(), "AES256".to_string()), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([1u8; 12])), + ]); + let outcome = rewrap_object_encryption_metadata(&HOST, "bucket", "object", &ssec) + .await + .expect("SSE-C objects must not error"); + assert!(matches!(outcome, ObjectDekRewrapOutcome::NotApplicable), "got {outcome:?}"); + + // MinIO builtin-KMS ciphertext: opaque bytes, not a RustFS envelope. + let minio = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()), + ( + MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), + BASE64_STANDARD.encode_to_string(b"opaque-minio-sealed-bytes"), + ), + ]); + let outcome = rewrap_object_encryption_metadata(&HOST, "bucket", "object", &minio) + .await + .expect("MinIO-sealed objects must not error"); + assert!(matches!(outcome, ObjectDekRewrapOutcome::NotApplicable), "got {outcome:?}"); + + assert!( + provider.calls.lock().expect("probe lock").is_empty(), + "no provider call may happen for non-rewrappable objects" + ); + + reset_sse_dek_provider(); +} + +#[tokio::test] +async fn test_sse_encryption_persists_aws_kms_header_for_kms_objects() { + let material = EncryptionMaterial { + sse_type: SSEType::SseKms, + server_side_encryption: String::from(AMZ_ENCRYPTION_KMS), + kms_key_id: Some("test-key".to_string()), + algorithm: AMZ_ENCRYPTION_KMS.to_string(), + key_bytes: [7u8; 32], + base_nonce: [9u8; 12], + encrypted_data_key: Some(vec![1, 2, 3, 4]), + customer_key_md5: None, + original_size: Some(1024), + key_kind: EncryptionKeyKind::Direct, + managed_kms_context: None, + managed_sealed_key: None, + }; + // Only an aws:kms object names its key in write responses. + assert_eq!(material.response_kms_key_id().as_deref(), Some("test-key")); + let metadata = encryption_material_to_metadata(&material).expect("managed SSE metadata should serialize"); + + assert_eq!(metadata.get("x-amz-server-side-encryption").map(String::as_str), Some("aws:kms")); + assert_eq!( + metadata + .get("x-amz-server-side-encryption-aws-kms-key-id") + .map(String::as_str), + Some("test-key") + ); +} + +#[cfg(feature = "rio-v2")] +#[tokio::test] +async fn test_sse_kms_roundtrip_persists_and_uses_minio_context() { + use rustfs_kms::types::{CreateKeyRequest, KeyUsage}; + let _guard = lock_sse_test_state().await; + + reset_sse_dek_provider(); + let manager = configure_test_global_local_kms().await; + manager + .get_encryption_service() + .await + .expect("encryption service should exist") + .create_key(CreateKeyRequest { + key_name: Some("kms-test".to_string()), + key_usage: KeyUsage::EncryptDecrypt, + description: None, + policy: None, + tags: HashMap::new(), + origin: None, + }) + .await + .expect("kms test key should be created"); + + let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) + .await + .expect("kms provider should initialize from the configured test manager"); + crate::kms::provider::set_sse_dek_provider_for_test(Arc::new(provider)); + + let client_context = HashMap::from([("tenant".to_string(), "alpha".to_string())]); + let request = EncryptionRequest { + bucket: "bucket", + key: "dir/object", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), + ssekms_key_id: Some("kms-test".to_string()), + ssekms_context: Some(client_context.clone()), + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 4096, + principal: None, + }; + + let material = sse_encryption(&HOST, request) + .await + .expect("sse-kms encryption") + .expect("managed sse-kms material"); + let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); + let encoded_context = metadata + .get(MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER) + .expect("minio kms context header should exist"); + let decoded_context: HashMap = + serde_json::from_slice(&BASE64_STANDARD.decode_to_vec(encoded_context).expect("decode base64 context")) + .expect("decode json context"); + assert_eq!(decoded_context, client_context); + + let decrypted = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "dir/object", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect("sse-kms decryption should succeed") + .expect("sse-kms material should exist"); + assert_eq!(decrypted.key_bytes, material.key_bytes); + + let mut wrong_metadata = metadata.clone(); + wrong_metadata.insert( + MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), + BASE64_STANDARD + .encode_to_string(serde_json::to_vec(&HashMap::from([("tenant".to_string(), "beta".to_string())])).unwrap()), + ); + let err = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "dir/object", + metadata: &wrong_metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect_err("mismatched kms context should fail"); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); + assert_eq!( + err.message, + "Encryption context mismatch: Context mismatch for key 'tenant': expected 'alpha', got 'beta'" + ); + assert_eq!(crate::core::audit::kms_data_plane_error_class(&err), "context_mismatch"); + + manager.stop().await.expect("kms service should stop cleanly"); + reset_sse_dek_provider(); +} + +#[cfg(feature = "rio-v2")] +#[test] +fn test_encryption_material_to_metadata_persists_minio_managed_headers() { + let encoded_nonce = BASE64_STANDARD.encode_to_string([9u8; 12]); + let encoded_key = BASE64_STANDARD.encode_to_string([1u8, 2, 3, 4]); + let metadata = encryption_material_to_metadata(&EncryptionMaterial { + sse_type: SSEType::SseKms, + server_side_encryption: String::from(AMZ_ENCRYPTION_KMS), + kms_key_id: Some("test-key".to_string()), + algorithm: AMZ_ENCRYPTION_KMS.to_string(), + key_bytes: [7u8; 32], + base_nonce: [9u8; 12], + encrypted_data_key: Some(vec![1, 2, 3, 4]), + customer_key_md5: None, + original_size: Some(1024), + key_kind: EncryptionKeyKind::Direct, + managed_kms_context: None, + managed_sealed_key: None, + }) + .expect("managed SSE metadata should serialize"); + + assert_eq!( + metadata.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER).map(String::as_str), + Some(encoded_nonce.as_str()) + ); + assert_eq!( + metadata + .get(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER) + .map(String::as_str), + Some(encoded_key.as_str()) + ); + assert_eq!( + metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER).map(String::as_str), + Some("test-key") + ); + assert_eq!( + metadata.get(MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER).map(String::as_str), + Some(MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM) + ); +} + +#[tokio::test] +async fn test_sse_encryption_omits_kms_header_for_sse_s3_objects() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + let local_sse_master_key = local_sse_master_key_b64(); + + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), + ("RUSTFS_SSE_S3_MASTER_KEY", Some(local_sse_master_key.as_str())), + ], + async { + let request = EncryptionRequest { + bucket: "test-bucket", + key: "test-key", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 1024, + principal: None, + }; + + let material = sse_encryption(&HOST, request) + .await + .expect("sse-s3 encryption should succeed"); + let material = material.expect("managed sse-s3 encryption should return material"); + let metadata = encryption_material_to_metadata(&material).expect("managed SSE-S3 metadata should serialize"); + + assert_eq!(material.kms_key_id.as_deref(), Some("default")); + // The wrapping key stays internal: no write response may + // advertise it for an AES256 object. + assert_eq!(material.response_kms_key_id(), None); + assert_eq!(metadata.get("x-amz-server-side-encryption").map(String::as_str), Some("AES256")); + assert!(!metadata.contains_key("x-amz-server-side-encryption-aws-kms-key-id")); + assert_eq!(metadata.get(INTERNAL_ENCRYPTION_KEY_ID_HEADER).map(String::as_str), Some("default")); + }, + ) + .await; + + reset_sse_dek_provider(); +} + +#[test] +fn test_strip_managed_encryption_metadata() { + let mut metadata = HashMap::new(); + metadata.insert("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()); + metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); + metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), "source-key-md5".to_string()); + metadata.insert(SSEC_ORIGINAL_SIZE_HEADER.to_string(), "123".to_string()); + metadata.insert("x-rustfs-encryption-key".to_string(), "encrypted_key".to_string()); + metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), "sealed".to_string()); + metadata.insert("content-type".to_string(), "text/plain".to_string()); + + strip_managed_encryption_metadata(&mut metadata); + + assert!(!metadata.contains_key("x-amz-server-side-encryption")); + assert!(!metadata.contains_key("x-amz-server-side-encryption-customer-algorithm")); + assert!(!metadata.contains_key("x-amz-server-side-encryption-customer-key-md5")); + assert!(!metadata.contains_key(SSEC_ORIGINAL_SIZE_HEADER)); + assert!(!metadata.contains_key("x-rustfs-encryption-key")); + assert!(!metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER)); + assert!(metadata.contains_key("content-type")); +} + +/// A copy destination must not inherit any key that `is_object_encryption_marker` +/// accepts as proof the payload is encrypted. +/// +/// Guards this chain: `ObjectInfo::is_encrypted` is keyed on that predicate, so a +/// single leftover marker makes a plaintext destination report itself encrypted. +/// `object_api::readers` then takes its encrypted branch and demands read material, +/// but the material itself was stripped, so `sse_decryption` reports no encryption +/// and the read fails closed on unresolvable encryption metadata — a destination +/// that CopyObject wrote successfully becomes permanently unreadable. +#[test] +fn test_strip_managed_encryption_metadata_clears_encryption_markers() { + let mut metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()), + ("x-amz-server-side-encryption-aws-kms-key-id".to_string(), "source-key".to_string()), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "source-key".to_string()), + (INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), "AES256".to_string()), + (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), "wrapped-dek".to_string()), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), "base-nonce".to_string()), + ("content-type".to_string(), "text/plain".to_string()), + ]); + + strip_managed_encryption_metadata(&mut metadata); + + let inherited: Vec<&str> = metadata + .keys() + .filter(|key| rustfs_utils::http::is_object_encryption_marker(key)) + .map(String::as_str) + .collect(); + assert!(inherited.is_empty(), "copy destination inherited encryption markers: {inherited:?}"); + assert!(metadata.contains_key("content-type")); +} + +/// A same-name CopyObject is normally serviced as a metadata-only update that reuses the +/// stored ciphertext, while the handler rebuilds the destination metadata around a *fresh* +/// DEK. `ObjectInfo::is_encrypted` — i.e. `is_object_encryption_marker` — is the guard that +/// keeps that shortcut away from encrypted objects (see the `metadata_only` decision in +/// `rustfs/src/app/object_usecase.rs`). Any encryption flavour whose headers +/// `strip_managed_encryption_metadata` drops must therefore also be *detected* there — a +/// flavour that is stripped but not detected would resurrect "new DEK + old ciphertext", +/// which leaves the object permanently undecryptable. +#[test] +fn every_strippable_encryption_shape_is_detected_as_encrypted() { + let shapes: [(&str, Vec<(&str, &str)>); 4] = [ + ( + "sse-s3", + vec![ + ("x-amz-server-side-encryption", "AES256"), + (MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER, "sealed"), + (MINIO_INTERNAL_ENCRYPTION_IV_HEADER, "iv"), + ], + ), + ( + "sse-kms", + vec![ + ("x-amz-server-side-encryption", "aws:kms"), + (MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER, "sealed"), + (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER, "key-1"), + ], + ), + ( + "legacy rustfs managed", + vec![ + ("x-amz-server-side-encryption", "AES256"), + (INTERNAL_ENCRYPTION_KEY_HEADER, "wrapped"), + (INTERNAL_ENCRYPTION_IV_HEADER, "iv"), + ], + ), + ( + "sse-c", + vec![ + (SSEC_ALGORITHM_HEADER, "AES256"), + (MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER, "sealed"), + ], + ), + ]; + + for (label, entries) in shapes { + let metadata: HashMap = entries + .iter() + .map(|(key, value)| ((*key).to_string(), (*value).to_string())) + .collect(); + + assert!( + metadata + .keys() + .any(|key| rustfs_utils::http::is_object_encryption_marker(key)), + "{label}: an encrypted object must be detected, otherwise a same-name copy would re-key it \ + without rewriting the ciphertext" + ); + + let mut stripped = metadata.clone(); + strip_managed_encryption_metadata(&mut stripped); + assert_ne!( + stripped, metadata, + "{label}: the copy path strips this shape's encryption metadata, so the destination cannot \ + reuse the source ciphertext" + ); + } +} + +#[test] +fn plain_object_metadata_is_not_flagged_as_encrypted() { + // The metadata-only self-copy shortcut must stay available for unencrypted objects. + let metadata: HashMap = [("content-type", "text/plain"), ("x-amz-meta-stage", "before")] + .iter() + .map(|(key, value)| ((*key).to_string(), (*value).to_string())) + .collect(); + + assert!( + !metadata + .keys() + .any(|key| rustfs_utils::http::is_object_encryption_marker(key)) + ); +} + +#[cfg(feature = "rio-v2")] +#[test] +fn test_legacy_managed_metadata_excludes_sealed_keys() { + let legacy_metadata = HashMap::from([ + (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), "encrypted-dek".to_string()), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), "nonce".to_string()), + ]); + assert!(is_legacy_rustfs_managed_metadata(&legacy_metadata)); + + let sealed_metadata = HashMap::from([ + (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), "encrypted-dek".to_string()), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), "nonce".to_string()), + (MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(), "sealed-key".to_string()), + ]); + assert!(!is_legacy_rustfs_managed_metadata(&sealed_metadata)); +} + +#[cfg(feature = "rio-v2")] +#[test] +fn test_normalize_managed_metadata_accepts_minio_only_headers() { + let metadata = HashMap::from([ + ( + MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(), + BASE64_STANDARD.encode_to_string(b"encrypted-key"), + ), + ( + MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(), + BASE64_STANDARD.encode_to_string([0x11u8; 12]), + ), + ( + MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), + MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.to_string(), + ), + (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_string(), "default".to_string()), + ]); + + let normalized = normalize_managed_metadata(&metadata, Some(recode_minio_kms_context)); + + assert_eq!( + normalized.get(INTERNAL_ENCRYPTION_KEY_HEADER), + Some(&BASE64_STANDARD.encode_to_string(b"encrypted-key")) + ); + assert_eq!( + normalized.get(INTERNAL_ENCRYPTION_IV_HEADER), + Some(&BASE64_STANDARD.encode_to_string([0x11u8; 12])) + ); + assert_eq!( + normalized.get(INTERNAL_ENCRYPTION_ALGORITHM_HEADER), + Some(&MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.to_string()) + ); + assert_eq!(normalized.get(INTERNAL_ENCRYPTION_KEY_ID_HEADER), Some(&"default".to_string())); +} + +#[cfg(feature = "rio-v2")] +#[test] +fn test_supported_sealed_object_key_cipher_accepts_current_minio_fixture_value() { + assert!(is_supported_sealed_object_key_cipher(DARE_CIPHER_AES_256_GCM)); + assert!(is_supported_sealed_object_key_cipher(DARE_CIPHER_CHACHA20_POLY1305)); + assert!(!is_supported_sealed_object_key_cipher(0x02)); +} + +/// Rewrites rio-v2 SSE-C metadata into the shape MinIO actually persists: +/// only the internal sealed-key slot, IV, and seal algorithm — the public +/// scheme, customer-algorithm, and customer-key-MD5 keys are synthesized +/// onto responses by MinIO and never hit disk (backlog#1638). +#[cfg(feature = "rio-v2")] +fn strip_to_minio_ssec_shape(metadata: &mut HashMap) { + metadata.remove("x-amz-server-side-encryption"); + metadata.remove("x-amz-server-side-encryption-customer-algorithm"); + metadata.remove("x-amz-server-side-encryption-customer-key-md5"); +} + +#[cfg(feature = "rio-v2")] +#[tokio::test] +async fn test_minio_shaped_ssec_metadata_decrypts_with_the_right_key_only() { + let customer_key_bytes = [0x42u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); + + let material = sse_encryption( + &HOST, + EncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(customer_key.clone()), + sse_customer_key_md5: Some(customer_key_md5.clone()), + content_size: 4096, + principal: None, + }, + ) + .await + .expect("sse-c encryption") + .expect("sse-c material"); + + let mut metadata = encryption_material_to_metadata(&material).expect("sse-c metadata should serialize"); + strip_to_minio_ssec_shape(&mut metadata); + assert!( + !metadata.contains_key("x-amz-server-side-encryption-customer-key-md5"), + "the MinIO shape stores no customer-key MD5" + ); + + // Correct key: detected via the sealed slot, proven by the unseal. + let decrypted = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "object", + metadata: &metadata, + sse_customer_key: Some(&customer_key), + sse_customer_key_md5: Some(&customer_key_md5), + principal: None, + }, + ) + .await + .expect("minio-shaped sse-c decryption") + .expect("minio-shaped sse-c material"); + assert_eq!(decrypted.key_kind, EncryptionKeyKind::Object); + assert_eq!(decrypted.key_bytes, material.key_bytes); + + // Wrong key with a self-consistent MD5: the missing stored MD5 cannot + // catch it, so the AEAD unseal must — the relaxation is not a bypass. + let wrong_key_bytes = [0x43u8; 32]; + let wrong_key = BASE64_STANDARD.encode_to_string(wrong_key_bytes); + let wrong_key_md5 = md5_base64(wrong_key_bytes); + let result = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "object", + metadata: &metadata, + sse_customer_key: Some(&wrong_key), + sse_customer_key_md5: Some(&wrong_key_md5), + principal: None, + }, + ) + .await; + assert!(result.is_err(), "a wrong customer key must fail the sealed-key unseal"); + + // No key at all: detected as SSE-C, so the caller is asked for the + // parameters instead of getting an opaque unreadable-object error. + let result = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "object", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await; + let error = result.expect_err("missing SSE-C parameters must fail closed"); + assert!(error.message.contains("must be provided"), "got: {}", error.message); +} + +#[cfg(feature = "rio-v2")] +#[test] +fn test_mark_encrypted_multipart_metadata_sets_minio_marker() { + let mut metadata = HashMap::new(); + mark_encrypted_multipart_metadata(&mut metadata); + assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER)); +} + +#[test] +fn test_verify_ssec_key_match_tolerates_missing_md5_only_for_minio_sealed_ssec() { + // MinIO SSE-C objects store no customer-key MD5; the AEAD unseal is the + // real key proof, so the early check stands down for that shape only. + assert!(verify_ssec_key_match("provided_md5", None, true).is_ok()); + // A stored MD5 always wins, even on the MinIO shape: a mismatch is a + // mismatch. + let stored = "stored_md5".to_string(); + assert!(verify_ssec_key_match("provided_md5", Some(&stored), true).is_err()); +} + +#[test] +fn test_verify_ssec_key_match_success() { + let md5 = "test_md5".to_string(); + let result = verify_ssec_key_match("test_md5", Some(&md5), false); + assert!(result.is_ok()); +} + +#[test] +fn test_verify_ssec_key_match_mismatch() { + let md5 = "stored_md5".to_string(); + let result = verify_ssec_key_match("provided_md5", Some(&md5), false); + assert!(result.is_err()); +} + +#[test] +fn test_verify_ssec_key_match_no_stored() { + let result = verify_ssec_key_match("provided_md5", None, false); + assert!(result.is_err()); +} + +fn multipart_ssec_request(key_byte: u8) -> EncryptionRequest<'static> { + let key_bytes = [key_byte; 32]; + EncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(BASE64_STANDARD.encode_to_string(key_bytes)), + sse_customer_key_md5: Some(md5_base64(key_bytes)), + content_size: 1, + principal: None, + } +} + +fn multipart_ssec_metadata(key_byte: u8) -> HashMap { + let key_bytes = [key_byte; 32]; + HashMap::from([ + ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()), + ("x-amz-server-side-encryption-customer-key-md5".to_string(), md5_base64(key_bytes)), + ]) +} + +#[test] +fn test_validate_multipart_ssec_exact_match() { + assert!( + multipart_ssec_request(42) + .validate_multipart_ssec(&multipart_ssec_metadata(42)) + .is_ok() + ); +} + +#[test] +fn test_validate_complete_multipart_ssec_allows_omitted_parameters() { + let no_ssec = EncryptionRequest { + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + ..multipart_ssec_request(42) + }; + + assert!(no_ssec.validate_complete_multipart_ssec(&multipart_ssec_metadata(42)).is_ok()); + assert!(no_ssec.validate_complete_multipart_ssec(&HashMap::new()).is_ok()); + + for invalid_metadata in [ + HashMap::from([("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string())]), + HashMap::from([ + ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES128".to_string()), + ("x-amz-server-side-encryption-customer-key-md5".to_string(), md5_base64([42u8; 32])), + ]), + HashMap::from([ + ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()), + ("x-amz-server-side-encryption-customer-key-md5".to_string(), "invalid".to_string()), + ]), + ] { + assert_eq!( + no_ssec + .validate_complete_multipart_ssec(&invalid_metadata) + .expect_err("corrupt SSE-C session metadata must fail closed") + .code, + S3ErrorCode::InvalidRequest + ); + } +} + +#[test] +fn ssec_checksum_completion_requires_key_for_both_metadata_aliases() { + let no_key = EncryptionRequest { + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + ..multipart_ssec_request(42) + }; + for prefix in ["x-rustfs-internal-", "x-minio-internal-"] { + let mut metadata = multipart_ssec_metadata(42); + metadata.insert(format!("{prefix}plaintext-checksum"), "true".to_string()); + assert_eq!( + no_key + .validate_complete_multipart_ssec(&metadata) + .expect_err("no key cannot compare or reveal plaintext checksums") + .code, + S3ErrorCode::InvalidRequest + ); + multipart_ssec_request(42) + .validate_complete_multipart_ssec(&metadata) + .expect("correct key"); + assert!( + multipart_ssec_request(43) + .validate_complete_multipart_ssec(&metadata) + .is_err() + ); + } +} + +#[test] +fn test_validate_complete_multipart_ssec_still_validates_present_parameters() { + let partial = EncryptionRequest { + sse_customer_key: None, + ..multipart_ssec_request(42) + }; + assert_eq!( + partial + .validate_complete_multipart_ssec(&multipart_ssec_metadata(42)) + .expect_err("partial SSE-C parameters must fail") + .code, + S3ErrorCode::InvalidRequest + ); + assert_eq!( + multipart_ssec_request(43) + .validate_complete_multipart_ssec(&multipart_ssec_metadata(42)) + .expect_err("wrong SSE-C parameters must fail") + .code, + S3ErrorCode::InvalidRequest + ); +} + +#[test] +fn test_validate_multipart_ssec_rejects_wrong_key_without_leaking_it() { + let request = multipart_ssec_request(43); + let encoded_key = request.sse_customer_key.clone().expect("fixture key"); + let encoded_md5 = request.sse_customer_key_md5.clone().expect("fixture MD5"); + + let error = request + .validate_multipart_ssec(&multipart_ssec_metadata(42)) + .expect_err("wrong key must fail"); + + assert_eq!(error.code, S3ErrorCode::InvalidRequest); + assert!(!error.message.contains(&encoded_key)); + assert!(!error.message.contains(&encoded_md5)); +} + +#[test] +fn test_validate_multipart_ssec_rejects_missing_or_unexpected_parameters() { + let no_ssec = EncryptionRequest { + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + ..multipart_ssec_request(42) + }; + assert_eq!( + no_ssec + .validate_multipart_ssec(&multipart_ssec_metadata(42)) + .expect_err("SSE-C session requires all parameters") + .code, + S3ErrorCode::InvalidRequest + ); + assert_eq!( + multipart_ssec_request(42) + .validate_multipart_ssec(&HashMap::new()) + .expect_err("plaintext session rejects SSE-C parameters") + .code, + S3ErrorCode::InvalidRequest + ); + let incomplete_session = HashMap::from([( + "x-amz-server-side-encryption-customer-key-md5".to_string(), + multipart_ssec_request(42).sse_customer_key_md5.expect("fixture MD5"), + )]); + assert_eq!( + multipart_ssec_request(42) + .validate_multipart_ssec(&incomplete_session) + .expect_err("incomplete stored SSE-C metadata must fail closed") + .code, + S3ErrorCode::InvalidRequest + ); +} + +// ============================================================================ +// Integration Tests - Encrypt/Decrypt with SimpleSseDekProvider +// ============================================================================ + +#[test] +fn test_encrypt_dek_writes_json_with_random_nonces() { + let dek = [0x11u8; 32]; + let cmk = [0x22u8; 32]; + + let encrypted_a = TestSseDekProvider::encrypt_dek(dek, cmk).expect("first DEK wrap should succeed"); + let encrypted_b = TestSseDekProvider::encrypt_dek(dek, cmk).expect("second DEK wrap should succeed"); + + let envelope_a: crate::kms::local::LocalSseDekEnvelope = + serde_json::from_str(&encrypted_a).expect("first wrapped DEK should be a JSON envelope"); + let envelope_b: crate::kms::local::LocalSseDekEnvelope = + serde_json::from_str(&encrypted_b).expect("second wrapped DEK should be a JSON envelope"); + + assert_eq!(envelope_a.version, crate::kms::local::LOCAL_SSE_DEK_FORMAT_VERSION); + assert_eq!(envelope_b.version, crate::kms::local::LOCAL_SSE_DEK_FORMAT_VERSION); + assert_ne!(envelope_a.nonce, envelope_b.nonce, "each DEK wrap should use a distinct nonce"); + assert_eq!( + TestSseDekProvider::decrypt_dek(&encrypted_a, cmk).expect("first JSON envelope should decrypt"), + dek + ); +} + +#[test] +fn test_decrypt_dek_accepts_legacy_zero_nonce_payload() { + let dek = [0x33u8; 32]; + let cmk = [0x44u8; 32]; + let cipher = Aes256Gcm::new(&Key::::from(cmk)); + let legacy_nonce = Nonce::from([0u8; 12]); + let ciphertext = cipher + .encrypt(&legacy_nonce, dek.as_slice()) + .expect("legacy wrap should succeed"); + let legacy_payload = format!( + "{}:{}", + BASE64_STANDARD.encode_to_string(legacy_nonce), + BASE64_STANDARD.encode_to_string(ciphertext) + ); + + let decrypted = TestSseDekProvider::decrypt_dek(&legacy_payload, cmk).expect("legacy payload should remain decryptable"); + assert_eq!(decrypted, dek); +} + +#[test] +fn test_decrypt_dek_rejects_unknown_json_version() { + let envelope = serde_json::json!({ + "version": crate::kms::local::LOCAL_SSE_DEK_FORMAT_VERSION + 1, + "nonce": BASE64_STANDARD.encode_to_string([0u8; 12]), + "ciphertext": BASE64_STANDARD.encode_to_string([0u8; 48]), + }) + .to_string(); + + let error = + TestSseDekProvider::decrypt_dek(&envelope, [0x55u8; 32]).expect_err("unknown JSON envelope versions must fail closed"); + assert_eq!(error.code, S3ErrorCode::InternalError); + assert_eq!(error.message, INTERNAL_ERROR_MESSAGE); + let source = error.source.as_deref().expect("the error should retain its source"); + assert!(source.to_string().contains("Unsupported encrypted DEK format version")); +} + +#[tokio::test] +async fn test_sse_encryption_fails_closed_without_local_sse_master_key() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), + ("RUSTFS_SSE_S3_MASTER_KEY", None::<&str>), + ], + async { + let err = sse_encryption( + &HOST, + EncryptionRequest { + bucket: "test-bucket", + key: "test-key", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 1024, + principal: None, + }, + ) + .await + .expect_err("SSE-S3 should fail closed without a configured local master key"); + + assert!(err.message.contains("RUSTFS_SSE_S3_MASTER_KEY")); + assert_eq!( + err.code, + S3ErrorCode::InvalidRequest, + "missing local SSE master key is a configuration error, not a 500 (rustfs#4844)" + ); + }, + ) + .await; + reset_sse_dek_provider(); +} + +#[tokio::test] +async fn test_sse_encryption_fails_closed_with_invalid_local_sse_master_key() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), + ("RUSTFS_SSE_S3_MASTER_KEY", Some("not-base64")), + ], + async { + let err = sse_encryption( + &HOST, + EncryptionRequest { + bucket: "test-bucket", + key: "test-key", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 1024, + principal: None, + }, + ) + .await + .expect_err("SSE-S3 should fail closed with an invalid local master key"); + + assert!(err.message.contains("valid base64")); + assert_eq!( + err.code, + S3ErrorCode::InvalidRequest, + "invalid local SSE master key is a configuration error, not a 500 (rustfs#4844)" + ); + }, + ) + .await; + reset_sse_dek_provider(); +} + +#[tokio::test] +async fn test_managed_decryption_selects_provider_from_persisted_dek() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + let manager = configure_test_global_local_kms().await; + + let local_master_key = [7u8; 32]; + let local_provider = TestSseDekProvider::new_with_key(local_master_key); + let context = ObjectEncryptionContext::new("bucket".to_string(), "object".to_string()); + let (data_key, encrypted_dek) = local_provider + .generate_sse_dek(&context, "legacy-local-key") + .await + .expect("generate beta.5 local DEK"); + + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::), + ("RUSTFS_SSE_S3_MASTER_KEY", Some(BASE64_STANDARD.encode_to_string(local_master_key))), + ], + async { + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_KMS.to_string()), + ( + INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), + BASE64_STANDARD.encode_to_string(encrypted_dek), + ), + ( + INTERNAL_ENCRYPTION_IV_HEADER.to_string(), + BASE64_STANDARD.encode_to_string(data_key.nonce), + ), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "legacy-local-key".to_string()), + ]); + + let material = apply_managed_decryption_material(&HOST, "bucket", "object", &metadata, None) + .await + .expect("legacy local DEK should not be routed to the running KMS") + .expect("managed metadata should produce decryption material"); + assert_eq!(material.key_bytes, data_key.plaintext_key); + assert_eq!(material.sse_type, SSEType::SseKms); + }, + ) + .await; + + manager.stop().await.expect("stop test KMS service"); + reset_sse_dek_provider(); + + let kms_envelope = br#"{ + "key_id": "test-key-id", + "master_key_id": "master-key-id", + "key_spec": "AES_256", + "encrypted_key": [1, 2, 3, 4], + "nonce": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + "encryption_context": {}, + "created_at": "2024-01-01T00:00:00+00:00" + }"#; + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.to_string()), + (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string(kms_envelope)), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([0x14; 12])), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "test-key-id".to_string()), + ]); + let error = match apply_managed_decryption_material(&HOST, "bucket", "object", &metadata, None).await { + Ok(_) => panic!("KMS envelope must not fall back to the local provider"), + Err(error) => error, + }; + assert_eq!(error.code, S3ErrorCode::ServiceUnavailable); + + reset_sse_dek_provider(); +} + +/// A loopback stand-in for AWS KMS, so the real AWS backend — SDK client, +/// service manager and all — sits behind the SSE entry points under test. +/// +/// It issues data keys the way AWS does: a binary blob that is not UTF-8 +/// and carries nothing RustFS could recognize, decryptable only with the +/// encryption context it was generated under. +struct FakeAwsKms { + endpoint: String, + state: Arc, + server: tokio::task::JoinHandle<()>, +} + +/// Plaintext data key and the encryption context it was generated under. +type FakeAwsDataKey = ([u8; 32], serde_json::Value); + +#[derive(Default)] +struct FakeAwsKmsState { + data_keys: std::sync::Mutex, FakeAwsDataKey>>, + decrypt_calls: std::sync::atomic::AtomicUsize, +} + +impl Drop for FakeAwsKms { + fn drop(&mut self) { + self.server.abort(); + } +} + +impl FakeAwsKms { + const KEY_ARN: &'static str = "arn:aws:kms:us-east-1:111122223333:key/test-key"; + + async fn start() -> Self { + let state = Arc::new(FakeAwsKmsState::default()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind fake AWS KMS listener"); + let endpoint = format!("http://{}", listener.local_addr().expect("fake AWS KMS address")); + let app = axum::Router::new().fallback(Self::handle).with_state(state.clone()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve fake AWS KMS"); + }); + Self { endpoint, state, server } + } + + fn decrypt_calls(&self) -> usize { + self.state.decrypt_calls.load(std::sync::atomic::Ordering::SeqCst) + } + + async fn handle( + axum::extract::State(state): axum::extract::State>, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, + ) -> axum::response::Response { + let operation = headers + .get("x-amz-target") + .and_then(|target| target.to_str().ok()) + .and_then(|target| target.rsplit('.').next()) + .unwrap_or_default(); + let request: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); + let context = request + .get("EncryptionContext") + .cloned() + .unwrap_or_else(|| serde_json::json!({})); + + let reply = match operation { + "ListKeys" => Ok(serde_json::json!({ "Keys": [], "Truncated": false })), + "DescribeKey" => Ok(serde_json::json!({ + "KeyMetadata": { + "KeyId": "test-key", + "Arn": Self::KEY_ARN, + "CreationDate": 1_700_000_000, + "Enabled": true, + "KeyUsage": "ENCRYPT_DECRYPT", + "KeyState": "Enabled", + "Origin": "AWS_KMS", + "KeyManager": "CUSTOMER", + } + })), + "GenerateDataKey" => { + let mut plaintext = [0u8; 32]; + rand::Rng::fill_bytes(&mut rand::rng(), &mut plaintext); + // A continuation byte straight after ASCII is never valid + // UTF-8, like the real blob in practice. + let mut blob = vec![0x01, 0x02, 0x02, 0x00, 0x78]; + let mut tail = [0u8; 48]; + rand::Rng::fill_bytes(&mut rand::rng(), &mut tail); + blob.extend(tail.map(|byte| 0x80 | (byte & 0x3f))); + state + .data_keys + .lock() + .expect("fake AWS KMS state") + .insert(blob.clone(), (plaintext, context)); + Ok(serde_json::json!({ + "KeyId": Self::KEY_ARN, + "Plaintext": BASE64_STANDARD.encode_to_string(plaintext), + "CiphertextBlob": BASE64_STANDARD.encode_to_string(&blob), + })) + } + "Decrypt" => { + state.decrypt_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let blob = request + .get("CiphertextBlob") + .and_then(serde_json::Value::as_str) + .and_then(|blob| BASE64_STANDARD.decode_to_vec(blob).ok()) + .unwrap_or_default(); + match state.data_keys.lock().expect("fake AWS KMS state").get(&blob) { + Some((plaintext, sealed_context)) if *sealed_context == context => Ok(serde_json::json!({ + "KeyId": Self::KEY_ARN, + "Plaintext": BASE64_STANDARD.encode_to_string(plaintext), + "EncryptionAlgorithm": "SYMMETRIC_DEFAULT", + })), + _ => Err("InvalidCiphertextException"), + } + } + _ => Err("UnsupportedOperationException"), + }; + + let (status, body) = match reply { + Ok(body) => (axum::http::StatusCode::OK, body), + Err(code) => ( + axum::http::StatusCode::BAD_REQUEST, + serde_json::json!({ "__type": code, "message": code }), + ), + }; + axum::response::Response::builder() + .status(status) + .header("content-type", "application/x-amz-json-1.1") + .body(axum::body::Body::from(body.to_string())) + .expect("fake AWS KMS response") + } +} + +/// Run `test` with the global KMS service on the AWS backend, pointed at a +/// [`FakeAwsKms`], and no SSE provider injected — the wiring a deployment +/// with `RUSTFS_KMS_BACKEND=aws` and no local master key has. +async fn with_aws_kms_backend(test: F) +where + F: FnOnce(Arc) -> Fut, + Fut: std::future::Future, +{ + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + let fake = Arc::new(FakeAwsKms::start().await); + + async_with_vars( + [ + ("AWS_ACCESS_KEY_ID", Some("AKIDTEST")), + ("AWS_SECRET_ACCESS_KEY", Some("secret")), + ("AWS_SESSION_TOKEN", None), + ("AWS_PROFILE", None), + ("AWS_EC2_METADATA_DISABLED", Some("true")), + ("HTTP_PROXY", None), + ("HTTPS_PROXY", None), + ("http_proxy", None), + ("https_proxy", None), + ("RUSTFS_SSE_S3_MASTER_KEY", None), + ("__RUSTFS_SSE_SIMPLE_CMK", None), + ], + async { + let mut config = rustfs_kms::KmsConfig::aws(Some("us-east-1".to_string())).with_insecure_development_defaults(); + let rustfs_kms::BackendConfig::Aws(aws) = &mut config.backend_config else { + panic!("the AWS constructor must create an AWS backend configuration"); + }; + aws.endpoint_url = Some(fake.endpoint.clone()); + let manager = rustfs_kms::init_global_kms_service_manager(); + manager.reconfigure(config).await.expect("start the AWS KMS backend"); + let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) + .await + .expect("kms provider should initialize from the AWS-backed manager"); + crate::kms::provider::set_sse_dek_provider_for_test(Arc::new(provider)); + + test(fake.clone()).await; + + manager.stop().await.expect("stop the AWS KMS backend"); + }, + ) + .await; + + reset_sse_dek_provider(); +} + +fn aws_sse_kms_write() -> EncryptionRequest<'static> { + EncryptionRequest { + bucket: "bucket", + key: "dir/object", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), + ssekms_key_id: Some("test-key".to_string()), + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 4096, + principal: None, + } +} + +async fn read_managed_object( + metadata: &HashMap, +) -> Result { + sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "dir/object", + metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .map(|material| material.expect("an SSE-KMS object must yield decryption material")) +} + +/// An SSE-KMS object written through the AWS backend must be readable. +/// +/// It was not: the AWS data key reached storage as a bare blob, the read +/// path took the unrecognized bytes for a locally wrapped key, and every +/// GET failed asking for `RUSTFS_SSE_S3_MASTER_KEY` without AWS ever being +/// asked to decrypt. +#[tokio::test] +async fn sse_kms_object_written_through_the_aws_backend_reads_back() { + with_aws_kms_backend(|aws| async move { + let material = sse_encryption(&HOST, aws_sse_kms_write()) + .await + .expect("sse-kms encryption") + .expect("managed sse-kms material"); + let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); + // The rio-v2 writer keeps the wrapped data key in MinIO's slot only. + let stored_key = metadata + .get(INTERNAL_ENCRYPTION_KEY_HEADER) + .or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER)) + .expect("stored data key"); + let stored_key = BASE64_STANDARD.decode_to_vec(stored_key).expect("stored data key is base64"); + assert!( + rustfs_kms::is_data_key_envelope(&stored_key), + "the stored data key must identify itself as KMS-wrapped" + ); + + let decrypted = read_managed_object(&metadata) + .await + .expect("an object written through the AWS backend must decrypt"); + + assert_eq!(decrypted.key_bytes, material.key_bytes); + assert_eq!(decrypted.sse_type, SSEType::SseKms); + assert_eq!(aws.decrypt_calls(), 1, "the read must be served by AWS Decrypt"); + }) + .await; +} + +/// Objects written by releases through 1.0.5 keep the AWS blob bare in +/// their metadata. They are intact and must decrypt as they are, without +/// being rewritten. A `rio-v2` build stored the same bare blob beside a +/// sealed object key, which is the shape MinIO's own objects have, so the +/// route has to hold there too. +#[tokio::test] +async fn sse_kms_object_with_a_bare_aws_data_key_reads_back() { + with_aws_kms_backend(|aws| async move { + let material = sse_encryption(&HOST, aws_sse_kms_write()) + .await + .expect("sse-kms encryption") + .expect("managed sse-kms material"); + let mut metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); + + // Rebuild what those releases persisted: the same headers, with + // the blob AWS issued in place of the envelope around it. + let envelope_b64 = metadata + .get(INTERNAL_ENCRYPTION_KEY_HEADER) + .or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER)) + .expect("stored data key") + .clone(); + let envelope: serde_json::Value = serde_json::from_slice( + &BASE64_STANDARD + .decode_to_vec(&envelope_b64) + .expect("stored data key is base64"), + ) + .expect("stored data key is an envelope"); + let bare: Vec = serde_json::from_value(envelope["encrypted_key"].clone()).expect("envelope carries the AWS blob"); + let bare_b64 = BASE64_STANDARD.encode_to_string(&bare); + let mut replaced = 0; + for value in metadata.values_mut().filter(|value| **value == envelope_b64) { + *value = bare_b64.clone(); + replaced += 1; + } + assert!(replaced > 0, "the stored data key must have been replaced"); + assert!(!rustfs_kms::is_data_key_envelope(&bare)); + + let decrypted = read_managed_object(&metadata) + .await + .expect("an object carrying a bare AWS data key must decrypt"); + + assert_eq!(decrypted.key_bytes, material.key_bytes); + assert_eq!(aws.decrypt_calls(), 1, "the read must be served by AWS Decrypt"); + }) + .await; +} + +/// The bare-blob route exists for AWS alone. No other backend claims an +/// unrecognized data key, and without a KMS it still belongs to the local +/// provider, which is the one that can say what is wrong with it. +#[tokio::test] +async fn bare_data_key_stays_with_the_local_provider_without_an_aws_backend() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + let local_kms = KmsSseDekProvider::new_with_service_manager(configure_test_global_local_kms().await) + .await + .expect("kms provider should initialize from the Local-backed manager"); + assert!(!local_kms.reads_bare_data_key_ciphertext().await); + assert!( + !TestSseDekProvider::new_with_key([9u8; 32]) + .reads_bare_data_key_ciphertext() + .await + ); + + async_with_vars([("RUSTFS_SSE_S3_MASTER_KEY", None::<&str>), ("__RUSTFS_SSE_SIMPLE_CMK", None)], async { + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_KMS.to_string()), + ( + INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), + BASE64_STANDARD.encode_to_string([0x01, 0x02, 0x02, 0x00, 0x78, 0x80, 0x81]), + ), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([0x14; 12])), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "test-key".to_string()), + ]); + + let error = read_managed_object(&metadata) + .await + .expect_err("a bare blob has no owner without a KMS"); + + assert!( + error.message.contains("RUSTFS_SSE_S3_MASTER_KEY"), + "the local provider must still own the diagnosis: {}", + error.message + ); + }) + .await; + + reset_sse_dek_provider(); +} + +/// A KMS stand-in that owns bare data keys and records what it is asked to unwrap. +#[cfg(feature = "rio-v2")] +struct BareKmsProvider { + data_key: [u8; 32], + unwrapped: std::sync::Mutex>>, +} + +#[cfg(feature = "rio-v2")] +#[async_trait::async_trait] +impl SseDekProvider for BareKmsProvider { + async fn generate_sse_dek( + &self, + _context: &ObjectEncryptionContext, + _kms_key_id: &str, + ) -> Result<(DataKey, Vec), SseError> { + Err(SseError::internal("not exercised")) + } + + async fn decrypt_sse_dek( + &self, + encrypted_dek: &[u8], + _kms_key_id: &str, + _context: &ObjectEncryptionContext, + ) -> Result<[u8; 32], SseError> { + self.unwrapped.lock().expect("unwrap log").push(encrypted_dek.to_vec()); + Ok(self.data_key) + } + + async fn reads_bare_data_key_ciphertext(&self) -> bool { + true + } +} + +/// Seal a data key the way MinIO's builtin KMS does, in its raw layout: +/// `sealed || iv[16] || nonce[12]`, AES-256-GCM under `HMAC-SHA256(master, iv)`. +#[cfg(feature = "rio-v2")] +fn seal_minio_kms_data_key(data_key: &[u8; 32], master_key: &[u8; 32], context: &ObjectEncryptionContext) -> Vec { + use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead}; + use hmac::Mac; + let (iv, nonce) = ([0x21u8; 16], [0x42u8; 12]); + let mut mac = crate::core::keying::object::HmacSha256::new_from_slice(master_key).expect("hmac key"); + mac.update(&iv); + let sealing_key: [u8; 32] = mac.finalize().into_bytes().into(); + let aad = crate::kms::minio::minio_kms_associated_data(context).expect("associated data"); + let mut sealed = Aes256Gcm::new_from_slice(&sealing_key) + .expect("sealing key") + .encrypt( + &aes_gcm::Nonce::from(nonce), + aes_gcm::aead::Payload { + msg: data_key, + aad: &aad, + }, + ) + .expect("seal"); + sealed.extend_from_slice(&iv); + sealed.extend_from_slice(&nonce); + sealed +} + +/// A sealed object key with no RustFS envelope comes from MinIO or from a +/// `rio-v2` build on a backend that stored its ciphertext bare. Opening it +/// as MinIO's is an authenticated proof, so the genuine MinIO object keeps +/// its route and only the remainder reaches the KMS. +#[cfg(feature = "rio-v2")] +#[tokio::test] +async fn unenveloped_sealed_data_key_goes_to_minio_first_and_the_kms_otherwise() { + let context = ObjectEncryptionContext::new("bucket".to_string(), "dir/object".to_string()); + let master_key = [0x5Au8; 32]; + let minio_data_key = [0x11u8; 32]; + let minio_ciphertext = seal_minio_kms_data_key(&minio_data_key, &master_key, &context); + let aws_blob = vec![ + 0x01, 0x02, 0x02, 0x00, 0x78, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + ]; + let kms = || { + Arc::new(BareKmsProvider { + data_key: [0x22u8; 32], + unwrapped: std::sync::Mutex::new(Vec::new()), + }) + }; + let local = || -> Result, SseError> { Ok(Arc::new(TestSseDekProvider::new_with_key(master_key))) }; + let no_local = || -> Result, SseError> { + Err(SseError { + code: S3ErrorCode::InvalidRequest, + message: "no local master key".to_string(), + source: None, + }) + }; + + // MinIO's own object on a deployment whose backend also reads bare keys. + let provider = kms(); + let data_key = + crate::kms::provider::decrypt_unenveloped_sealed_dek(Some(provider.clone()), local(), &minio_ciphertext, "key", &context) + .await + .expect("a MinIO-sealed data key must open under the local master key"); + assert_eq!(data_key, minio_data_key); + assert!( + provider.unwrapped.lock().expect("unwrap log").is_empty(), + "a MinIO-sealed data key must never be sent to the KMS" + ); + + // A bare backend blob: with a local master key that cannot open it, and with none at all. + for local in [local(), no_local()] { + let provider = kms(); + let data_key = + crate::kms::provider::decrypt_unenveloped_sealed_dek(Some(provider.clone()), local, &aws_blob, "key", &context) + .await + .expect("a bare backend blob must be unwrapped by the KMS"); + assert_eq!(data_key, [0x22u8; 32]); + assert_eq!(*provider.unwrapped.lock().expect("unwrap log"), vec![aws_blob.clone()]); + } + + // Without a backend that reads bare keys, the MinIO route is the only one. + let data_key = crate::kms::provider::decrypt_unenveloped_sealed_dek(None, local(), &minio_ciphertext, "key", &context) + .await + .expect("the MinIO route is unchanged"); + assert_eq!(data_key, minio_data_key); + crate::kms::provider::decrypt_unenveloped_sealed_dek(None, local(), &aws_blob, "key", &context) + .await + .expect_err("bytes MinIO did not seal have no owner without such a backend"); + let error = crate::kms::provider::decrypt_unenveloped_sealed_dek(None, no_local(), &minio_ciphertext, "key", &context) + .await + .expect_err("a missing local master key is still reported as such"); + assert_eq!((error.code, error.message.as_str()), (S3ErrorCode::InvalidRequest, "no local master key")); +} + +#[test] +fn local_sse_dek_recognition_covers_exactly_the_local_formats() { + let wrapped = TestSseDekProvider::encrypt_dek([7u8; 32], [9u8; 32]).expect("local wrap"); + assert!(crate::kms::local::is_local_sse_dek(wrapped.as_bytes())); + assert!(crate::kms::local::is_local_sse_dek(b"bm9uY2U=:Y2lwaGVydGV4dA==")); + // A damaged local envelope is still the local provider's to diagnose. + assert!(crate::kms::local::is_local_sse_dek(br#" {"version": 9"#)); + + // An AWS blob: binary, and not UTF-8. + assert!(!crate::kms::local::is_local_sse_dek(&[0x01, 0x02, 0x02, 0x00, 0x78, 0x80, 0x81])); + // Text that merely contains a colon is not the legacy pair. + assert!(!crate::kms::local::is_local_sse_dek(b"vault:v1:Y2lwaGVydGV4dA==")); + assert!(!crate::kms::local::is_local_sse_dek(b"not base64:Y2lwaGVydGV4dA==")); + assert!(!crate::kms::local::is_local_sse_dek(b"")); +} + +/// Regression test for "local provider cached → dynamically enable KMS → decrypt KMS envelope". +/// +/// Verifies that a `TestSseDekProvider` previously cached in `GLOBAL_SSE_DEK_PROVIDER` +/// is NEVER selected to unwrap a KMS data-key envelope. The KMS-envelope branch must +/// read `GLOBAL_KMS_DEK_PROVIDER` (or fall back to `KmsSseDekProvider::new()`), not +/// the local-provider cache. +#[tokio::test] +async fn test_kms_envelope_never_routes_to_cached_local_provider() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + + // 1. Populate GLOBAL_SSE_DEK_PROVIDER with a local provider — the kind + // that `get_local_sse_dek_provider` would cache when KMS is absent. + let local_master_key = [0xAAu8; 32]; + *crate::kms::provider::GLOBAL_SSE_DEK_PROVIDER + .write() + .expect("write local provider into local cache") = Some(Arc::new(TestSseDekProvider::new_with_key(local_master_key))); + + // 2. Start a KMS service (dynamic enable). + let manager = configure_test_global_local_kms().await; + + // 3. Construct a KMS JSON envelope — the persisted format of a KMS-wrapped DEK. + // is_data_key_envelope() will return true for this payload. + let kms_envelope = br#"{ + "key_id": "envelope-key", + "master_key_id": "master-key-id", + "key_spec": "AES_256", + "encrypted_key": [10, 20, 30, 40], + "nonce": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], + "encryption_context": {}, + "created_at": "2024-01-01T00:00:00+00:00" + }"#; + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.to_string()), + (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string(kms_envelope)), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([0x14; 12])), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "envelope-key".to_string()), + ]); + + // 4. Decrypt the KMS envelope. Before the fix, this would pick up the cached + // TestSseDekProvider from GLOBAL_SSE_DEK_PROVIDER and either panic (wrong + // format) or produce garbage. After the fix, it routes to KmsSseDekProvider, + // which fails because the envelope contains dummy encrypted bytes that the + // test KMS cannot decrypt — but crucially the error code is NOT a local- + // provider error. + let error = match apply_managed_decryption_material(&HOST, "bucket", "object", &metadata, None).await { + Ok(_) => panic!("dummy KMS envelope must not produce valid decryption material"), + Err(error) => error, + }; + // The KMS service was reached (ServiceUnavailable or the KMS's own decrypt + // failure), not a local-provider format error. + assert!( + error.code == S3ErrorCode::ServiceUnavailable || error.code == S3ErrorCode::InternalError, + "KMS envelope must be routed to KMS provider, not local; got code {:?} msg '{}'", + error.code, + error.message, + ); + + manager.stop().await.expect("stop test KMS service"); + reset_sse_dek_provider(); +} + +#[tokio::test] +async fn test_managed_encryption_preserves_provider_unavailable_error() { + let _guard = lock_sse_test_state().await; + let manager = rustfs_kms::init_global_kms_service_manager(); + manager.stop().await.expect("stop global KMS service"); + reset_sse_dek_provider(); + *crate::kms::provider::GLOBAL_SSE_DEK_PROVIDER + .write() + .expect("update SSE DEK provider cache") = Some(Arc::new(UnavailableSseDekProvider)); + + let error = match apply_managed_encryption_material( + &HOST, + ManagedEncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: String::from(AMZ_ENCRYPTION_AES), + kms_key_id: None, + ssekms_context: None, + content_size: 0, + principal: None, + }, + ) + .await + { + Ok(_) => panic!("provider unavailability must fail managed encryption"), + Err(error) => error, + }; + assert_eq!(error.code, S3ErrorCode::ServiceUnavailable); + + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.to_string()), + ( + INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), + BASE64_STANDARD.encode_to_string(b"local-provider-format"), + ), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([0x14; 12])), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "test-key-id".to_string()), + ]); + let error = match apply_managed_decryption_material(&HOST, "bucket", "object", &metadata, None).await { + Ok(_) => panic!("provider unavailability must fail managed decryption"), + Err(error) => error, + }; + assert_eq!(error.code, S3ErrorCode::ServiceUnavailable); + + reset_sse_dek_provider(); +} + +#[tokio::test] +async fn test_kms_sse_dek_provider_uses_latest_reconfigured_service() { + use rustfs_kms::config::KmsConfig; + let _guard = lock_sse_test_state().await; + + let manager = Arc::new(rustfs_kms::KmsServiceManager::new()); + + manager + .reconfigure(KmsConfig::static_kms( + "first-key".to_string(), + BASE64_STANDARD.encode_to_string([0x11; 32]), + )) + .await + .expect("first KMS reconfigure should succeed"); + + let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) + .await + .expect("provider should initialize"); + let context = ObjectEncryptionContext::new("bucket".to_string(), "object".to_string()); + provider + .generate_sse_dek(&context, "first-key") + .await + .expect("provider should use the initial service"); + + manager + .reconfigure(KmsConfig::static_kms( + "second-key".to_string(), + BASE64_STANDARD.encode_to_string([0x22; 32]), + )) + .await + .expect("second KMS reconfigure should succeed"); + + provider + .generate_sse_dek(&context, "second-key") + .await + .expect("provider should resolve the latest reconfigured service"); + + manager.stop().await.expect("kms service should stop cleanly"); + let generate_error = provider + .generate_sse_dek(&context, "second-key") + .await + .expect_err("stopped KMS must reject data-key generation"); + assert_eq!(generate_error.code, S3ErrorCode::ServiceUnavailable); + let decrypt_error = provider + .decrypt_sse_dek(b"{}", "second-key", &context) + .await + .expect_err("stopped KMS must reject data-key decryption"); + assert_eq!(decrypt_error.code, S3ErrorCode::ServiceUnavailable); + #[cfg(feature = "rio-v2")] + { + let legacy_error = provider + .decrypt_legacy_sse_dek(b"{}", "second-key", &context) + .await + .expect_err("stopped KMS must reject legacy data-key decryption"); + assert_eq!(legacy_error.code, S3ErrorCode::ServiceUnavailable); + } +} + +#[test] +fn test_encryption_type_enum() { + // Test EncryptionType enum + assert_eq!(SSEType::SseS3, SSEType::SseS3); + assert_eq!(SSEType::SseKms, SSEType::SseKms); + assert_eq!(SSEType::SseC, SSEType::SseC); + assert_ne!(SSEType::SseS3, SSEType::SseKms); + + // Test Debug format + let debug_str = format!("{:?}", SSEType::SseKms); + assert!(debug_str.contains("SseKms")); +} + +#[test] +fn test_verify_ssec_key_match_returns_invalid_request() { + let stored = "stored_md5".to_string(); + let err = verify_ssec_key_match("wrong_md5", Some(&stored), false).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_verify_ssec_key_match_no_stored_returns_invalid_request() { + let err = verify_ssec_key_match("any_md5", None, false).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_ssec_for_read_non_encrypted_object() { + let metadata = HashMap::new(); + let result = validate_ssec_for_read(&metadata, None, None); + assert!(result.is_ok()); +} + +#[test] +fn test_validate_ssec_for_read_missing_customer_key() { + let mut metadata = HashMap::new(); + metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); + metadata.insert( + "x-amz-server-side-encryption-customer-key-md5".to_string(), + "DWygnHRtgiJ77HCm+1rvHw==".to_string(), + ); + + let err = validate_ssec_for_read(&metadata, None, None).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_ssec_for_read_wrong_key() { + // Key A is used to "encrypt" the object (stored MD5 is from key A). + let key_a = [42u8; 32]; + let stored_md5 = md5_base64(key_a); + + let mut metadata = HashMap::new(); + metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); + metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), stored_md5); + + // Key B is a different key; its MD5 won't match stored MD5. + let key_b = [99u8; 32]; + let key_b_b64 = BASE64_STANDARD.encode_to_string(key_b); + let key_b_md5 = md5_base64(key_b); + + let err = validate_ssec_for_read(&metadata, Some(&key_b_b64), Some(&key_b_md5)).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_ssec_for_read_correct_key() { + let key_bytes = [42u8; 32]; + let key_b64 = BASE64_STANDARD.encode_to_string(key_bytes); + let key_md5 = md5_base64(key_bytes); + + let mut metadata = HashMap::new(); + metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); + metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), key_md5.clone()); + + let result = validate_ssec_for_read(&metadata, Some(&key_b64), Some(&key_md5)); + assert!(result.is_ok()); +} + +#[test] +fn test_validate_ssec_for_read_spoofed_md5() { + // A client provides the correct stored MD5 in the header but with a + // DIFFERENT key. The server must recompute MD5 from the key bytes and + // reject the request because the recomputed MD5 won't match the header. + let real_key = [42u8; 32]; + let stored_md5 = md5_base64(real_key); + + let mut metadata = HashMap::new(); + metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); + metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), stored_md5.clone()); + + // Attacker has a different key but tries to pass the stored MD5 as their header + let fake_key = [99u8; 32]; + let fake_key_b64 = BASE64_STANDARD.encode_to_string(fake_key); + + let err = validate_ssec_for_read(&metadata, Some(&fake_key_b64), Some(&stored_md5)).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_sse_headers_for_read_rejects_kms_on_plain_object() { + let mut headers = HeaderMap::new(); + headers.insert("x-amz-server-side-encryption", http::HeaderValue::from_static("aws:kms")); + headers.insert("x-amz-server-side-encryption-aws-kms-key-id", http::HeaderValue::from_static("test-key")); + + let metadata = HashMap::new(); + let err = validate_sse_headers_for_read(&metadata, &headers).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[test] +fn test_validate_sse_headers_for_read_rejects_ssec_on_plain_object() { + let mut headers = HeaderMap::new(); + headers.insert( + "x-amz-server-side-encryption-customer-algorithm", + http::HeaderValue::from_static("AES256"), + ); + headers.insert("x-amz-server-side-encryption-customer-key", http::HeaderValue::from_static("test-key")); + headers.insert( + "x-amz-server-side-encryption-customer-key-md5", + http::HeaderValue::from_static("test-key-md5"), + ); + + let metadata = HashMap::new(); + let err = validate_sse_headers_for_read(&metadata, &headers).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_sse_headers_for_read_rejects_ssec_on_managed_object() { + let mut headers = HeaderMap::new(); + headers.insert( + "x-amz-server-side-encryption-customer-algorithm", + http::HeaderValue::from_static("AES256"), + ); + headers.insert("x-amz-server-side-encryption-customer-key", http::HeaderValue::from_static("test-key")); + headers.insert( + "x-amz-server-side-encryption-customer-key-md5", + http::HeaderValue::from_static("test-key-md5"), + ); + + let metadata = HashMap::from([("x-amz-server-side-encryption".to_string(), "aws:kms".to_string())]); + let err = validate_sse_headers_for_read(&metadata, &headers).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[test] +fn test_validate_sse_headers_for_read_allows_encrypted_object_without_request_headers() { + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()), + ("x-rustfs-encryption-key".to_string(), "encrypted-key".to_string()), + ]); + let headers = HeaderMap::new(); + assert!(validate_sse_headers_for_read(&metadata, &headers).is_ok()); +} + +#[test] +fn test_validate_sse_headers_for_read_rejects_sse_on_ssec_object() { + let mut headers = HeaderMap::new(); + headers.insert("x-amz-server-side-encryption", http::HeaderValue::from_static("aws:kms")); + headers.insert("x-amz-server-side-encryption-aws-kms-key-id", http::HeaderValue::from_static("test-key")); + + let metadata = HashMap::from([("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string())]); + let err = validate_sse_headers_for_read(&metadata, &headers).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); +} + +#[test] +fn test_validate_ssec_params_returns_invalid_request_on_bad_algorithm() { + let key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let key_md5 = md5_base64([42u8; 32]); + let params = SsecParams { + algorithm: "AES128".to_string(), + key, + key_md5, + }; + let err = validate_ssec_params(params).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn test_validate_ssec_params_returns_invalid_request_on_bad_md5() { + let key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let params = SsecParams { + algorithm: "AES256".to_string(), + key, + key_md5: BASE64_STANDARD.encode_to_string([99u8; 16]), + }; + let err = validate_ssec_params(params).unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); +} + +// ======================================================================== +// Unit tests for issue #2041: no mandatory KMS when encryption not used +// ======================================================================== + +/// When SSE-C params are not present and no managed SSE is requested, +/// encryption should be skipped (Ok(None)). Ensures we do not require KMS +/// when the client sends no encryption headers. +#[tokio::test] +async fn test_sse_encryption_skip_when_no_ssec_and_no_managed_sse_requested() { + let request = EncryptionRequest { + bucket: "test-bucket", + key: "test-key", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 1024, + principal: None, + }; + let result = sse_encryption(&HOST, request).await; + match &result { + Ok(None) => {} + Ok(Some(_)) => panic!("expected no encryption material when no SSE params provided"), + Err(e) => { + assert!( + !e.message.contains("No KMS key"), + "must not require KMS when no encryption requested; got: {}", + e.message + ); + } + } +} + +/// When SSE-C params are partial or invalid, sse_encryption must return an error. +#[tokio::test] +async fn test_sse_encryption_errors_on_invalid_ssec_params() { + let bucket = "test-bucket"; + let key = "test-key"; + let sse_key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let wrong_md5 = BASE64_STANDARD.encode_to_string([99u8; 16]); + + let request_wrong_md5 = EncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(sse_key.clone()), + sse_customer_key_md5: Some(wrong_md5), + content_size: 1024, + principal: None, + }; + let err = sse_encryption(&HOST, request_wrong_md5).await.unwrap_err(); + assert_eq!(err.code, S3ErrorCode::InvalidRequest); + + let request_unsupported_algorithm = EncryptionRequest { + bucket, + key, + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("unsupported-algo".to_string()), + sse_customer_key: Some(sse_key), + sse_customer_key_md5: Some(md5_base64([42u8; 32])), + content_size: 1024, + principal: None, + }; + let err = sse_encryption(&HOST, request_unsupported_algorithm).await.unwrap_err(); + assert!(err.code == S3ErrorCode::InvalidRequest || err.code == S3ErrorCode::InvalidArgument); +} + +/// When bucket has no SSE-S3/aws:kms setting and request has no SSE headers, +/// encryption should be skipped (Ok(None)). Ensures no mandatory bucket default SSE. +#[tokio::test] +async fn test_sse_prepare_encryption_skip_when_no_params_and_no_bucket_sse() { + let request = PrepareEncryptionRequest { + bucket: "test-bucket-no-sse-config", + key: "test-key", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }; + let result = sse_prepare_encryption(&HOST, request).await; + match &result { + Ok(None) => {} + Ok(Some(_)) => panic!("expected no encryption when bucket has no SSE config and no request SSE"), + Err(e) => { + assert!( + !e.message.contains("No KMS key"), + "must not require KMS when no bucket SSE and no request SSE; got: {}", + e.message + ); + } + } +} + +// ------------------------------------------------------------------------ +// Per-key KMS authorization on the SSE-KMS data path (rustfs/backlog#1582) +// ------------------------------------------------------------------------ + +fn enforcing_principal(allowed: bool) -> (SseKmsPrincipal, Arc) { + let authorizer = RecordingKmsKeyAuthorizer::new(allowed); + (SseKmsPrincipal::for_test("analyst", true, authorizer.clone()), authorizer) +} + +fn permissive_principal_with_enforcement_off() -> (SseKmsPrincipal, Arc) { + let authorizer = RecordingKmsKeyAuthorizer::new(false); + (SseKmsPrincipal::for_test("analyst", false, authorizer.clone()), authorizer) +} + +fn sse_kms_write(principal: Option<&SseKmsPrincipal>) -> EncryptionRequest<'_> { + EncryptionRequest { + bucket: "finance", + key: "ledger.csv", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), + ssekms_key_id: Some("finance-key".to_string()), + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 128, + principal, + } +} + +#[cfg(feature = "rio-v2")] +#[tokio::test] +async fn test_managed_sse_rio_v2_uses_object_key_metadata_roundtrip() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + if let Some(manager) = rustfs_kms::get_global_kms_service_manager() { + let _ = manager.stop().await; + } + let local_sse_master_key = local_sse_master_key_b64(); + + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), + ("RUSTFS_SSE_S3_MASTER_KEY", Some(local_sse_master_key.as_str())), + ], + async { + let request = EncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 4096, + principal: None, + }; + + let material = sse_encryption(&HOST, request) + .await + .expect("managed sse encryption") + .expect("managed sse material"); + assert_eq!(material.key_kind, EncryptionKeyKind::Object); + + let metadata = encryption_material_to_metadata(&material).expect("managed SSE metadata should serialize"); + assert!(!metadata.contains_key(INTERNAL_ENCRYPTION_KEY_HEADER)); + assert!(!metadata.contains_key(INTERNAL_ENCRYPTION_IV_HEADER)); + + let sealing_iv = metadata + .get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER) + .expect("minio sealing iv should be stored"); + let sealed_key = metadata + .get(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER) + .expect("minio sealed key should be stored"); + assert_eq!(BASE64_STANDARD.decode_to_vec(sealing_iv).expect("decode iv").len(), SEALED_KEY_IV_SIZE); + assert_eq!( + BASE64_STANDARD.decode_to_vec(sealed_key).expect("decode sealed key").len(), + SEALED_KEY_SIZE + ); + + let decrypted = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "object", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect("managed sse decryption") + .expect("managed decryption material"); + + assert_eq!(decrypted.key_kind, EncryptionKeyKind::Object); + assert_eq!(decrypted.key_bytes, material.key_bytes); + }, + ) + .await; + + reset_sse_dek_provider(); +} + +#[cfg(feature = "rio-v2")] +#[tokio::test] +async fn test_ssec_rio_v2_uses_sealed_object_key_metadata_roundtrip() { + let customer_key_bytes = [0x42u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); + + let material = sse_encryption( + &HOST, + EncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(customer_key.clone()), + sse_customer_key_md5: Some(customer_key_md5.clone()), + content_size: 4096, + principal: None, + }, + ) + .await + .expect("sse-c encryption") + .expect("sse-c material"); + + assert_eq!(material.key_kind, EncryptionKeyKind::Object); + + let metadata = encryption_material_to_metadata(&material).expect("sse-c metadata should serialize"); + assert_eq!( + metadata.get(MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER).map(String::as_str), + Some(MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM) + ); + assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_IV_HEADER)); + assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)); + + let decrypted = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "object", + metadata: &metadata, + sse_customer_key: Some(&customer_key), + sse_customer_key_md5: Some(&customer_key_md5), + principal: None, + }, + ) + .await + .expect("sse-c decryption") + .expect("sse-c decryption material"); + + assert_eq!(decrypted.key_kind, EncryptionKeyKind::Object); + assert_eq!(decrypted.key_bytes, material.key_bytes); +} + +#[cfg(feature = "rio-v2")] +#[tokio::test] +async fn test_minio_shaped_ssec_metadata_resolves_and_classifies() { + let customer_key_bytes = [0x51u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); + + let material = sse_encryption( + &HOST, + EncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(customer_key.clone()), + sse_customer_key_md5: Some(customer_key_md5.clone()), + content_size: 4096, + principal: None, + }, + ) + .await + .expect("sse-c encryption") + .expect("sse-c material"); + let mut metadata = encryption_material_to_metadata(&material).expect("sse-c metadata should serialize"); + strip_to_minio_ssec_shape(&mut metadata); + + let mut headers = HeaderMap::new(); + headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static("AES256")); + headers.insert( + "x-amz-server-side-encryption-customer-key", + HeaderValue::from_str(&customer_key).expect("customer key header"), + ); + headers.insert( + "x-amz-server-side-encryption-customer-key-md5", + HeaderValue::from_str(&customer_key_md5).expect("customer key MD5 header"), + ); + let decrypted = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "object", + metadata: &metadata, + sse_customer_key: Some(&customer_key), + sse_customer_key_md5: Some(&customer_key_md5), + principal: None, + }, + ) + .await + .expect("minio-shaped SSE-C decryption") + .expect("minio-shaped SSE-C material"); + assert_eq!(decrypted.key_kind, EncryptionKeyKind::Object); + assert_eq!(decrypted.key_bytes, material.key_bytes); + + // HEAD-path key validation: no stored MD5 to compare against, so a + // self-consistent key passes here and the unseal remains the proof. + crate::core::s3::ssec::validate_ssec_for_read(&metadata, Some(&customer_key), Some(&customer_key_md5)) + .expect("self-consistent SSE-C parameters validate"); + crate::core::s3::ssec::validate_ssec_for_read(&metadata, None, None).expect_err("missing SSE-C parameters must be rejected"); + + // Response classification reports SSE-C, not managed SSE. + let classified = classify_sse_read_response( + &HOST, + DecryptionRequest { + bucket: "bucket", + key: "object", + metadata: &metadata, + sse_customer_key: Some(&customer_key), + sse_customer_key_md5: Some(&customer_key_md5), + principal: None, + }, + ) + .await + .expect("minio-shaped sse-c classification") + .expect("minio-shaped sse-c response headers"); + assert!(classified.sse_customer_algorithm.is_some()); + assert!(classified.ssekms_key_id.is_none()); +} + +fn sse_s3_object_metadata() -> HashMap { + HashMap::from([ + ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.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(), "AES256".to_string()), + ]) +} + +#[test] +fn kms_authorization_subject_scopes_to_enforced_sse_kms_requests_only() { + let (principal, _) = enforcing_principal(true); + + assert!(crate::core::s3::authorization::kms_authorization_subject(true, Some(&principal), SSEType::SseKms).is_some()); + // Compatibility switch off keeps the pre-enforcement behaviour. + assert!(crate::core::s3::authorization::kms_authorization_subject(false, Some(&principal), SSEType::SseKms).is_none()); + // SSE-S3 and SSE-C are exempt, matching AWS. + assert!(crate::core::s3::authorization::kms_authorization_subject(true, Some(&principal), SSEType::SseS3).is_none()); + assert!(crate::core::s3::authorization::kms_authorization_subject(true, Some(&principal), SSEType::SseC).is_none()); + // No principal means an internal caller. + assert!(crate::core::s3::authorization::kms_authorization_subject(true, None, SSEType::SseKms).is_none()); +} + +#[tokio::test] +async fn sse_kms_write_without_generate_data_key_is_denied() { + let (principal, authorizer) = enforcing_principal(false); + + let error = sse_encryption(&HOST, sse_kms_write(Some(&principal))) + .await + .expect_err("SSE-KMS write must fail without kms:GenerateDataKey on the key"); + + assert_eq!(error.code, S3ErrorCode::AccessDenied); + assert_eq!(authorizer.calls(), vec![(KmsAction::GenerateDataKeyAction, "finance-key".to_string())]); +} + +#[tokio::test] +async fn sse_kms_write_with_generate_data_key_clears_the_gate() { + let (principal, authorizer) = enforcing_principal(true); + + let outcome = sse_encryption(&HOST, sse_kms_write(Some(&principal))).await; + + assert!( + !matches!(&outcome, Err(error) if error.code == S3ErrorCode::AccessDenied), + "granting kms:GenerateDataKey on the key must clear the authorization gate" + ); + assert_eq!(authorizer.calls(), vec![(KmsAction::GenerateDataKeyAction, "finance-key".to_string())]); +} + +#[tokio::test] +async fn sse_kms_read_without_decrypt_is_denied() { + let (principal, authorizer) = enforcing_principal(false); + let metadata = sse_kms_object_metadata(); + + let error = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: Some(&principal), + }, + ) + .await + .expect_err("SSE-KMS read must fail without kms:Decrypt on the key"); + + assert_eq!(error.code, S3ErrorCode::AccessDenied); + assert_eq!(authorizer.calls(), vec![(KmsAction::DecryptAction, "finance-key".to_string())]); +} + +#[tokio::test] +async fn sse_s3_objects_are_exempt_from_kms_key_authorization() { + let (principal, authorizer) = enforcing_principal(false); + let metadata = sse_s3_object_metadata(); + + let write = sse_encryption( + &HOST, + EncryptionRequest { + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), + ssekms_key_id: None, + ..sse_kms_write(Some(&principal)) + }, + ) + .await; + let read = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: Some(&principal), + }, + ) + .await; + + assert!(!matches!(&write, Err(error) if error.code == S3ErrorCode::AccessDenied)); + assert!(!matches!(&read, Err(error) if error.code == S3ErrorCode::AccessDenied)); + assert!(authorizer.calls().is_empty(), "SSE-S3 must never consult KMS key policy"); +} + +#[tokio::test] +async fn ssec_requests_are_exempt_from_kms_key_authorization() { + let (principal, authorizer) = enforcing_principal(false); + let customer_key = BASE64_STANDARD.encode_to_string([42u8; 32]); + let customer_key_md5 = md5_base64([42u8; 32]); + + let outcome = sse_encryption( + &HOST, + EncryptionRequest { + server_side_encryption: None, + ssekms_key_id: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(customer_key), + sse_customer_key_md5: Some(customer_key_md5), + ..sse_kms_write(Some(&principal)) + }, + ) + .await; + + assert!(outcome.is_ok(), "SSE-C must not be gated on KMS key policy"); + assert!(authorizer.calls().is_empty(), "SSE-C never reaches KMS"); +} + +#[tokio::test] +async fn internal_callers_bypass_kms_key_authorization() { + let metadata = sse_kms_object_metadata(); + + // No principal: replication, lifecycle transition, heal and scanner reach the SSE + // layer below the S3 authorization boundary and must not be interrupted. + let write = sse_encryption(&HOST, sse_kms_write(None)).await; + let read = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await; + + assert!(!matches!(&write, Err(error) if error.code == S3ErrorCode::AccessDenied)); + assert!(!matches!(&read, Err(error) if error.code == S3ErrorCode::AccessDenied)); +} + +#[tokio::test] +async fn enforcement_switch_off_preserves_current_behaviour() { + let (principal, authorizer) = permissive_principal_with_enforcement_off(); + let metadata = sse_kms_object_metadata(); + + let write = sse_encryption(&HOST, sse_kms_write(Some(&principal))).await; + let read = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: Some(&principal), + }, + ) + .await; + + assert!(!matches!(&write, Err(error) if error.code == S3ErrorCode::AccessDenied)); + assert!(!matches!(&read, Err(error) if error.code == S3ErrorCode::AccessDenied)); + assert!( + authorizer.calls().is_empty(), + "with the switch off the data path must not evaluate KMS key policy at all" + ); +} + +#[tokio::test] +async fn multipart_write_authorization_uses_stored_key_and_current_principal() { + let (denied, denied_authorizer) = enforcing_principal(false); + let (allowed, allowed_authorizer) = enforcing_principal(true); + let metadata = sse_kms_object_metadata(); + let error = crate::core::s3::authorization::authorize_sse_kms_multipart_write(&HOST, Some(&denied), &metadata) + .await + .expect_err("upload ID must not grant its creator's KMS permission"); + assert_eq!(error.code, S3ErrorCode::AccessDenied); + assert_eq!( + denied_authorizer.calls(), + vec![(KmsAction::GenerateDataKeyAction, "finance-key".to_string())] + ); + crate::core::s3::authorization::authorize_sse_kms_multipart_write(&HOST, Some(&allowed), &metadata) + .await + .expect("authorized writer"); + assert_eq!( + allowed_authorizer.calls(), + vec![(KmsAction::GenerateDataKeyAction, "finance-key".to_string())] + ); + for metadata in [HashMap::new(), sse_s3_object_metadata(), multipart_ssec_metadata(42)] { + crate::core::s3::authorization::authorize_sse_kms_multipart_write(&HOST, Some(&denied), &metadata) + .await + .expect("non-KMS upload"); + } + assert_eq!(denied_authorizer.calls().len(), 1); + let (off, off_authorizer) = permissive_principal_with_enforcement_off(); + crate::core::s3::authorization::authorize_sse_kms_multipart_write(&HOST, Some(&off), &metadata) + .await + .expect("enforcement off"); + crate::core::s3::authorization::authorize_sse_kms_multipart_write(&HOST, None, &metadata) + .await + .expect("trusted internal writer"); + assert!(off_authorizer.calls().is_empty()); +} + +#[tokio::test] +async fn copy_source_read_authorization_targets_the_source_key() { + let (denied, denied_authorizer) = enforcing_principal(false); + let (allowed, allowed_authorizer) = enforcing_principal(true); + let metadata = sse_kms_object_metadata(); + + let error = authorize_sse_kms_object_read(&HOST, Some(&denied), &metadata) + .await + .expect_err("copying an SSE-KMS source must require kms:Decrypt on the source key"); + assert_eq!(error.code, S3ErrorCode::AccessDenied); + assert_eq!(denied_authorizer.calls(), vec![(KmsAction::DecryptAction, "finance-key".to_string())]); + + authorize_sse_kms_object_read(&HOST, Some(&allowed), &metadata) + .await + .expect("kms:Decrypt on the source key must allow the copy"); + assert_eq!(allowed_authorizer.calls(), vec![(KmsAction::DecryptAction, "finance-key".to_string())]); +} + +#[tokio::test] +async fn copy_source_read_authorization_skips_unencrypted_and_sse_s3_sources() { + let (principal, authorizer) = enforcing_principal(false); + + authorize_sse_kms_object_read(&HOST, Some(&principal), &HashMap::new()) + .await + .expect("plaintext sources are not gated"); + authorize_sse_kms_object_read(&HOST, Some(&principal), &sse_s3_object_metadata()) + .await + .expect("SSE-S3 sources are not gated"); + + assert!(authorizer.calls().is_empty()); +} + +// ======================================================================== +// Data-plane KMS audit attachment +// ======================================================================== + +fn audited_principal(enforced: bool, allowed: bool) -> (SseKmsPrincipal, Arc) { + let audit = Arc::new(crate::core::audit::KmsRequestAudit::default()); + let authorizer = RecordingKmsKeyAuthorizer::new(allowed); + let principal = SseKmsPrincipal::for_test("analyst", enforced, authorizer).with_request_audit(audit.clone()); + (principal, audit) +} + +fn audit_tag(tags: &[(&'static str, serde_json::Value)], key: &str) -> Option { + tags.iter() + .find(|(candidate, _)| *candidate == key) + .and_then(|(_, value)| value.as_str().map(str::to_string)) +} + +#[tokio::test] +async fn sse_kms_write_and_read_summarise_key_id_and_outcome_for_the_audit_entry() { + use rustfs_kms::types::{CreateKeyRequest, KeyUsage}; + let _guard = lock_sse_test_state().await; + + reset_sse_dek_provider(); + let manager = configure_test_global_local_kms().await; + manager + .get_encryption_service() + .await + .expect("encryption service should exist") + .create_key(CreateKeyRequest { + key_name: Some("audit-key".to_string()), + key_usage: KeyUsage::EncryptDecrypt, + description: None, + policy: None, + tags: HashMap::new(), + origin: None, + }) + .await + .expect("kms test key should be created"); + let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) + .await + .expect("kms provider should initialize from the configured test manager"); + crate::kms::provider::set_sse_dek_provider_for_test(Arc::new(provider)); + + let (write_principal, write_audit) = audited_principal(false, true); + let material = sse_encryption( + &HOST, + EncryptionRequest { + bucket: "finance", + key: "ledger.csv", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), + ssekms_key_id: Some("audit-key".to_string()), + ssekms_context: Some(HashMap::from([("tenant".to_string(), "acct-4711".to_string())])), + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 128, + principal: Some(&write_principal), + }, + ) + .await + .expect("sse-kms encryption should succeed") + .expect("managed sse-kms material"); + + let write_tags = write_audit.audit_tags(); + assert_eq!(audit_tag(&write_tags, "sseType").as_deref(), Some("SSE-KMS")); + assert_eq!(audit_tag(&write_tags, "kmsKeyId").as_deref(), Some("audit-key")); + assert_eq!(audit_tag(&write_tags, "kmsOutcome").as_deref(), Some("success")); + assert_eq!(audit_tag(&write_tags, "kmsErrorClass"), None, "a successful request has no error class"); + + // The audit entry reaches every configured target: no encoding of the data + // key, and no caller-supplied encryption-context value, may appear in it. + let rendered = format!("{write_tags:?}"); + let encrypted_data_key = material.encrypted_data_key.clone().expect("managed sse wraps a data key"); + for secret in [ + BASE64_STANDARD.encode_to_string(&encrypted_data_key), + BASE64_STANDARD.encode_to_string(material.key_bytes), + format!("{:?}", material.key_bytes), + format!("{encrypted_data_key:?}"), + "acct-4711".to_string(), + ] { + assert!(!rendered.contains(&secret), "audit tags must not carry key material: {rendered}"); + } + + let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); + let (read_principal, read_audit) = audited_principal(false, true); + sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: Some(&read_principal), + }, + ) + .await + .expect("sse-kms decryption should succeed") + .expect("managed sse-kms material"); + + let read_tags = read_audit.audit_tags(); + assert_eq!(audit_tag(&read_tags, "sseType").as_deref(), Some("SSE-KMS")); + assert_eq!(audit_tag(&read_tags, "kmsKeyId").as_deref(), Some("audit-key")); + assert_eq!(audit_tag(&read_tags, "kmsOutcome").as_deref(), Some("success")); +} + +async fn install_test_kms_provider(key_name: &str) { + use rustfs_kms::types::{CreateKeyRequest, KeyUsage}; + + reset_sse_dek_provider(); + let manager = configure_test_global_local_kms().await; + manager + .get_encryption_service() + .await + .expect("encryption service should exist") + .create_key(CreateKeyRequest { + key_name: Some(key_name.to_string()), + key_usage: KeyUsage::EncryptDecrypt, + description: None, + policy: None, + tags: HashMap::new(), + origin: None, + }) + .await + .expect("kms test key should be created"); + let provider = KmsSseDekProvider::new_with_service_manager(manager) + .await + .expect("kms provider should initialize from the configured test manager"); + crate::kms::provider::set_sse_dek_provider_for_test(Arc::new(provider)); +} + +fn sse_kms_request<'a>(bucket: &'a str, key: &'a str, context: HashMap) -> EncryptionRequest<'a> { + EncryptionRequest { + bucket, + key, + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), + ssekms_key_id: Some("binding-key".to_string()), + ssekms_context: Some(context), + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 64, + principal: None, + } +} + +#[tokio::test] +async fn sse_kms_write_rejects_a_context_key_equal_to_the_bucket_name() { + let _guard = lock_sse_test_state().await; + install_test_kms_provider("binding-key").await; + let context = HashMap::from([("finance".to_string(), "finance/elsewhere".to_string())]); + + let err = sse_encryption(&HOST, sse_kms_request("finance", "ledger.csv", context.clone())) + .await + .expect_err("a context entry under the bucket name must be rejected"); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); + assert!( + err.message.contains("\"finance\""), + "the message must name the offending key: {}", + err.message + ); + + // CreateMultipartUpload generates the session data key through the + // prepare path; it must refuse the same context. + let err = sse_prepare_encryption( + &HOST, + PrepareEncryptionRequest { + bucket: "finance", + key: "ledger.csv", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), + ssekms_key_id: Some("binding-key".to_string()), + ssekms_context: Some(context), + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect_err("the multipart prepare path must reject the same context"); + assert_eq!(err.code, S3ErrorCode::InvalidArgument); + + reset_sse_dek_provider(); +} + +#[tokio::test] +async fn sse_kms_write_keeps_the_location_binding_when_the_context_names_another_bucket() { + let _guard = lock_sse_test_state().await; + install_test_kms_provider("binding-key").await; + let context = HashMap::from([ + ("archive".to_string(), "archive/ledger.csv".to_string()), + ("tenant".to_string(), "acct-4711".to_string()), + ]); + + let material = sse_encryption(&HOST, sse_kms_request("finance", "ledger.csv", context)) + .await + .expect("a key naming a different bucket is an ordinary context entry") + .expect("managed sse-kms material"); + let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); + + let read = |key: &'static str| { + let metadata = metadata.clone(); + async move { + sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key, + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + } + }; + let decrypted = read("ledger.csv") + .await + .expect("the object decrypts at its own location") + .expect("managed sse-kms material"); + assert_eq!(decrypted.key_bytes, material.key_bytes); + read("relocated.csv") + .await + .expect_err("the data key stays bound to the object's location"); + + reset_sse_dek_provider(); +} + +#[tokio::test] +async fn sse_kms_objects_stored_with_a_bucket_keyed_context_stay_readable() { + let _guard = lock_sse_test_state().await; + install_test_kms_provider("binding-key").await; + let context = HashMap::from([("finance".to_string(), "finance/elsewhere".to_string())]); + + // Objects written before the write-side rejection reached the inner + // routine without validation; reproduce that stored shape directly. + let material = apply_managed_encryption_material_inner( + &HOST, + ManagedEncryptionRequest { + bucket: "finance", + key: "ledger.csv", + server_side_encryption: String::from(AMZ_ENCRYPTION_KMS), + kms_key_id: Some("binding-key".to_string()), + ssekms_context: Some(context), + content_size: 64, + principal: None, + }, + ) + .await + .expect("the inner routine does not validate the client context"); + let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); + + let decrypted = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect("an existing object must stay readable after the write-side rejection") + .expect("managed sse-kms material"); + assert_eq!(decrypted.key_bytes, material.key_bytes); + + reset_sse_dek_provider(); +} + +#[tokio::test] +async fn sse_c_requests_produce_no_kms_audit_summary() { + let key = [0x21u8; 32]; + let (principal, audit) = audited_principal(false, true); + + sse_encryption( + &HOST, + EncryptionRequest { + bucket: "finance", + key: "ledger.csv", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(BASE64_STANDARD.encode_to_string(key)), + sse_customer_key_md5: Some(md5_base64(key)), + content_size: 128, + principal: Some(&principal), + }, + ) + .await + .expect("sse-c encryption should succeed") + .expect("sse-c material"); + + assert!( + audit.audit_tags().is_empty(), + "SSE-C keys never reach KMS, so the request has no KMS outcome to report" + ); +} + +#[tokio::test] +async fn denied_sse_kms_read_is_summarised_as_an_access_denied_failure() { + let (principal, audit) = audited_principal(true, false); + + authorize_sse_kms_object_read(&HOST, Some(&principal), &sse_kms_object_metadata()) + .await + .expect_err("an unauthorized principal must not read the source key"); + + let tags = audit.audit_tags(); + assert_eq!(audit_tag(&tags, "sseType").as_deref(), Some("SSE-KMS")); + assert_eq!(audit_tag(&tags, "kmsKeyId").as_deref(), Some("finance-key")); + assert_eq!(audit_tag(&tags, "kmsOutcome").as_deref(), Some("failure")); + assert_eq!(audit_tag(&tags, "kmsErrorClass").as_deref(), Some("access_denied")); +} + +// ======================================================================== +// Read-side response classification (single-decrypt GET path) +// ======================================================================== + +/// An AES256 object is read under the same key-id resolution as aws:kms +/// (authorization needs it), but the response must not advertise that +/// internal wrapping key. +#[tokio::test] +async fn classification_withholds_the_wrapping_key_for_sse_s3_reads() { + let metadata = HashMap::from([ + ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.to_string()), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "service-default".to_string()), + (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string([1u8; 16])), + (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([2u8; 12])), + ]); + let headers = crate::core::read::classify_sse_read_response( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect("sse-s3 classification should succeed") + .expect("managed metadata should classify"); + assert_eq!(headers.server_side_encryption.as_str(), AMZ_ENCRYPTION_AES); + assert_eq!(headers.ssekms_key_id, None); +} + +#[tokio::test] +async fn classification_reproduces_managed_read_headers_and_audit_without_a_kms_unwrap() { + use rustfs_kms::types::{CreateKeyRequest, KeyUsage}; + let _guard = lock_sse_test_state().await; + + reset_sse_dek_provider(); + let manager = configure_test_global_local_kms().await; + manager + .get_encryption_service() + .await + .expect("encryption service should exist") + .create_key(CreateKeyRequest { + key_name: Some("classify-key".to_string()), + key_usage: KeyUsage::EncryptDecrypt, + description: None, + policy: None, + tags: HashMap::new(), + origin: None, + }) + .await + .expect("kms test key should be created"); + let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) + .await + .expect("kms provider should initialize from the configured test manager"); + crate::kms::provider::set_sse_dek_provider_for_test(Arc::new(provider)); + + let material = sse_encryption( + &HOST, + EncryptionRequest { + bucket: "finance", + key: "ledger.csv", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), + ssekms_key_id: Some("classify-key".to_string()), + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 128, + principal: None, + }, + ) + .await + .expect("sse-kms encryption should succeed") + .expect("managed sse-kms material"); + let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); + + // Header parity against the unwrap-based path, on the same metadata. + let unwrapped = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect("sse-kms decryption should succeed") + .expect("managed sse-kms material"); + + // Classification must not need a data-key unwrap at all: drop the + // provider before classifying, so any KMS round trip would fail loudly. + reset_sse_dek_provider(); + + let (read_principal, read_audit) = audited_principal(false, true); + let headers = classify_sse_read_response( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: Some(&read_principal), + }, + ) + .await + .expect("classification should succeed without a dek provider") + .expect("managed metadata must classify as encrypted"); + + assert_eq!(headers.server_side_encryption, unwrapped.server_side_encryption); + assert_eq!(headers.ssekms_key_id, unwrapped.kms_key_id); + assert_eq!(headers.sse_customer_algorithm, None); + assert_eq!(headers.sse_customer_key_md5, None); + + // Audit parity: the same summary fields the unwrap-based read recorded. + let read_tags = read_audit.audit_tags(); + assert_eq!(audit_tag(&read_tags, "sseType").as_deref(), Some("SSE-KMS")); + assert_eq!(audit_tag(&read_tags, "kmsKeyId").as_deref(), Some("classify-key")); + assert_eq!(audit_tag(&read_tags, "kmsOutcome").as_deref(), Some("success")); + assert_eq!(audit_tag(&read_tags, "kmsErrorClass"), None); +} + +#[tokio::test] +async fn classification_denies_an_unauthorized_principal_with_the_same_audit_summary() { + let (principal, audit) = audited_principal(true, false); + + let error = classify_sse_read_response( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &sse_kms_object_metadata(), + sse_customer_key: None, + sse_customer_key_md5: None, + principal: Some(&principal), + }, + ) + .await + .expect_err("an unauthorized principal must not classify against the key"); + assert_eq!(error.code, S3ErrorCode::AccessDenied); + + let tags = audit.audit_tags(); + assert_eq!(audit_tag(&tags, "sseType").as_deref(), Some("SSE-KMS")); + assert_eq!(audit_tag(&tags, "kmsKeyId").as_deref(), Some("finance-key")); + assert_eq!(audit_tag(&tags, "kmsOutcome").as_deref(), Some("failure")); + assert_eq!(audit_tag(&tags, "kmsErrorClass").as_deref(), Some("access_denied")); +} + +#[test] +fn read_response_projection_uses_shared_managed_metadata_compatibility() { + let context_json = r#"{"tenant":"s3-select"}"#; + let context = BASE64_STANDARD.encode_to_string(context_json); + let key_id = "arn:aws:kms:us-east-1:123456789012:key/select"; + let kms_metadata = HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS.to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID.to_string(), + key_id.to_string(), + ), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), key_id.to_string()), + (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_string(), key_id.to_string()), + (MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), context.clone()), + ]); + + let headers = project_sse_read_response_headers(&kms_metadata, None, None) + .expect("valid SSE-KMS metadata should project response headers"); + assert_eq!( + headers + .get(crate::core::s3::headers::X_AMZ_SERVER_SIDE_ENCRYPTION) + .expect("SSE-KMS algorithm"), + rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS + ); + assert_eq!( + headers + .get(crate::core::s3::headers::X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID) + .expect("SSE-KMS key ID"), + key_id + ); + assert_eq!( + headers + .get(crate::core::s3::headers::X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT) + .expect("SSE-KMS context"), + context.as_str() + ); + + let s3_metadata = HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_AES.to_string(), + ), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "default".to_string()), + (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_string(), "default".to_string()), + ( + rustfs_utils::http::object_encryption_keys::INTERNAL_ENCRYPTION_CONTEXT_HEADER.to_string(), + r#"{"bucket":"select"}"#.to_string(), + ), + ("x-amz-meta-private".to_string(), "private".to_string()), + ]); + let headers = project_sse_read_response_headers(&s3_metadata, None, None) + .expect("valid SSE-S3 metadata should project response headers"); + assert_eq!(headers.len(), 1); + assert_eq!( + headers + .get(crate::core::s3::headers::X_AMZ_SERVER_SIDE_ENCRYPTION) + .expect("SSE-S3 algorithm"), + rustfs_utils::http::headers::AMZ_ENCRYPTION_AES + ); + + let plaintext = project_sse_read_response_headers(&HashMap::new(), None, None) + .expect("plaintext metadata should not produce SSE headers"); + assert!(plaintext.is_empty()); +} + +#[test] +fn read_response_projection_returns_only_validated_ssec_values() { + let key_md5 = "customer-key-md5"; + let metadata = HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_AES.to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5.to_string(), + key_md5.to_string(), + ), + ]); + let algorithm = String::from(rustfs_utils::http::headers::AMZ_ENCRYPTION_AES); + let key_md5 = String::from(key_md5); + + let headers = project_sse_read_response_headers(&metadata, Some(&algorithm), Some(&key_md5)) + .expect("validated SSE-C values should project response headers"); + assert_eq!(headers.len(), 2); + assert_eq!( + headers + .get(crate::core::s3::headers::X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM) + .expect("SSE-C algorithm"), + rustfs_utils::http::headers::AMZ_ENCRYPTION_AES + ); + assert_eq!( + headers + .get(crate::core::s3::headers::X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5) + .expect("SSE-C key MD5"), + key_md5.as_str() + ); + assert!( + headers + .get(rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY) + .is_none() + ); + + let missing_algorithm = project_sse_read_response_headers(&metadata, None, Some(&key_md5)) + .expect_err("missing SSE-C algorithm must fail before streaming"); + assert_eq!(missing_algorithm.code, S3ErrorCode::InvalidRequest); +} + +#[test] +fn read_response_projection_rejects_unvalidated_or_sensitive_metadata() { + let invalid_context = "not-base64"; + let persisted_context = "must-not-leak-context"; + let persisted_key = "must-not-leak-key"; + let corrupt_metadata = [ + HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION.to_ascii_lowercase(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_AES.to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION.to_ascii_uppercase(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS.to_string(), + ), + ]), + HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS.to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_AES.to_string(), + ), + ]), + HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS.to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID.to_string(), + "key-1".to_string(), + ), + (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "key-2".to_string()), + ]), + HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS.to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID.to_string(), + "key-1".to_string(), + ), + (MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), invalid_context.to_string()), + ]), + HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS.to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID.to_string(), + "key-1".to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT.to_string(), + persisted_context.to_string(), + ), + ]), + HashMap::from([ + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM.to_string(), + rustfs_utils::http::headers::AMZ_ENCRYPTION_AES.to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5.to_string(), + "customer-key-md5".to_string(), + ), + ( + rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY.to_ascii_uppercase(), + persisted_key.to_string(), + ), + ]), + ]; + + for metadata in corrupt_metadata { + let error = + project_sse_read_response_headers(&metadata, None, None).expect_err("corrupt encryption metadata must fail closed"); + assert_eq!(error.code, S3ErrorCode::InternalError); + for sensitive in [invalid_context, persisted_context, persisted_key] { + assert!(!error.to_string().contains(sensitive)); + } + } + + let marker_only_kms = HashMap::from([(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), "sealed".to_string())]); + let marker_error = project_sse_read_response_headers(&marker_only_kms, None, None) + .expect_err("marker-only KMS metadata must not bypass the existing authorization classifier"); + assert_eq!(marker_error.code, S3ErrorCode::InternalError); +} + +#[tokio::test] +async fn classification_matches_ssec_validation_and_headers() { + let key = [0x42u8; 32]; + let key_b64 = BASE64_STANDARD.encode_to_string(key); + let key_md5 = md5_base64(key); + let metadata = HashMap::from([ + ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()), + ("x-amz-server-side-encryption-customer-key-md5".to_string(), key_md5.clone()), + ]); + + let headers = classify_sse_read_response( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: Some(&key_b64.clone()), + sse_customer_key_md5: Some(&key_md5.clone()), + principal: None, + }, + ) + .await + .expect("a matching customer key should classify") + .expect("SSE-C metadata must classify as encrypted"); + assert_eq!(headers.server_side_encryption.as_str(), AMZ_ENCRYPTION_AES); + assert_eq!(headers.sse_customer_algorithm.as_deref(), Some("AES256")); + assert_eq!(headers.sse_customer_key_md5.as_deref(), Some(key_md5.as_str())); + assert_eq!(headers.ssekms_key_id, None); + + // Same error and precedence as `sse_decryption` when the key is absent… + let missing = classify_sse_read_response( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect_err("an SSE-C object must not classify without the customer key"); + assert_eq!(missing.code, S3ErrorCode::InvalidRequest); + + // …and when the provided key does not match the stored digest. + let other_key = [0x43u8; 32]; + let mismatch = classify_sse_read_response( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: Some(&BASE64_STANDARD.encode_to_string(other_key)), + sse_customer_key_md5: Some(&md5_base64(other_key)), + principal: None, + }, + ) + .await + .expect_err("a mismatched customer key must not classify"); + let parity = sse_decryption( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &metadata, + sse_customer_key: Some(&BASE64_STANDARD.encode_to_string(other_key)), + sse_customer_key_md5: Some(&md5_base64(other_key)), + principal: None, + }, + ) + .await + .expect_err("the unwrap-based path rejects the same mismatch"); + assert_eq!(mismatch.code, parity.code); +} + +#[tokio::test] +async fn classification_reports_plaintext_objects_as_unencrypted() { + let result = classify_sse_read_response( + &HOST, + DecryptionRequest { + bucket: "finance", + key: "ledger.csv", + metadata: &HashMap::new(), + sse_customer_key: None, + sse_customer_key_md5: None, + principal: None, + }, + ) + .await + .expect("plaintext metadata should classify cleanly"); + assert!(result.is_none(), "objects without SSE metadata carry no SSE response headers"); +} + +#[test] +fn kms_backend_failures_keep_the_kms_audit_error_class() { + assert_eq!( + crate::core::audit::kms_data_plane_error_class(&kms_operation_error(rustfs_kms::KmsError::key_not_found("finance-key"))), + "key_not_found" + ); + assert_eq!( + crate::core::audit::kms_data_plane_error_class(&kms_operation_error(rustfs_kms::KmsError::access_denied("nope"))), + "access_denied" + ); + // Failures raised by the SSE layer itself never saw a KmsError; they are + // classified by the boundary they surfaced through. + assert_eq!( + crate::core::audit::kms_data_plane_error_class(&SseError { + code: S3ErrorCode::AccessDenied, + message: "Access Denied".to_string(), + source: None, + }), + "access_denied" + ); + assert_eq!( + crate::core::audit::kms_data_plane_error_class(&SseError::internal("no KMS key available")), + "sse_internal" + ); +} + +#[test] +fn a_request_audit_slot_is_reachable_only_while_its_scope_lives() { + let scope = crate::core::audit::KmsRequestAuditScope::register("request-under-audit"); + let slot = crate::core::audit::kms_request_audit("request-under-audit").expect("a registered request must resolve its slot"); + slot.record(SSEType::SseKms, Some("finance-key"), None, None); + assert_eq!(audit_tag(&scope.audit_tags(), "kmsKeyId").as_deref(), Some("finance-key")); + + drop(scope); + assert!( + crate::core::audit::kms_request_audit("request-under-audit").is_none(), + "the slot must not outlive the audit entry it belongs to" + ); +} + +#[test] +fn a_request_that_did_no_kms_work_reports_no_tags() { + let scope = crate::core::audit::KmsRequestAuditScope::register("quiet-request"); + assert!(scope.audit_tags().is_empty()); +} + +/// The canonical seven-field envelope, with `master_key_version` grafted on +/// when a wrapping version is wanted. +fn audit_test_envelope(master_key_version: Option) -> Vec { + let mut envelope = serde_json::json!({ + "key_id": "test-key-id", + "master_key_id": "master-key-id", + "key_spec": "AES_256", + "encrypted_key": [1, 2, 3, 4], + "nonce": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + "encryption_context": {}, + "created_at": "2024-01-01T00:00:00+00:00" + }); + if let Some(version) = master_key_version { + envelope + .as_object_mut() + .expect("envelope is an object") + .insert("master_key_version".to_string(), serde_json::json!(version)); + } + serde_json::to_vec(&envelope).expect("encode envelope") +} + +#[test] +fn envelope_master_key_version_reads_only_true_envelopes() { + // A versioned envelope reports the wrapping version. + assert_eq!(crate::core::audit::envelope_master_key_version(&audit_test_envelope(Some(3))), Some(3)); + // A pre-versioning envelope has no version to report. + assert_eq!(crate::core::audit::envelope_master_key_version(&audit_test_envelope(None)), None); + // Opaque backend ciphertext (Transit, AWS) is not an envelope. + assert_eq!(crate::core::audit::envelope_master_key_version(b"vault:v2:abcdefgh"), None); + // JSON that is not the envelope shape must not be probed for a version. + assert_eq!(crate::core::audit::envelope_master_key_version(br#"{"master_key_version": 9}"#), None); +} + +#[test] +fn stored_envelope_master_key_version_reads_both_metadata_families() { + let envelope = BASE64_STANDARD.encode_to_string(audit_test_envelope(Some(2))); + + // RustFS-branded stored key. + let metadata = HashMap::from([(INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), envelope.clone())]); + assert_eq!(crate::core::audit::stored_envelope_master_key_version(&metadata), Some(2)); + + // MinIO-branded stored key reaches the same answer through + // normalize_managed_metadata — the dual internal metadata key rule. + let metadata = HashMap::from([( + rustfs_utils::http::object_encryption_keys::MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), + envelope, + )]); + assert_eq!(crate::core::audit::stored_envelope_master_key_version(&metadata), Some(2)); + + assert_eq!(crate::core::audit::stored_envelope_master_key_version(&HashMap::new()), None); +} + +#[test] +fn recorded_key_versions_reach_the_audit_tags() { + let scope = crate::core::audit::KmsRequestAuditScope::register("versioned-request"); + let slot = crate::core::audit::kms_request_audit("versioned-request").expect("a registered request must resolve its slot"); + slot.record(SSEType::SseKms, Some("finance-key"), Some(3), None); + let tags = scope.audit_tags(); + assert_eq!(audit_tag(&tags, "kmsKeyVersion").as_deref(), Some("3")); + assert_eq!(audit_tag(&tags, "kmsOutcome").as_deref(), Some("success")); +} diff --git a/docs/architecture/crate-boundaries.md b/docs/architecture/crate-boundaries.md index 9d940e37b2..cdb183f7b2 100644 --- a/docs/architecture/crate-boundaries.md +++ b/docs/architecture/crate-boundaries.md @@ -30,9 +30,11 @@ 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 diff --git a/docs/architecture/global-state-inventory.md b/docs/architecture/global-state-inventory.md index e46375e15b..2c9cd47433 100644 --- a/docs/architecture/global-state-inventory.md +++ b/docs/architecture/global-state-inventory.md @@ -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` | `rustfs/src/storage/sse.rs` | DEK provider caches stay private to the SSE owner. | +| `GLOBAL_KMS_DEK_PROVIDER`, `GLOBAL_SSE_DEK_PROVIDER` | `crates/sse/src/kms/provider.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. | diff --git a/docs/architecture/kms-bulk-rekey-contract.md b/docs/architecture/kms-bulk-rekey-contract.md index 03c7dbe2a4..9753db31a9 100644 --- a/docs/architecture/kms-bulk-rekey-contract.md +++ b/docs/architecture/kms-bulk-rekey-contract.md @@ -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 `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`. +**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`. 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 `rustfs/src/storage/sse.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 `crates/sse/src/core/read.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 `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. +- **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. - **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. diff --git a/docs/architecture/minio-file-format-compat.md b/docs/architecture/minio-file-format-compat.md index 35df40aba1..1064826aea 100644 --- a/docs/architecture/minio-file-format-compat.md +++ b/docs/architecture/minio-file-format-compat.md @@ -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`, `rustfs/src/storage/sse.rs`, `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`, `crates/sse/src/core/`, `crates/sse/src/kms/`, `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 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 `rustfs-sse/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 in `rustfs/src/storage/sse.rs` 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 under `crates/sse/src/core/` 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` 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. | +| 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. | | 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 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. | +| 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. | ## Fixture Evidence diff --git a/docs/operations/kms-aws-backend-guide.md b/docs/operations/kms-aws-backend-guide.md index 3ef5b3956f..63da1aa564 100644 --- a/docs/operations/kms-aws-backend-guide.md +++ b/docs/operations/kms-aws-backend-guide.md @@ -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), `rustfs/src/storage/sse.rs` (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), `crates/sse/src/core/` (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). diff --git a/docs/operations/kms-aws-backend-guide.zh-CN.md b/docs/operations/kms-aws-backend-guide.zh-CN.md index 89365d3d75..e207cec1e7 100644 --- a/docs/operations/kms-aws-backend-guide.zh-CN.md +++ b/docs/operations/kms-aws-backend-guide.zh-CN.md @@ -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`(重试、超时与熔断)、`rustfs/src/storage/sse.rs`(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`(重试、超时与熔断)、`crates/sse/src/core/`(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)。 diff --git a/rustfs/Cargo.toml b/rustfs/Cargo.toml index 12cf8698fe..3fb978c2db 100644 --- a/rustfs/Cargo.toml +++ b/rustfs/Cargo.toml @@ -82,7 +82,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"] +rio-v2 = ["rustfs-ecstore/rio-v2", "rustfs-sse/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. @@ -285,6 +285,7 @@ rustfs-rio = { workspace = true } rustfs-s3-client = { workspace = true } rustfs-s3-types = { workspace = true } rustfs-s3-ops = { workspace = true } +rustfs-sse = { workspace = true } rustfs-security-governance = { workspace = true } rustfs-data-usage = { workspace = true } rustfs-s3select-api = { workspace = true } @@ -426,6 +427,7 @@ 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"] } rustfs-s3-types = { workspace = true, features = ["http-response"] } s3s = { git = "https://github.com/s3s-project/s3s", rev = "5761ddfe4c509fcac87e3b99fd5bd9e176b442c0", features = ["minio"] } s3s-sigv4 = { git = "https://github.com/s3s-project/s3s", rev = "5761ddfe4c509fcac87e3b99fd5bd9e176b442c0" } diff --git a/rustfs/src/app/multipart_usecase.rs b/rustfs/src/app/multipart_usecase.rs index 02adbb1579..86606c9dc0 100644 --- a/rustfs/src/app/multipart_usecase.rs +++ b/rustfs/src/app/multipart_usecase.rs @@ -60,7 +60,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, + DecryptionRequest, EncryptionKeyKind, EncryptionRequest, PrepareEncryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt, 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, diff --git a/rustfs/src/app/multipart_usecase/upload_part.rs b/rustfs/src/app/multipart_usecase/upload_part.rs index 2e7cf903a7..e3c4baa70e 100644 --- a/rustfs/src/app/multipart_usecase/upload_part.rs +++ b/rustfs/src/app/multipart_usecase/upload_part.rs @@ -378,7 +378,8 @@ impl DefaultMultipartUsecase { content_size: actual_size, principal: None, } - .validate_multipart_ssec(&fi.user_defined)?; + .validate_multipart_ssec(&fi.user_defined) + .map_err(ApiError::from)?; } let (requested_sse, requested_kms_key_id) = if has_ssec { let ssec_material = sse_decryption(DecryptionRequest { diff --git a/rustfs/src/app/multipart_usecase/upload_part_copy.rs b/rustfs/src/app/multipart_usecase/upload_part_copy.rs index dc9899d1d8..05dfa91981 100644 --- a/rustfs/src/app/multipart_usecase/upload_part_copy.rs +++ b/rustfs/src/app/multipart_usecase/upload_part_copy.rs @@ -261,7 +261,8 @@ impl DefaultMultipartUsecase { content_size: 0, principal: None, } - .validate_multipart_ssec(&mp_info.user_defined)?; + .validate_multipart_ssec(&mp_info.user_defined) + .map_err(ApiError::from)?; let src_versioned = BucketVersioningSys::prefix_enabled(&src_bucket, &src_key).await; let src_version_suspended = BucketVersioningSys::prefix_suspended(&src_bucket, &src_key).await; diff --git a/rustfs/src/app/object/mod.rs b/rustfs/src/app/object/mod.rs index bfba2bdd69..01600084ad 100644 --- a/rustfs/src/app/object/mod.rs +++ b/rustfs/src/app/object/mod.rs @@ -106,12 +106,14 @@ 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}; +use super::storage_api::object_usecase::sse::{DecryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt}; #[cfg(test)] -pub(crate) use super::storage_api::object_usecase::sse::{DecryptionRequest, SseKmsPrincipal, sse_decryption}; +pub(crate) use super::storage_api::object_usecase::sse::{ + DecryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt, sse_decryption, +}; use super::storage_api::object_usecase::sse::{ - EncryptionRequest, 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, + EncryptionMaterialExt, EncryptionRequest, 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, validate_bucket_object_lock_enabled_state, diff --git a/rustfs/src/app/owned_audit_test.rs b/rustfs/src/app/owned_audit_test.rs index a9e0e784db..d486da1c93 100644 --- a/rustfs/src/app/owned_audit_test.rs +++ b/rustfs/src/app/owned_audit_test.rs @@ -640,7 +640,7 @@ 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, sse_decryption}; + 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( diff --git a/rustfs/src/app/select_object.rs b/rustfs/src/app/select_object.rs index 95d5e3217e..22d80ab3de 100644 --- a/rustfs/src/app/select_object.rs +++ b/rustfs/src/app/select_object.rs @@ -2,7 +2,9 @@ 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, authorize_sse_kms_object_read, project_sse_read_response_headers}; +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::{ StoragePrepareSelectObjectSnapshotError, StorageSelectObjectSnapshot, get_validated_store, validate_sse_headers_for_read, validate_ssec_for_read, diff --git a/rustfs/src/app/storage_api.rs b/rustfs/src/app/storage_api.rs index 1d87078907..d577b92af2 100644 --- a/rustfs/src/app/storage_api.rs +++ b/rustfs/src/app/storage_api.rs @@ -1673,9 +1673,9 @@ pub(crate) mod sse { validate_bucket_object_lock_enabled_state, }; pub(crate) use crate::storage::storage_api::sse_consumer::{ - 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, + 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, }; } diff --git a/rustfs/src/error.rs b/rustfs/src/error.rs index 8259f1914b..7c917e8aed 100644 --- a/rustfs/src/error.rs +++ b/rustfs/src/error.rs @@ -18,6 +18,7 @@ use http::StatusCode; use rustfs_kms::KmsUnavailableError; use rustfs_lock::LockError; use rustfs_s3_types::S3ErrorCode; +use rustfs_sse::{SseError, data_plane_kms_error}; const CONTENT_SHA256_MISMATCH_CODE: &str = "XAmzContentSHA256Mismatch"; const CONTENT_SHA256_MISMATCH_MESSAGE: &str = "The provided 'x-amz-content-sha256' header does not match what was computed."; @@ -49,7 +50,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 const KMS_KEY_NOT_FOUND_ERROR_CODE: &str = "KMS.NotFoundException"; +pub use rustfs_sse::KMS_KEY_NOT_FOUND_ERROR_CODE; fn lock_resource_class(resource: Option<&str>) -> &'static str { let Some(resource) = resource else { @@ -120,77 +121,6 @@ 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 @@ -824,6 +754,17 @@ impl From for ApiError { } } +/// An SSE failure arrives already classified for the S3 data path; carry it over as is. +impl From for ApiError { + fn from(err: SseError) -> Self { + ApiError { + code: err.code, + message: err.message, + source: err.source, + } + } +} + impl From for ApiError { fn from(err: StorageError) -> Self { record_s3_lock_failure(&err); diff --git a/rustfs/src/init.rs b/rustfs/src/init.rs index fc657ca03d..356e9e6113 100644 --- a/rustfs/src/init.rs +++ b/rustfs/src/init.rs @@ -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::log_sse_kms_key_policy_mode; +use crate::storage_api::startup::sse::init_sse_startup; 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,7 +539,9 @@ pub async fn init_kms_system(config: &config::Config, store: Arc) -> st // Initialize global KMS service manager (starts in NotConfigured state) let service_manager = startup_runtime_sources::init_kms_service_manager(); - log_sse_kms_key_policy_mode(); + // Settles what SSE reads from the environment. Idempotent, so a second + // embedded server in this process reports nothing new. + init_sse_startup(); // A key referenced by any bucket's encryption configuration must never be // deleted. Register the gate before the service can start so every diff --git a/rustfs/src/storage/AGENTS.md b/rustfs/src/storage/AGENTS.md index f9d1155192..1ef54971a4 100644 --- a/rustfs/src/storage/AGENTS.md +++ b/rustfs/src/storage/AGENTS.md @@ -12,7 +12,9 @@ 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/` diff --git a/rustfs/src/storage/sse.rs b/rustfs/src/storage/sse.rs index 780038c1cd..3cef125b2c 100644 --- a/rustfs/src/storage/sse.rs +++ b/rustfs/src/storage/sse.rs @@ -12,631 +12,191 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Server-Side Encryption (SSE) utilities +//! The server's side of server-side encryption. //! -//! This module provides reusable components for handling S3 Server-Side Encryption: -//! - SSE-S3 (AES256): Server-managed encryption with S3-managed keys -//! - SSE-KMS (aws:kms): Server-managed encryption with KMS-managed keys -//! - SSE-C (AES256): Customer-provided encryption keys -//! -//! ## Architecture -//! -//! ### Unified API -//! The module provides two core functions that automatically route to the correct encryption method: -//! - `sse_encryption()` - Unified encryption entry point -//! - `sse_decryption()` - Unified decryption entry point -//! -//! ### Managed SSE (SSE-S3 / SSE-KMS) -//! - Keys are managed by the server-side KMS service -//! - Data keys are generated and encrypted by KMS -//! - Encryption metadata is stored in object metadata -//! -//! ### Customer-Provided Keys (SSE-C) -//! - Keys are provided by the client on every request -//! - Server validates key using MD5 hash -//! - Keys are NEVER stored on the server -//! -//! ## Usage Example -//! -//! ```rust,ignore -//! // Unified encryption API -//! 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, -//! }; -//! -//! if let Some(material) = sse_encryption(request).await? { -//! metadata.extend(encryption_material_to_metadata(&material)?); -//! } -//! -//! // Unified decryption API -//! 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(request).await? { -//! content_size = material.original_size.unwrap_or(actual_size); -//! } -//! ``` +//! Key resolution, metadata and validation live in the `rustfs-sse` crate, which +//! knows neither the storage engine nor IAM. This module is the seam between +//! the two: it gives that crate the server it runs in ([`RustfsSseHost`]), +//! binds its host-taking entry points to that server, and carries its results +//! across the storage-engine boundary (the read-side resolver, the write plan, +//! the multipart completion gate). use super::StorageError; use super::storage_api::ecstore_object::{ EncryptionResolutionError, EncryptionResolutionErrorKind, ObjectEncryptionResolver, ReadEncryptionMaterial, ReadEncryptionMode, ReadEncryptionRequest, }; +use super::{Error, WriteEncryption, get_bucket_sse_config}; +use crate::error::ApiError; use crate::runtime_sources::current_kms_runtime_service_manager; use crate::storage::authorization::resource_free_condition_values; use crate::storage::authorization::{AuthorizationRequest, request_context_from_req}; use crate::storage::storage_api::runtime_sources_consumer::runtime_sources; -#[cfg(feature = "rio-v2")] -use aes_gcm::aead::Payload; -use aes_gcm::{ - Aes256Gcm, Key, Nonce, - aead::{Aead, KeyInit}, -}; use async_trait::async_trait; -use base64_simd::STANDARD as BASE64_STANDARD; -#[cfg(feature = "rio-v2")] -use chacha20poly1305::ChaCha20Poly1305; -#[cfg(feature = "rio-v2")] -use hmac::{Hmac, Mac}; -use http::{HeaderMap, HeaderName, HeaderValue}; -use md5::{Digest as Md5Digest, Md5}; -use rand::Rng; -#[cfg(feature = "rio-v2")] -use rand::RngExt; -use rustfs_config::{DEFAULT_KMS_ENFORCE_SSE_KEY_POLICY, ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY}; -use rustfs_kms::{DataKey, KmsUnavailableError, is_data_key_envelope, types::ObjectEncryptionContext}; +use http::HeaderMap; +use rustfs_kms::KmsServiceManager; +use rustfs_kms::service::ObjectEncryptionService; use rustfs_policy::policy::Args; use rustfs_policy::policy::action::{Action, KmsAction}; use rustfs_s3_types::S3ErrorCode; -use rustfs_utils::{get_env_bool, get_env_opt_str}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; -#[cfg(feature = "rio-v2")] -use sha2::Sha256; -use std::collections::{BTreeSet, HashMap}; -use std::sync::{Arc, LazyLock, Mutex, RwLock, Weak}; -use tracing::{debug, error}; - -const LOG_COMPONENT_STORAGE: &str = "storage"; -const LOG_SUBSYSTEM_SSE: &str = "sse"; - -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, normalize_managed_metadata, - stored_managed_encryption_key, +use rustfs_sse::{ + BucketDefaultEncryption, BucketEncryption, DEFAULT_SSE_ALGORITHM, KMS_KEY_NOT_FOUND_ERROR_CODE, KmsKeyAuthorizer, SseError, + SseHost, normalize_encryption_metadata_case, ssec_invalid_request, }; -// The managed-SSE classifier lives in the shared encryption-keys module so the -// scanner can reuse it (backlog#1643 PR-B0); these re-exports keep the -// historical `crate::storage::sse` paths compiling. -pub use rustfs_utils::http::object_encryption_keys::SSEType; -pub(crate) use rustfs_utils::http::object_encryption_keys::contains_managed_encryption_metadata; -#[cfg(feature = "rio-v2")] -const MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM: &str = "DAREv2-HMAC-SHA256"; -#[cfg(feature = "rio-v2")] -const DARE_VERSION_20: u8 = 0x20; -#[cfg(feature = "rio-v2")] -const DARE_CIPHER_AES_256_GCM: u8 = 0x00; -#[cfg(feature = "rio-v2")] -const DARE_CIPHER_CHACHA20_POLY1305: u8 = 0x01; -#[cfg(feature = "rio-v2")] -const DARE_HEADER_SIZE: usize = 16; -#[cfg(feature = "rio-v2")] -const DARE_TAG_SIZE: usize = 16; -#[cfg(feature = "rio-v2")] -const SEALED_KEY_IV_SIZE: usize = 32; -#[cfg(feature = "rio-v2")] -const SEALED_KEY_SIZE: usize = DARE_HEADER_SIZE + 32 + DARE_TAG_SIZE; -#[cfg(feature = "rio-v2")] -const OBJECT_KEY_DERIVATION_CONTEXT: &[u8] = b"object-encryption-key generation"; +use std::borrow::Cow; +use std::collections::HashMap; +use std::sync::Arc; -fn md5_bytes(input: impl AsRef<[u8]>) -> [u8; 16] { - let mut hasher = Md5::new(); - hasher.update(input.as_ref()); - hasher.finalize().into() -} - -fn md5_base64(input: impl AsRef<[u8]>) -> String { - BASE64_STANDARD.encode_to_string(md5_bytes(input)) -} - -use super::Error; -use super::get_bucket_sse_config; -use crate::error::ApiError; -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, +#[cfg(all(test, feature = "rio-v2"))] +pub(crate) use rustfs_sse::reset_sse_dek_provider; +pub(crate) use rustfs_sse::startup::init as init_sse_startup; +#[cfg(test)] +pub(crate) use rustfs_sse::testing::{RecordingKmsKeyAuthorizer, sse_kms_object_metadata}; +pub(crate) use rustfs_sse::{ + DecryptionMaterial, DecryptionRequest, EncryptionKeyKind, EncryptionMaterial, EncryptionRequest, KmsRequestAuditScope, + ObjectDekRewrapOutcome, PrepareEncryptionRequest, SseKmsPrincipal, SseReadResponseHeaders, SsecParamsFromHeaders, + build_ssec_read_headers, contains_managed_encryption_metadata, mark_encrypted_multipart_metadata, stored_ssec_metadata, + strip_managed_encryption_metadata, }; #[cfg(test)] -use rustfs_utils::http::headers::{AMZ_SERVER_SIDE_ENCRYPTION, AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID}; -use rustfs_utils::path::path_join_buf; -use std::borrow::Cow; - -// The same header names s3s publishes. Owned so this module does not import s3s. -const X_AMZ_SERVER_SIDE_ENCRYPTION: HeaderName = HeaderName::from_static("x-amz-server-side-encryption"); -const X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID: HeaderName = - HeaderName::from_static("x-amz-server-side-encryption-aws-kms-key-id"); -const X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT: HeaderName = HeaderName::from_static("x-amz-server-side-encryption-context"); -const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM: HeaderName = - HeaderName::from_static("x-amz-server-side-encryption-customer-algorithm"); -const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5: HeaderName = - HeaderName::from_static("x-amz-server-side-encryption-customer-key-md5"); +pub(crate) use rustfs_sse::{SseDekProvider, TestAuthorizationHooks, TestSseDekProvider}; // ============================================================================ -// High-Level SSE Configuration +// The server `rustfs-sse` runs in // ============================================================================ -const DEFAULT_SSE_ALGORITHM: &str = "AES256"; +/// This server, as `rustfs-sse` sees it. +/// +/// Stateless: every capability is resolved from the running server on each +/// call, so a KMS reconfiguration or a bucket-encryption change is observed by +/// the next operation. +pub(crate) struct RustfsSseHost; -const SUPPORT_SSE_ALGORITHMS: &[&str] = &[DEFAULT_SSE_ALGORITHM]; +static HOST: RustfsSseHost = RustfsSseHost; -// check sse type -#[allow(unused)] -pub fn get_sse_type( - server_side_encryption: Option<&str>, - customer_algorithm: Option<&String>, - customer_key: Option<&String>, - customer_key_md5: Option<&String>, -) -> Option { - if customer_algorithm.is_some() && customer_key.is_some() && customer_key_md5.is_some() { - return Some(SSEType::SseC); +#[async_trait] +impl SseHost for RustfsSseHost { + async fn encryption_service(&self) -> Option> { + runtime_sources::current_encryption_service().await } - let sse = server_side_encryption?; - match sse { - AMZ_ENCRYPTION_AES => Some(SSEType::SseS3), - AMZ_ENCRYPTION_KMS => Some(SSEType::SseKms), - _ => None, + fn kms_service_manager(&self) -> Option> { + current_kms_runtime_service_manager() + } + + async fn bucket_encryption(&self, bucket: &str) -> Result, SseError> { + match get_bucket_sse_config(bucket).await { + Ok((config, _updated_at)) => Ok(Some(BucketEncryption { + default_rule: config + .rules + .first() + .and_then(|rule| rule.apply_server_side_encryption_by_default.as_ref()) + .map(|sse| BucketDefaultEncryption { + sse_algorithm: sse.sse_algorithm.as_str().to_string(), + kms_master_key_id: sse.kms_master_key_id.clone(), + }), + })), + Err(Error::ConfigNotFound) => Ok(None), + Err(err) => Err(sse_error(ApiError::from(err))), + } + } + + fn kms_key_authorizer(&self) -> &dyn KmsKeyAuthorizer { + &IamKmsKeyAuthorizer } } -/// SSE configuration resolved from request and bucket defaults -#[derive(Debug)] -pub 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, +/// Hand a storage failure this server already classified to `rustfs-sse` unchanged. +fn sse_error(error: ApiError) -> SseError { + SseError { + code: error.code, + message: error.message, + source: error.source, + } } + +struct IamKmsKeyAuthorizer; + +#[async_trait] +impl KmsKeyAuthorizer for IamKmsKeyAuthorizer { + async fn is_allowed(&self, principal: &SseKmsPrincipal, action: KmsAction, key_id: &str) -> Result { + let iam_store = runtime_sources::current_ready_iam_handle() + .map_err(|err| SseError::internal(format!("KMS key authorization requires IAM: {err:?}")))?; + + Ok(iam_store + .is_allowed(&Args { + account: principal.account(), + groups: principal.groups(), + action: Action::KmsAction(action), + // Call-site contract of `Statement::kms_key_scope_matches`: the requested key + // identifier travels in `object` with `bucket` left empty. + bucket: "", + object: key_id, + conditions: principal.conditions(), + is_owner: principal.is_owner(), + claims: principal.claims(), + deny_only: false, + }) + .await) + } +} + +// ============================================================================ +// `rustfs-sse` entry points, bound to this server +// ============================================================================ + +/// Building an [`SseKmsPrincipal`] from the request that crossed the S3 boundary. +pub(crate) trait SseKmsPrincipalExt: Sized { + /// Build a principal from an S3 request. + /// + /// 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`. + fn from_request(req: &R) -> Option; +} + +impl SseKmsPrincipalExt for SseKmsPrincipal { + fn from_request(req: &R) -> Option { + let req_info = req.req_info()?; + let cred = req_info.cred.as_ref(); + + let principal = SseKmsPrincipal::new( + cred.map(|cred| cred.access_key.clone()).unwrap_or_default(), + cred.and_then(|cred| cred.groups.clone()), + req_info.is_owner, + cred.map(|cred| cred.claims_or_empty().clone()).unwrap_or_default(), + cred.map(|cred| resource_free_condition_values(req, cred)).unwrap_or_default(), + ); + let principal = match request_context_from_req(req) { + Some(context) => principal.with_request_id(&context.request_id), + None => principal, + }; + #[cfg(test)] + let principal = principal.with_test_hooks(req.test_extensions().get::().cloned()); + Some(principal) + } +} + /// Managed SSE resolved from a bucket default encryption rule on a write path. /// -/// The single mapping shared by every writer: this resolver, and the PUT, COPY -/// and extract paths in `app::object_usecase`, which reach it through -/// `resolve_bucket_default_sse`. 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). +/// See [`rustfs_sse::bucket_default_write_sse`] for the mapping and why an +/// unknown algorithm resolves to AES256 rather than to nothing. pub(crate) fn bucket_default_write_sse(sse: &rustfs_gateway_types::persistence::PersistedEncryptionByDefault) -> String { - match sse.sse_algorithm.as_str() { - "AES256" => String::from(AMZ_ENCRYPTION_AES), - "aws:kms" => String::from(AMZ_ENCRYPTION_KMS), - _ => String::from(AMZ_ENCRYPTION_AES), - } + rustfs_sse::bucket_default_write_sse(sse.sse_algorithm.as_str()) } -/// 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 -async fn prepare_sse_configuration( - bucket: &str, - server_side_encryption: Option, - ssekms_key_id: Option, -) -> Result, ApiError> { - 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_sse_config_result = get_bucket_sse_config(bucket).await; - debug!( - component = LOG_COMPONENT_STORAGE, - subsystem = LOG_SUBSYSTEM_SSE, - event = "bucket_sse_config_lookup", - bucket = %bucket, - found = bucket_sse_config_result.is_ok(), - "Bucket SSE configuration lookup completed" - ); - - if let Ok((bucket_sse_config, _timestamp)) = bucket_sse_config_result { - let effective_sse = server_side_encryption.clone().or_else(|| { - bucket_sse_config.rules.first().and_then(|rule| { - rule.apply_server_side_encryption_by_default.as_ref().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) - }) - }) - }); - 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, || { - bucket_sse_config.rules.first().and_then(|rule| { - rule.apply_server_side_encryption_by_default - .as_ref() - .and_then(|sse| sse.kms_master_key_id.clone()) - }) - }); - - Ok(Some(SseConfiguration { - effective_sse, - effective_kms_key_id, - })) - } else if let Err(e) = bucket_sse_config_result { - match e { - Error::ConfigNotFound => { - // 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). - if let Some(sse) = server_side_encryption { - Ok(Some(SseConfiguration { - effective_sse: sse, - effective_kms_key_id: ssekms_key_id, - })) - } else { - Ok(None) - } - } - _ => Err(ApiError::from(e)), - } - } else { - Ok(None) - } -} - -fn resolve_effective_kms_key_id( - effective_sse: Option<&str>, - requested_kms_key_id: Option, - bucket_default_kms_key_id: F, -) -> Option -where - F: FnOnce() -> Option, -{ - 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) -} - -#[derive(Clone)] -pub enum SseTypeV2 { - SseS3(String), - SseKms(String, Option), - SseC(String, String, String), -} - -impl std::fmt::Debug for SseTypeV2 { - 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(..)", - }) - } -} - -impl SseTypeV2 { - #[allow(unused)] - pub fn to_metadata(&self) -> HashMap { - sse_configuration_to_metadata(self) - } -} - -pub async fn prepare_sse_configuration_v2( - bucket: &str, - server_side_encryption: Option, - customer_algorithm: Option, - customer_key: Option, - customer_key_md5: Option, - ssekms_key_id: Option, -) -> Result, ApiError> { - if let Some(customer_algorithm) = customer_algorithm - && let Some(customer_key_md5) = customer_key_md5 - { - // if create_multipart_upload request, customer_key is not provided - let customer_key = customer_key.unwrap_or_default(); - - return Ok(Some(SseTypeV2::SseC(customer_algorithm, customer_key, customer_key_md5))); - } - - let sse_config = prepare_sse_configuration(bucket, server_side_encryption, ssekms_key_id).await?; - - if let Some(sse_config) = sse_config { - return match sse_config.effective_sse.as_str() { - AMZ_ENCRYPTION_AES => Ok(Some(SseTypeV2::SseS3(sse_config.effective_sse))), - AMZ_ENCRYPTION_KMS => Ok(Some(SseTypeV2::SseKms(sse_config.effective_sse.clone(), sse_config.effective_kms_key_id))), - _ => Ok(None), - }; - } - - Ok(None) -} - -#[allow(unused)] -pub fn sse_configuration_to_metadata(sse_configuration: &SseTypeV2) -> HashMap { - let mut metadata = HashMap::new(); - match sse_configuration { - SseTypeV2::SseS3(sse) => { - metadata.insert("x-amz-server-side-encryption".to_string(), sse.as_str().to_string()); - } - SseTypeV2::SseKms(sse, kms_key_id) => { - metadata.insert("x-amz-server-side-encryption".to_string(), sse.as_str().to_string()); - if let Some(kms_key_id) = kms_key_id { - metadata.insert("x-amz-server-side-encryption-aws-kms-key-id".to_string(), kms_key_id.to_string()); - } - } - SseTypeV2::SseC(algorithm, _key, key_md5) => { - metadata.insert("x-amz-server-side-encryption".to_string(), "AES256".to_string()); - metadata.insert( - "x-amz-server-side-encryption-customer-algorithm".to_string(), - algorithm.as_str().to_string(), - ); - metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), key_md5.to_string()); - } - } - - metadata -} - -// ============================================================================ -// Core Types - Unified Encryption/Decryption API -// ============================================================================ - -/// 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, - /// KMS key ID (for SSE-KMS) - pub ssekms_key_id: Option, - /// Optional client-provided KMS context for SSE-KMS. - pub ssekms_context: Option>, - /// SSE-C algorithm (customer-provided key) - pub sse_customer_algorithm: Option, - /// SSE-C key (Base64-encoded) - pub sse_customer_key: Option, - /// SSE-C key MD5 (Base64-encoded) - pub sse_customer_key_md5: Option, - /// 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 std::fmt::Debug for DecryptionRequest<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("DecryptionRequest").finish_non_exhaustive() - } -} - -impl EncryptionRequest<'_> { - pub fn validate_complete_multipart_ssec(&self, user_defined: &HashMap) -> Result<(), ApiError> { - 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) -> Result<(), ApiError> { - 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) - } -} - -#[inline] -fn sse_invalid_argument(message: &str) -> ApiError { - ApiError { - code: S3ErrorCode::InvalidArgument, - message: message.to_string(), - source: None, - } -} - -/// SSE-C parameters extracted from headers (algorithm, key, key MD5). -pub(crate) type SsecParamsFromHeaders = (Option, Option, Option); - -/// 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(crate) fn extract_ssec_params_from_headers(headers: &HeaderMap) -> Result { - 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)) + Ok(rustfs_sse::extract_ssec_params_from_headers(headers)?) } -/// 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(crate) fn extract_server_side_encryption_from_headers(headers: &HeaderMap) -> Result, ApiError> { - 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.")), - } + Ok(rustfs_sse::extract_server_side_encryption_from_headers(headers)?) } pub(crate) fn extract_ssekms_context_from_headers(headers: &HeaderMap) -> Result>, ApiError> { - 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.") - }) + Ok(rustfs_sse::extract_ssekms_context_from_headers(headers)?) } -#[inline] pub(crate) fn validate_sse_headers_for_write( server_side_encryption: Option<&str>, ssekms_key_id: Option<&String>, @@ -646,103 +206,111 @@ pub(crate) fn validate_sse_headers_for_write( sse_customer_key_md5: Option<&String>, require_sse_customer_key: bool, ) -> Result<(), ApiError> { - 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(()) + Ok(rustfs_sse::validate_sse_headers_for_write( + server_side_encryption, + ssekms_key_id, + ssekms_context, + sse_customer_algorithm, + sse_customer_key, + sse_customer_key_md5, + require_sse_customer_key, + )?) } -#[inline] pub(crate) fn validate_sse_headers_for_read(metadata: &HashMap, headers: &HeaderMap) -> Result<(), ApiError> { - 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(()) + Ok(rustfs_sse::validate_sse_headers_for_read(metadata, headers)?) } +pub(crate) fn validate_ssec_for_read( + metadata: &HashMap, + sse_customer_key: Option<&String>, + sse_customer_key_md5: Option<&String>, +) -> Result<(), ApiError> { + Ok(rustfs_sse::validate_ssec_for_read(metadata, sse_customer_key, sse_customer_key_md5)?) +} + +pub fn encryption_material_to_metadata(material: &EncryptionMaterial) -> Result, ApiError> { + Ok(rustfs_sse::encryption_material_to_metadata(material)?) +} + +pub(crate) fn project_sse_read_response_headers( + metadata: &HashMap, + sse_customer_algorithm: Option<&String>, + sse_customer_key_md5: Option<&String>, +) -> Result { + Ok(rustfs_sse::project_sse_read_response_headers( + metadata, + sse_customer_algorithm, + sse_customer_key_md5, + )?) +} + +pub async fn authorize_sse_kms_object_read( + principal: Option<&SseKmsPrincipal>, + metadata: &HashMap, +) -> Result<(), ApiError> { + Ok(rustfs_sse::authorize_sse_kms_object_read(&HOST, principal, metadata).await?) +} + +pub async fn authorize_sse_kms_multipart_write( + principal: Option<&SseKmsPrincipal>, + metadata: &HashMap, +) -> Result<(), ApiError> { + Ok(rustfs_sse::authorize_sse_kms_multipart_write(&HOST, principal, metadata).await?) +} + +pub async fn sse_encryption(request: EncryptionRequest<'_>) -> Result, ApiError> { + Ok(rustfs_sse::sse_encryption(&HOST, request).await?) +} + +pub async fn sse_prepare_encryption(request: PrepareEncryptionRequest<'_>) -> Result, ApiError> { + Ok(rustfs_sse::sse_prepare_encryption(&HOST, request).await?) +} + +pub async fn sse_decryption(request: DecryptionRequest<'_>) -> Result, ApiError> { + Ok(rustfs_sse::sse_decryption(&HOST, request).await?) +} + +pub async fn classify_sse_read_response(request: DecryptionRequest<'_>) -> Result, ApiError> { + Ok(rustfs_sse::classify_sse_read_response(&HOST, request).await?) +} + +pub(crate) async fn rewrap_object_encryption_metadata( + bucket: &str, + key: &str, + metadata: &HashMap, +) -> Result { + Ok(rustfs_sse::rewrap_object_encryption_metadata(&HOST, bucket, key, metadata).await?) +} + +// ============================================================================ +// Storage-engine boundary: write plan +// ============================================================================ + +/// Turning resolved encryption material into the write plan the object layer applies. +pub(crate) trait EncryptionMaterialExt { + fn write_encryption(&self, multipart_part_number: Option) -> WriteEncryption; +} + +impl EncryptionMaterialExt for EncryptionMaterial { + fn write_encryption(&self, multipart_part_number: Option) -> WriteEncryption { + match (self.key_kind, multipart_part_number) { + (EncryptionKeyKind::Object, Some(part_number)) => { + WriteEncryption::multipart_object_key(self.key_bytes, part_number as u32) + } + (EncryptionKeyKind::Object, None) => WriteEncryption::singlepart_object_key(self.key_bytes), + (EncryptionKeyKind::Direct, Some(part_number)) => { + WriteEncryption::multipart(self.key_bytes, self.base_nonce, part_number) + } + (EncryptionKeyKind::Direct, None) => WriteEncryption::singlepart(self.key_bytes, self.base_nonce), + } + } +} + +// ============================================================================ +// Storage-engine boundary: read errors +// ============================================================================ + pub(crate) fn map_get_object_reader_error(err: StorageError) -> ApiError { // GET/HEAD object-read contract: these failures mean "this object is not // readable right now" (S3 `SlowDownRead`), not a write admission reject. @@ -760,7 +328,7 @@ pub(crate) fn map_get_object_reader_error(err: StorageError) -> ApiError { EncryptionResolutionErrorKind::ServiceUnavailable => S3ErrorCode::ServiceUnavailable, // Same code the write path returns for this key; `From` // attaches the 400 that s3s cannot derive for a custom code. - EncryptionResolutionErrorKind::KeyNotFound => S3ErrorCode::Custom(crate::error::KMS_KEY_NOT_FOUND_ERROR_CODE.into()), + EncryptionResolutionErrorKind::KeyNotFound => S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()), EncryptionResolutionErrorKind::AccessDenied => S3ErrorCode::AccessDenied, EncryptionResolutionErrorKind::NotImplemented => S3ErrorCode::NotImplemented, // A permanent property of the stored object, not a transient server @@ -818,387 +386,143 @@ fn map_ssec_get_object_reader_error_message(err: &StorageError) -> Option { - /// Bucket name - pub bucket: &'a str, - /// Object key - pub key: &'a str, - /// Object metadata containing encryption headers - pub metadata: &'a HashMap, - /// 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>, -} - -/// 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, - - #[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>, - /// SSE-C key MD5 if customer-managed encryption is in use. - pub customer_key_md5: Option, - /// Original plaintext size when it should be persisted alongside metadata. - pub original_size: Option, - /// 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>, - /// 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, -} - -/// 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, - #[allow(unused)] - pub algorithm: String, - pub customer_key_md5: Option, // 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, -} - -// ============================================================================ -// Per-key KMS authorization (SSE-KMS data path) -// ============================================================================ - -/// 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 { - account: String, - groups: Option>, - is_owner: bool, - claims: HashMap, - conditions: HashMap>, - /// 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. - request_audit: Option>, - /// Test-only decision overrides. Carried per principal rather than in a global slot so - /// concurrent tests cannot observe each other's injection. - #[cfg(test)] - test_hooks: Option, -} - -impl SseKmsPrincipal { - /// Build a principal from an S3 request. - /// - /// 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(crate) fn from_request(req: &R) -> Option { - let req_info = req.req_info()?; - let cred = req_info.cred.as_ref(); - - Some(Self { - account: cred.map(|cred| cred.access_key.clone()).unwrap_or_default(), - groups: cred.and_then(|cred| cred.groups.clone()), - is_owner: req_info.is_owner, - claims: cred.map(|cred| cred.claims_or_empty().clone()).unwrap_or_default(), - conditions: cred.map(|cred| resource_free_condition_values(req, cred)).unwrap_or_default(), - request_audit: request_context_from_req(req).and_then(|context| kms_request_audit(&context.request_id)), - #[cfg(test)] - test_hooks: req.test_extensions().get::().cloned(), - }) - } - - #[cfg(test)] - fn for_test(account: &str, enforced: bool, authorizer: Arc) -> 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)] - fn with_request_audit(mut self, audit: Arc) -> Self { - self.request_audit = Some(audit); - self - } -} - -#[cfg(test)] -#[derive(Clone)] -pub(crate) struct TestAuthorizationHooks { - pub(crate) enforced: bool, - pub(crate) authorizer: Arc, -} - -#[cfg(test)] -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() - } -} - -/// 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(crate) trait KmsKeyAuthorizer: Send + Sync { - async fn is_allowed(&self, principal: &SseKmsPrincipal, action: KmsAction, key_id: &str) -> Result; -} - -struct IamKmsKeyAuthorizer; - -#[async_trait] -impl KmsKeyAuthorizer for IamKmsKeyAuthorizer { - async fn is_allowed(&self, principal: &SseKmsPrincipal, action: KmsAction, key_id: &str) -> Result { - let iam_store = runtime_sources::current_ready_iam_handle() - .map_err(|err| ApiError::from(StorageError::other(format!("KMS key authorization requires IAM: {err:?}"))))?; - - Ok(iam_store - .is_allowed(&Args { - account: &principal.account, - groups: &principal.groups, - action: Action::KmsAction(action), - // Call-site contract of `Statement::kms_key_scope_matches`: the requested key - // identifier travels in `object` with `bucket` left empty. - bucket: "", - object: key_id, - conditions: &principal.conditions, - is_owner: principal.is_owner, - claims: &principal.claims, - deny_only: false, - }) - .await) - } -} - -fn kms_key_authorizer(principal: &SseKmsPrincipal) -> Arc { - #[cfg(test)] - if let Some(hooks) = principal.test_hooks.as_ref() { - return hooks.authorizer.clone(); - } - #[cfg(not(test))] - let _ = principal; - - static DEFAULT: LazyLock> = LazyLock::new(|| Arc::new(IamKmsKeyAuthorizer)); - DEFAULT.clone() -} - -/// Whether per-key KMS authorization is enforced on the SSE-KMS data path. -fn sse_kms_key_policy_enforced(principal: Option<&SseKmsPrincipal>) -> bool { - #[cfg(test)] - if let Some(hooks) = principal.and_then(|candidate| candidate.test_hooks.as_ref()) { - return hooks.enforced; - } - #[cfg(not(test))] - let _ = principal; - - static ENFORCED: LazyLock = - LazyLock::new(|| get_env_bool(ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY, DEFAULT_KMS_ENFORCE_SSE_KEY_POLICY)); - *ENFORCED -} - -/// Report the configured SSE-KMS authorization mode once, at startup. -/// -/// 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. -pub(crate) fn log_sse_kms_key_policy_mode() { - if sse_kms_key_policy_enforced(None) { - tracing::info!( - component = LOG_COMPONENT_STORAGE, - subsystem = LOG_SUBSYSTEM_SSE, - event = "sse_kms_key_policy_mode", - enforced = true, - "SSE-KMS requests are authorized against the resolved KMS key (kms:GenerateDataKey / kms:Decrypt)" - ); - return; - } - - tracing::warn!( - component = LOG_COMPONENT_STORAGE, - subsystem = LOG_SUBSYSTEM_SSE, - event = "sse_kms_key_policy_mode", - 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." - ); -} - -/// 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. -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. -async fn authorize_sse_kms_key( - principal: Option<&SseKmsPrincipal>, - sse_type: SSEType, - action: KmsAction, - key_id: &str, -) -> Result<(), ApiError> { - let Some(principal) = kms_authorization_subject(sse_kms_key_policy_enforced(principal), principal, sse_type) else { - return Ok(()); +/// Carry the S3-level classification of a decryption failure through the +/// ecstore boundary. Every code produced by `rustfs_sse::data_plane_kms_error` +/// needs a kind here, otherwise the read path reports it as an internal fault +/// even though the write path already reports the same KMS error to the client. +fn map_encryption_resolution_error(error: impl Into) -> EncryptionResolutionError { + let error = error.into(); + let kind = match &error.code { + S3ErrorCode::InvalidArgument | S3ErrorCode::InvalidRequest => EncryptionResolutionErrorKind::InvalidRequest, + S3ErrorCode::ServiceUnavailable => EncryptionResolutionErrorKind::ServiceUnavailable, + S3ErrorCode::Custom(code) if &**code == KMS_KEY_NOT_FOUND_ERROR_CODE => EncryptionResolutionErrorKind::KeyNotFound, + S3ErrorCode::AccessDenied => EncryptionResolutionErrorKind::AccessDenied, + S3ErrorCode::NotImplemented => EncryptionResolutionErrorKind::NotImplemented, + _ => EncryptionResolutionErrorKind::DecryptionFailed, }; + EncryptionResolutionError::new(kind, error.message) +} - if kms_key_authorizer(principal).is_allowed(principal, action, key_id).await? { - return Ok(()); - } +/// Canonical-case encryption metadata, or the resolution error for conflicting spellings. +fn normalize_metadata_for_resolution( + metadata: &HashMap, +) -> Result>, EncryptionResolutionError> { + normalize_encryption_metadata_case(metadata) + .map_err(|conflict| EncryptionResolutionError::new(EncryptionResolutionErrorKind::InvalidMetadata, conflict.to_string())) +} - 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" - ); +// ============================================================================ +// Storage-engine boundary: read-side resolver +// ============================================================================ - // 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." - ); - }); - } +pub(crate) struct SseObjectEncryptionResolver; - Err(ApiError { - code: S3ErrorCode::AccessDenied, - message: "Access Denied".to_string(), - source: None, +/// Checks metadata and key access before a conditional read returns without a body. +pub(crate) async fn validate_conditional_read( + bucket: &str, + object: &str, + metadata: &HashMap, + headers: &HeaderMap, + principal: Option<&SseKmsPrincipal>, +) -> Result<(), ApiError> { + let metadata = normalize_metadata_for_resolution(metadata) + .map_err(|error| map_get_object_reader_error(StorageError::Io(std::io::Error::other(error))))?; + validate_sse_headers_for_read(&metadata, headers)?; + let (_, customer_key, customer_key_md5) = extract_ssec_params_from_headers(headers)?; + classify_sse_read_response(DecryptionRequest { + bucket, + key: object, + metadata: &metadata, + sse_customer_key: customer_key.as_ref(), + sse_customer_key_md5: customer_key_md5.as_ref(), + principal, }) + .await?; + SseObjectEncryptionResolver + .resolve_read_material(ReadEncryptionRequest { + bucket, + object, + metadata: &metadata, + headers, + }) + .await + .map_err(|error| map_get_object_reader_error(StorageError::Io(std::io::Error::other(error))))?; + Ok(()) } -/// 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( - principal: Option<&SseKmsPrincipal>, - metadata: &HashMap, -) -> Result<(), ApiError> { - let Some((sse_type, key_id)) = stored_managed_encryption_key(metadata) else { - return Ok(()); - }; +#[async_trait] +impl ObjectEncryptionResolver for SseObjectEncryptionResolver { + async fn resolve_read_material( + &self, + request: ReadEncryptionRequest<'_>, + ) -> Result, EncryptionResolutionError> { + let metadata = normalize_metadata_for_resolution(request.metadata)?; + let (customer_algorithm, customer_key, customer_key_md5) = + extract_ssec_params_from_headers(request.headers).map_err(map_encryption_resolution_error)?; + if let Some(stored_algorithm) = metadata.get("x-amz-server-side-encryption-customer-algorithm") { + let request_algorithm = customer_algorithm.as_ref().ok_or_else(|| { + map_encryption_resolution_error(ssec_invalid_request( + "The object was stored using a form of Server Side Encryption. \ + The correct parameters must be provided to retrieve the object.", + )) + })?; + if stored_algorithm != request_algorithm.as_str() { + return Err(map_encryption_resolution_error(ssec_invalid_request( + "The provided encryption parameters did not match the ones used originally to encrypt the object.", + ))); + } + } + let material = sse_decryption(DecryptionRequest { + bucket: request.bucket, + key: request.object, + metadata: &metadata, + sse_customer_key: customer_key.as_ref(), + sse_customer_key_md5: customer_key_md5.as_ref(), + // The object layer resolves read material for internal readers too (replication, + // lifecycle transition, heal, scanner) and carries no request identity, so this hook + // never authorizes. Callers that cross the S3 boundary are authorized by the S3 layer + // before their bytes are served. + principal: None, + }) + .await + .map_err(map_encryption_resolution_error)?; + let Some(material) = material else { + // Fail closed with a diagnosis instead of a bare `None`: the read + // plan classifies the object as encrypted from these same markers + // and would refuse to serve it anyway, but its generic error names + // neither the object's format nor what the operator can do about it. + if metadata + .keys() + .any(|key| rustfs_utils::http::is_object_encryption_marker(key)) + { + #[cfg(not(feature = "rio-v2"))] + let message = "object is stored encrypted, but its decryption material could not be resolved: the \ + encryption metadata is incomplete, or it is in the MinIO-compatible sealed format, \ + which this server build has no read path for (reading it requires a build with the \ + `rio-v2` feature)"; + #[cfg(feature = "rio-v2")] + let message = "object is stored encrypted, but its decryption material could not be resolved: the \ + encryption metadata is incomplete or in an unrecognized sealed format"; + return Err(EncryptionResolutionError::new(EncryptionResolutionErrorKind::InvalidMetadata, message)); + } + return Ok(None); + }; - let result = authorize_sse_kms_key(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), - ); + Ok(Some(ReadEncryptionMaterial { + key_bytes: material.key_bytes, + mode: match material.key_kind { + EncryptionKeyKind::Direct => ReadEncryptionMode::Direct { + base_nonce: material.base_nonce, + }, + EncryptionKeyKind::Object => ReadEncryptionMode::Object, + }, + })) } - - 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( - principal: Option<&SseKmsPrincipal>, - metadata: &HashMap, -) -> Result<(), ApiError> { - let Some((sse_type, key_id)) = stored_managed_encryption_key(metadata) else { - return Ok(()); - }; - let result = authorize_sse_kms_key(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 -} +// ============================================================================ +// Storage-engine boundary: multipart completion gate +// ============================================================================ /// Capture the request's encryption gate without exposing customer keys in /// ObjectOptions Debug output. Storage applies it to the source selected under @@ -1259,3443 +583,95 @@ impl super::storage_api::contract::multipart::MultipartCompletionAuthorization f } } -// ============================================================================ -// Data-plane KMS audit attachment (SSE-S3 / SSE-KMS) -// ============================================================================ - -/// 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, - key_versions: BTreeSet, - /// 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 by the [`OperationHelper`](crate::storage::helper::OperationHelper) that -/// owns the request's audit entry. -#[derive(Debug, Default)] -pub(crate) struct KmsRequestAudit(Mutex); - -impl KmsRequestAudit { - fn record(&self, sse_type: SSEType, key_id: Option<&str>, key_version: Option, 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(crate) 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>) -> Value { - let joined = values.map(|value| value.as_ref().to_string()).collect::>(); - 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>>> = LazyLock::new(|| Mutex::new(HashMap::new())); - -/// Registration of one request's KMS audit slot, dropped with the request's -/// audit entry. -pub(crate) struct KmsRequestAuditScope { - request_id: String, - audit: Arc, -} - -impl KmsRequestAuditScope { - /// Open a slot for `request_id`, so managed-SSE operations served under it can - /// be summarised onto its audit entry. - pub(crate) 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(crate) 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. -fn kms_request_audit(request_id: &str) -> Option> { - 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. -fn kms_data_plane_error_class(error: &ApiError) -> &'static str { - if let Some(failure) = error - .source - .as_ref() - .and_then(|source| source.downcast_ref::()) - { - 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)] -struct KmsDataPlaneFailure { - class: &'static str, - source: Option>, -} - -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. -fn record_managed_kms_outcome( - principal: Option<&SseKmsPrincipal>, - sse_type: SSEType, - key_id: Option<&str>, - key_version: impl FnOnce() -> Option, - result: Result<(), &ApiError>, -) { - 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. -fn envelope_master_key_version(envelope_bytes: &[u8]) -> Option { - if !is_data_key_envelope(envelope_bytes) { - return None; - } - u32::try_from( - serde_json::from_slice::(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. -fn stored_envelope_master_key_version(metadata: &HashMap) -> Option { - // 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) -} - -pub(crate) struct SseObjectEncryptionResolver; - -/// Checks metadata and key access before a conditional read returns without a body. -pub(crate) async fn validate_conditional_read( - bucket: &str, - object: &str, - metadata: &HashMap, - headers: &HeaderMap, - principal: Option<&SseKmsPrincipal>, -) -> Result<(), ApiError> { - let metadata = normalize_encryption_metadata_case(metadata) - .map_err(|error| map_get_object_reader_error(StorageError::Io(std::io::Error::other(error))))?; - validate_sse_headers_for_read(&metadata, headers)?; - let (_, customer_key, customer_key_md5) = extract_ssec_params_from_headers(headers)?; - classify_sse_read_response(DecryptionRequest { - bucket, - key: object, - metadata: &metadata, - sse_customer_key: customer_key.as_ref(), - sse_customer_key_md5: customer_key_md5.as_ref(), - principal, - }) - .await?; - SseObjectEncryptionResolver - .resolve_read_material(ReadEncryptionRequest { - bucket, - object, - metadata: &metadata, - headers, - }) - .await - .map_err(|error| map_get_object_reader_error(StorageError::Io(std::io::Error::other(error))))?; - Ok(()) -} - -#[async_trait] -impl ObjectEncryptionResolver for SseObjectEncryptionResolver { - async fn resolve_read_material( - &self, - request: ReadEncryptionRequest<'_>, - ) -> Result, EncryptionResolutionError> { - let metadata = normalize_encryption_metadata_case(request.metadata)?; - let (customer_algorithm, customer_key, customer_key_md5) = - extract_ssec_params_from_headers(request.headers).map_err(map_encryption_resolution_error)?; - if let Some(stored_algorithm) = metadata.get("x-amz-server-side-encryption-customer-algorithm") { - let request_algorithm = customer_algorithm.as_ref().ok_or_else(|| { - map_encryption_resolution_error(ssec_invalid_request( - "The object was stored using a form of Server Side Encryption. \ - The correct parameters must be provided to retrieve the object.", - )) - })?; - if stored_algorithm != request_algorithm.as_str() { - return Err(map_encryption_resolution_error(ssec_invalid_request( - "The provided encryption parameters did not match the ones used originally to encrypt the object.", - ))); - } - } - let material = sse_decryption(DecryptionRequest { - bucket: request.bucket, - key: request.object, - metadata: &metadata, - sse_customer_key: customer_key.as_ref(), - sse_customer_key_md5: customer_key_md5.as_ref(), - // The object layer resolves read material for internal readers too (replication, - // lifecycle transition, heal, scanner) and carries no request identity, so this hook - // never authorizes. Callers that cross the S3 boundary are authorized by the S3 layer - // before their bytes are served. - principal: None, - }) - .await - .map_err(map_encryption_resolution_error)?; - - let Some(material) = material else { - // Fail closed with a diagnosis instead of a bare `None`: the read - // plan classifies the object as encrypted from these same markers - // and would refuse to serve it anyway, but its generic error names - // neither the object's format nor what the operator can do about it. - if metadata - .keys() - .any(|key| rustfs_utils::http::is_object_encryption_marker(key)) - { - #[cfg(not(feature = "rio-v2"))] - let message = "object is stored encrypted, but its decryption material could not be resolved: the \ - encryption metadata is incomplete, or it is in the MinIO-compatible sealed format, \ - which this server build has no read path for (reading it requires a build with the \ - `rio-v2` feature)"; - #[cfg(feature = "rio-v2")] - let message = "object is stored encrypted, but its decryption material could not be resolved: the \ - encryption metadata is incomplete or in an unrecognized sealed format"; - return Err(EncryptionResolutionError::new(EncryptionResolutionErrorKind::InvalidMetadata, message)); - } - return Ok(None); - }; - - Ok(Some(ReadEncryptionMaterial { - key_bytes: material.key_bytes, - mode: match material.key_kind { - EncryptionKeyKind::Direct => ReadEncryptionMode::Direct { - base_nonce: material.base_nonce, - }, - EncryptionKeyKind::Object => ReadEncryptionMode::Object, - }, - })) - } -} - -fn normalize_encryption_metadata_case( - metadata: &HashMap, -) -> Result>, EncryptionResolutionError> { - 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(EncryptionResolutionError::new( - EncryptionResolutionErrorKind::InvalidMetadata, - format!("conflicting object encryption metadata for {canonical}"), - )); - } - if !normalized.contains_key(*canonical) { - normalized.insert((*canonical).to_string(), value.clone()); - } - } - Ok(Cow::Owned(normalized)) -} - -/// Carry the S3-level classification of a decryption failure through the -/// ecstore boundary. Every code produced by `data_plane_kms_error` needs a -/// kind here, otherwise the read path reports it as an internal fault even -/// though the write path already reports the same KMS error to the client. -fn map_encryption_resolution_error(error: ApiError) -> EncryptionResolutionError { - let kind = match &error.code { - S3ErrorCode::InvalidArgument | S3ErrorCode::InvalidRequest => EncryptionResolutionErrorKind::InvalidRequest, - S3ErrorCode::ServiceUnavailable => EncryptionResolutionErrorKind::ServiceUnavailable, - S3ErrorCode::Custom(code) if &**code == crate::error::KMS_KEY_NOT_FOUND_ERROR_CODE => { - EncryptionResolutionErrorKind::KeyNotFound - } - S3ErrorCode::AccessDenied => EncryptionResolutionErrorKind::AccessDenied, - S3ErrorCode::NotImplemented => EncryptionResolutionErrorKind::NotImplemented, - _ => EncryptionResolutionErrorKind::DecryptionFailed, - }; - EncryptionResolutionError::new(kind, error.message) -} - -#[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 { - matches!(self.sse_type, SSEType::SseKms) - .then(|| self.kms_key_id.clone()) - .flatten() - } - - pub fn write_encryption(&self, multipart_part_number: Option) -> super::WriteEncryption { - match (self.key_kind, multipart_part_number) { - (EncryptionKeyKind::Object, Some(part_number)) => { - super::WriteEncryption::multipart_object_key(self.key_bytes, part_number as u32) - } - (EncryptionKeyKind::Object, None) => super::WriteEncryption::singlepart_object_key(self.key_bytes), - (EncryptionKeyKind::Direct, Some(part_number)) => { - super::WriteEncryption::multipart(self.key_bytes, self.base_nonce, part_number) - } - (EncryptionKeyKind::Direct, None) => super::WriteEncryption::singlepart(self.key_bytes, self.base_nonce), - } - } -} - -#[cfg(feature = "rio-v2")] -type HmacSha256 = Hmac; - -#[cfg(feature = "rio-v2")] -fn managed_sse_domain(sse_type: SSEType) -> &'static str { - match sse_type { - SSEType::SseS3 => "SSE-S3", - SSEType::SseKms => "SSE-KMS", - SSEType::SseC => "SSE-C", - } -} - -/// The public `x-amz-server-side-encryption` value a managed scheme reports. -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, - } -} - -fn canonical_kms_bucket_path(bucket: &str, key: &str) -> String { - path_join_buf(&[bucket, key]) -} - -fn build_kms_request_context( - bucket: &str, - key: &str, - provided_context: Option<&HashMap>, -) -> HashMap { - let mut context = provided_context.cloned().unwrap_or_default(); - context - .entry(bucket.to_string()) - .or_insert_with(|| canonical_kms_bucket_path(bucket, key)); - context -} - -/// Rejects a client encryption context that would replace the location binding. -/// -/// [`build_kms_request_context`] binds the data key to `{bucket: bucket/key}` -/// with `or_insert`, 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. -fn reject_kms_context_location_override(bucket: &str, ssekms_context: Option<&HashMap>) -> Result<(), ApiError> { - 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(()) -} - -fn build_object_encryption_context( - bucket: &str, - key: &str, - provided_context: Option<&HashMap>, -) -> 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 -} - -fn encode_minio_kms_context(context: &HashMap) -> Result { - let encoded = serde_json::to_vec(context) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to serialize KMS context: {e}"))))?; - Ok(BASE64_STANDARD.encode_to_string(encoded)) -} - -fn decode_minio_kms_context(metadata: &HashMap) -> Result>, ApiError> { - 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| ApiError::from(StorageError::other(format!("Failed to decode MinIO KMS context: {e}"))))?; - serde_json::from_slice(&decoded) - .map(Some) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to parse MinIO KMS context: {e}")))) -} - -#[cfg(feature = "rio-v2")] -fn is_supported_sealed_object_key_cipher(cipher: u8) -> bool { - matches!(cipher, DARE_CIPHER_AES_256_GCM | DARE_CIPHER_CHACHA20_POLY1305) -} - -#[cfg(feature = "rio-v2")] -fn decrypt_sealed_object_key_payload(sealing_key: [u8; 32], header: &[u8], sealed_key: &[u8]) -> Result, ApiError> { - 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| ApiError::from(StorageError::other(format!("Invalid AES-GCM sealing key: {err}"))))?; - let nonce = Nonce::try_from(nonce) - .map_err(|_| ApiError::from(StorageError::other("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| ApiError::from(StorageError::other(format!("Invalid ChaCha20-Poly1305 sealing key: {err}"))))?; - let nonce = chacha20poly1305::Nonce::try_from(nonce) - .map_err(|_| ApiError::from(StorageError::other("Invalid sealed object-key package nonce")))?; - cipher.decrypt(&nonce, Payload { msg: ciphertext, aad }) - } - _ => return Err(ApiError::from(StorageError::other("Unsupported sealed object-key DARE header"))), - } - .map_err(|err| ApiError::from(StorageError::other(format!("Failed to unseal object key: {err}")))) -} - -#[cfg(feature = "rio-v2")] -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}") - } -} - -#[cfg(feature = "rio-v2")] -fn derive_object_key(external_key: [u8; 32]) -> Result<[u8; 32], ApiError> { - let mut random = [0u8; 32]; - rand::rng().fill(&mut random); - - let mut mac = HmacSha256::new_from_slice(&external_key) - .map_err(|err| ApiError::from(StorageError::other(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) -} - -#[cfg(feature = "rio-v2")] -fn derive_sealing_key( - external_key: [u8; 32], - iv: [u8; SEALED_KEY_IV_SIZE], - domain: &str, - bucket: &str, - object: &str, -) -> Result<[u8; 32], ApiError> { - let mut mac = HmacSha256::new_from_slice(&external_key) - .map_err(|err| ApiError::from(StorageError::other(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) -} - -#[cfg(feature = "rio-v2")] -fn seal_object_key( - object_key: [u8; 32], - external_key: [u8; 32], - sse_type: SSEType, - bucket: &str, - object: &str, -) -> Result { - 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| ApiError::from(StorageError::other(format!("Invalid sealing key: {err}"))))?; - let nonce = Nonce::try_from(stream_nonce.as_slice()) - .map_err(|_| ApiError::from(StorageError::other("Invalid sealed object-key stream nonce")))?; - let ciphertext = cipher - .encrypt( - &nonce, - aes_gcm::aead::Payload { - msg: &object_key, - aad: &header[..4], - }, - ) - .map_err(|err| ApiError::from(StorageError::other(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 }) -} - -#[cfg(feature = "rio-v2")] -fn unseal_object_key( - sealed: &ManagedSealedKey, - external_key: [u8; 32], - sse_type: SSEType, - bucket: &str, - object: &str, -) -> Result<[u8; 32], ApiError> { - let header = &sealed.sealed_key[..DARE_HEADER_SIZE]; - if header[0] != DARE_VERSION_20 || !is_supported_sealed_object_key_cipher(header[1]) { - return Err(ApiError::from(StorageError::other("Unsupported sealed object-key DARE header"))); - } - if u16::from_le_bytes([header[2], header[3]]) != 31 || header[4] & 0x80 == 0 { - return Err(ApiError::from(StorageError::other("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(|_| ApiError::from(StorageError::other("Sealed object key must decrypt to 32 bytes")))?; - Ok(object_key) -} - -#[cfg(feature = "rio-v2")] -fn try_decode_minio_sealed_key(bytes: &str) -> Result, ApiError> { - let decoded = BASE64_STANDARD - .decode_to_vec(bytes) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to decode sealed object key: {e}"))))?; - match decoded.as_slice().try_into() { - Ok(sealed_key) => Ok(Some(sealed_key)), - Err(_) => Ok(None), - } -} - -#[cfg(feature = "rio-v2")] -fn try_decode_minio_sealing_iv(bytes: &str) -> Result, ApiError> { - let decoded = BASE64_STANDARD - .decode_to_vec(bytes) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to decode sealing IV: {e}"))))?; - match decoded.as_slice().try_into() { - Ok(iv) => Ok(Some(iv)), - Err(_) => Ok(None), - } -} - -pub(crate) 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 -} - -pub fn encryption_material_to_metadata(material: &EncryptionMaterial) -> Result, ApiError> { - let mut metadata = HashMap::new(); - - match material.sse_type { - SSEType::SseC => { - 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()); - } - - // Persist the random base nonce for the SSE-C Direct scheme (default, - // non-`rio-v2` build) so decrypt can read it back instead of recomputing a - // deterministic value. Written under both the RustFS and MinIO keys per repo - // convention. This covers single-PUT persistence and multipart-session - // persistence (CreateMultipartUpload builds session metadata here). Under - // `rio-v2` the SSE-C path uses `EncryptionKeyKind::Object` and the sealed-key - // block below, so this branch is not taken. - if material.key_kind == EncryptionKeyKind::Direct { - metadata.insert( - INTERNAL_ENCRYPTION_IV_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(material.base_nonce), - ); - metadata.insert( - MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(material.base_nonce), - ); - } - - #[cfg(feature = "rio-v2")] - if let Some(sealed) = &material.managed_sealed_key { - 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), - ); - } - } - SSEType::SseS3 | SSEType::SseKms => { - let encrypted_data_key = material - .encrypted_data_key - .as_deref() - .ok_or_else(|| ApiError::from(StorageError::other("managed SSE materials must carry an encrypted data key")))?; - 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); - } - } - - if material.key_kind == EncryptionKeyKind::Direct { - metadata.insert( - INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(encrypted_data_key), - ); - metadata.insert( - INTERNAL_ENCRYPTION_IV_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(material.base_nonce), - ); - metadata.insert(INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), material.algorithm.as_str().to_string()); - } - - #[cfg(feature = "rio-v2")] - if let Some(sealed) = &material.managed_sealed_key { - 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(), - ); - 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()); - } - 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(), - BASE64_STANDARD.encode_to_string(encrypted_data_key), - ); - } else if cfg!(feature = "rio-v2") { - metadata.insert( - MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(material.base_nonce), - ); - 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_key = BASE64_STANDARD.encode_to_string(encrypted_data_key); - match material.sse_type { - SSEType::SseS3 => { - metadata.insert(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(), encoded_key); - } - SSEType::SseKms => { - metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), encoded_key.clone()); - metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), encoded_key); - } - SSEType::SseC => {} - } - } - } - } - - Ok(metadata) -} - -// ============================================================================ -// Core API - Unified Encryption/Decryption Entry Points -// ============================================================================ - -/// **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(request).await? { -/// reader = material.wrap_reader(reader); -/// metadata.extend(material.metadata); -/// } -/// ``` -pub async fn sse_encryption(request: EncryptionRequest<'_>) -> Result, ApiError> { - validate_sse_headers_for_write( - request.server_side_encryption.as_deref(), - request.ssekms_key_id.as_ref(), - request.ssekms_context.as_ref(), - request.sse_customer_algorithm.as_ref(), - request.sse_customer_key.as_ref(), - request.sse_customer_key_md5.as_ref(), - true, - )?; - - // Priority 1: SSE-C (customer-provided key) - if let (Some(algorithm), Some(key), Some(key_md5)) = - (request.sse_customer_algorithm, request.sse_customer_key, request.sse_customer_key_md5) - { - return apply_ssec_encryption_material(request.bucket, request.key, algorithm, key, key_md5, request.content_size) - .await - .map(Some); - } - - // Priority 2: Managed SSE (SSE-S3 or SSE-KMS) - let sse_config = prepare_sse_configuration(request.bucket, request.server_side_encryption, request.ssekms_key_id).await?; - - if let Some(sse_config) = sse_config - && is_managed_sse(&sse_config.effective_sse) - { - return apply_managed_encryption_material( - request.bucket, - request.key, - sse_config.effective_sse, - sse_config.effective_kms_key_id, - request.ssekms_context, - request.content_size, - request.principal, - ) - .await - .map(Some); - } - - // No encryption requested - Ok(None) -} - -/// **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, - /// KMS key ID (for SSE-KMS) - pub ssekms_key_id: Option, - /// Optional client-provided KMS context for SSE-KMS. - pub ssekms_context: Option>, - /// SSE-C algorithm (customer-provided key) - pub sse_customer_algorithm: Option, - /// SSE-C key (Base64-encoded) - pub sse_customer_key: Option, - /// SSE-C key MD5 (Base64-encoded) - pub sse_customer_key_md5: Option, - /// 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(request: PrepareEncryptionRequest<'_>) -> Result, ApiError> { - validate_sse_headers_for_write( - request.server_side_encryption.as_deref(), - request.ssekms_key_id.as_ref(), - request.ssekms_context.as_ref(), - request.sse_customer_algorithm.as_ref(), - request.sse_customer_key.as_ref(), - request.sse_customer_key_md5.as_ref(), - true, - )?; - - let sse_type = prepare_sse_configuration_v2( - request.bucket, - request.server_side_encryption, - request.sse_customer_algorithm, - request.sse_customer_key.clone(), - request.sse_customer_key_md5, - request.ssekms_key_id, - ) - .await?; - - // apply encryption material - let material = match sse_type { - Some(SseTypeV2::SseS3(sse)) => { - apply_managed_encryption_material( - request.bucket, - request.key, - sse, - None, - request.ssekms_context, - 0, - request.principal, - ) - .await? - } - Some(SseTypeV2::SseKms(sse, kms_key_id)) => { - apply_managed_encryption_material( - request.bucket, - request.key, - sse, - kms_key_id, - request.ssekms_context, - 0, - request.principal, - ) - .await? - } - Some(SseTypeV2::SseC(algorithm, _, key_md5)) => { - apply_ssec_prepare_encryption_material(request.bucket, request.key, algorithm, request.sse_customer_key, key_md5) - .await? - } - None => return Ok(None), - }; - - Ok(Some(material)) -} - -/// **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(request).await? { -/// content_size = material.original_size.unwrap_or(actual_size); -/// } -/// ``` -pub async fn sse_decryption(request: DecryptionRequest<'_>) -> Result, ApiError> { - // Check for SSE-C encryption - if stored_ssec_metadata(request.metadata) { - let (key, key_md5) = match (request.sse_customer_key, request.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 = request.metadata.get("x-amz-server-side-encryption-customer-key-md5"); - verify_ssec_key_match(key_md5, stored_md5, minio_sealed_ssec_metadata(request.metadata))?; - - 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(request.bucket, request.key, request.metadata, request.principal).await; - } - - // No encryption detected - Ok(None) -} - -/// 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, - pub sse_customer_key_md5: Option, - pub ssekms_key_id: Option, -} - -fn invalid_sse_response_metadata() -> ApiError { - ApiError { - 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<(), ApiError> { - 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(crate) fn project_sse_read_response_headers( - metadata: &HashMap, - sse_customer_algorithm: Option<&String>, - sse_customer_key_md5: Option<&String>, -) -> Result { - 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::>(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) -} - -/// 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(request: DecryptionRequest<'_>) -> Result, ApiError> { - if stored_ssec_metadata(request.metadata) { - let (key, key_md5) = match (request.sse_customer_key, request.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.", - )); - } - }; - - let stored_md5 = request.metadata.get("x-amz-server-side-encryption-customer-key-md5"); - verify_ssec_key_match(key_md5, stored_md5, minio_sealed_ssec_metadata(request.metadata))?; - - let algorithm = request - .metadata - .get("x-amz-server-side-encryption-customer-algorithm") - .map(|s| s.as_str()) - .unwrap_or("AES256"); - 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, - })); - } - - if !contains_managed_encryption_metadata(request.metadata) { - return Ok(None); - } - - let sse_type = match request.metadata.get("x-amz-server-side-encryption").map(String::as_str) { - Some(AMZ_ENCRYPTION_KMS) => SSEType::SseKms, - Some(_) => SSEType::SseS3, - #[cfg(feature = "rio-v2")] - None => match infer_minio_managed_sse_type(request.metadata) { - Some(sse_type) => sse_type, - None => return Ok(None), - }, - #[cfg(not(feature = "rio-v2"))] - None => return Ok(None), - }; - - // Same key-id resolution chain as the unwrap path, so authorization and the - // response header name the same key. - let normalized_metadata = normalize_managed_metadata(request.metadata, Some(recode_minio_kms_context)); - let kms_key_id = resolve_stored_kms_key_id( - normalized_metadata - .get(INTERNAL_ENCRYPTION_KEY_ID_HEADER) - .or_else(|| request.metadata.get("x-amz-server-side-encryption-aws-kms-key-id")) - .cloned(), - ) - .await; - - // 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(request.principal, 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, - sse_type, - Some(&kms_key_id), - || stored_envelope_master_key_version(request.metadata), - Ok(()), - ); - - Ok(Some(SseReadResponseHeaders { - server_side_encryption: managed_sse_public_header(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!(sse_type, SSEType::SseKms).then_some(kms_key_id), - })) -} - -// ============================================================================ -// Internal Implementation - SSE-C -// ============================================================================ - -async fn apply_ssec_prepare_encryption_material( - bucket: &str, - key: &str, - algorithm: String, - sse_key: Option, - sse_key_md5: String, -) -> Result { - #[cfg(feature = "rio-v2")] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = if let Some(sse_key) = sse_key { - let validated = validate_ssec_params(SsecParams { - algorithm: algorithm.clone(), - key: sse_key, - key_md5: sse_key_md5.clone(), - })?; - let object_key = derive_object_key(validated.key_bytes)?; - let sealed_key = seal_object_key(object_key, validated.key_bytes, SSEType::SseC, bucket, key)?; - (object_key, [0; 12], EncryptionKeyKind::Object, Some(sealed_key)) - } else { - ([0; 32], [0; 12], EncryptionKeyKind::Direct, None) - }; - - #[cfg(not(feature = "rio-v2"))] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = { - let _ = (bucket, key, sse_key); - // Generate a real random nonce for the multipart session and persist it (see - // `encryption_material_to_metadata`). Every part of this upload reads the same - // persisted nonce back via `apply_ssec_decryption_material`, so all parts share one - // nonce without reintroducing the deterministic (bucket, key) reuse hazard. - // key_bytes stays a placeholder here: it is neither used for encryption nor persisted; - // the real customer key is validated per part on upload. - let mut base_nonce = [0u8; 12]; - rand::rng().fill_bytes(&mut base_nonce); - ([0; 32], base_nonce, EncryptionKeyKind::Direct, None) - }; - - Ok(EncryptionMaterial { - sse_type: SSEType::SseC, - server_side_encryption: String::from(AMZ_ENCRYPTION_AES), - kms_key_id: None, - algorithm, - key_bytes, - base_nonce, - encrypted_data_key: None, - customer_key_md5: Some(sse_key_md5), - original_size: None, - key_kind, - managed_kms_context: None, - managed_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 { - let params = SsecParams { - algorithm, - key: sse_key, - key_md5: sse_key_md5, - }; - - let validated = validate_ssec_params(params)?; - - #[cfg(feature = "rio-v2")] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = { - let object_key = derive_object_key(validated.key_bytes)?; - let sealed_key = seal_object_key(object_key, validated.key_bytes, SSEType::SseC, bucket, key)?; - (object_key, [0; 12], EncryptionKeyKind::Object, Some(sealed_key)) - }; - - #[cfg(not(feature = "rio-v2"))] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = { - // Use a fresh random nonce per encryption. A deterministic nonce derived from - // (bucket, key) would repeat whenever the same object is overwritten under the same - // SSE-C key, reusing an identical (key, nonce) pair and catastrophically breaking - // AES-256-GCM. The nonce is persisted (see `encryption_material_to_metadata`) and read - // back on decrypt (see `apply_ssec_decryption_material`). - let _ = (bucket, key); - let mut base_nonce = [0u8; 12]; - rand::rng().fill_bytes(&mut base_nonce); - (validated.key_bytes, base_nonce, EncryptionKeyKind::Direct, None) - }; - - // 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, - base_nonce, - encrypted_data_key: None, - customer_key_md5: Some(validated.key_md5), - original_size: Some(content_size), - key_kind, - managed_kms_context: None, - managed_sealed_key, - }) -} - -/// Resolve the SSE-C Direct base nonce for decryption. -/// -/// New objects persist a random nonce at encryption time (see -/// `encryption_material_to_metadata`) 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. -fn read_stored_ssec_nonce(metadata: &HashMap, 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)) -} - -async fn apply_ssec_decryption_material( - bucket: &str, - key: &str, - metadata: &HashMap, - sse_key: &str, - sse_key_md5: &str, -) -> Result { - // Validate provided key - let algorithm = metadata - .get("x-amz-server-side-encryption-customer-algorithm") - .map(|s| s.as_str()) - .unwrap_or("AES256"); - - 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)?; - - #[cfg(feature = "rio-v2")] - let (key_bytes, base_nonce, key_kind) = if let Some(sealed_key) = parse_minio_managed_sealed_key(metadata, SSEType::SseC)? { - ( - unseal_object_key(&sealed_key, validated.key_bytes, SSEType::SseC, bucket, key)?, - [0; 12], - EncryptionKeyKind::Object, - ) - } else { - let base_nonce = read_stored_ssec_nonce(metadata, bucket, key); - (validated.key_bytes, base_nonce, EncryptionKeyKind::Direct) - }; - - #[cfg(not(feature = "rio-v2"))] - let (key_bytes, base_nonce, key_kind) = { - let base_nonce = read_stored_ssec_nonce(metadata, bucket, key); - (validated.key_bytes, base_nonce, EncryptionKeyKind::Direct) - }; - - 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, - base_nonce, - key_kind, - }) -} - -// ============================================================================ -// Internal Implementation - Managed SSE (SSE-S3 / SSE-KMS) -// ============================================================================ - -async fn apply_managed_encryption_material( - bucket: &str, - key: &str, - server_side_encryption: String, - kms_key_id: Option, - ssekms_context: Option>, - content_size: i64, - principal: Option<&SseKmsPrincipal>, -) -> Result { - // Request validation, not a KMS operation: reject before the KMS is called - // and before an audit outcome is recorded. - reject_kms_context_location_override(bucket, ssekms_context.as_ref())?; - - let requested_sse_type = managed_sse_type(server_side_encryption.as_str()); - let requested_key_id = kms_key_id.clone(); - let result = apply_managed_encryption_material_inner( - bucket, - key, - server_side_encryption, - kms_key_id, - ssekms_context, - content_size, - principal, - ) - .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 -} - -/// Scheme a managed-SSE header names, defaulting to SSE-S3 the same way the -/// encryption and decryption paths do. -fn managed_sse_type(server_side_encryption: &str) -> SSEType { - match server_side_encryption { - AMZ_ENCRYPTION_KMS => SSEType::SseKms, - _ => SSEType::SseS3, - } -} - -async fn apply_managed_encryption_material_inner( - bucket: &str, - key: &str, - server_side_encryption: String, - kms_key_id: Option, - ssekms_context: Option>, - content_size: i64, - principal: Option<&SseKmsPrincipal>, -) -> Result { - if !is_managed_sse(&server_side_encryption) { - return Err(ApiError::from(StorageError::other(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) = runtime_sources::current_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 runtime_sources::current_encryption_service().await.is_none() { - return Err(sse_kms_unavailable_error(kms_configured_but_unavailable().await)); - } - return Err(ApiError { - 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(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().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().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) && runtime_sources::current_encryption_service().await.is_none() { - return Err(sse_kms_unavailable_error(kms_configured_but_unavailable().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(); - #[cfg(feature = "rio-v2")] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = { - let object_key = derive_object_key(data_key.plaintext_key)?; - let sealed_key = seal_object_key(object_key, data_key.plaintext_key, encryption_type, bucket, key)?; - (object_key, [0u8; 12], EncryptionKeyKind::Object, Some(sealed_key)) - }; - - #[cfg(not(feature = "rio-v2"))] - let (key_bytes, base_nonce, key_kind, managed_sealed_key) = - (data_key.plaintext_key, data_key.nonce, EncryptionKeyKind::Direct, None); - - Ok(EncryptionMaterial { - sse_type: encryption_type, - server_side_encryption, - kms_key_id: Some(kms_key_to_use), - algorithm, - key_bytes, - base_nonce, - encrypted_data_key: Some(encrypted_data_key), - customer_key_md5: None, - original_size: Some(content_size), - key_kind, - managed_kms_context: matches!(encryption_type, SSEType::SseKms).then_some(ssekms_context.unwrap_or_default()), - managed_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() -> bool { - match current_kms_runtime_service_manager() { - Some(manager) => !matches!(manager.get_status().await, rustfs_kms::KmsServiceStatus::NotConfigured), - None => false, - } -} - -fn sse_kms_unavailable_error(configured_but_unavailable: bool) -> ApiError { - if configured_but_unavailable { - return ApiError::from(StorageError::other(KmsUnavailableError)); - } - ApiError { - code: S3ErrorCode::InvalidRequest, - message: "SSE-KMS requires a configured and running KMS service".to_string(), - source: None, - } -} - -async fn apply_managed_decryption_material( - bucket: &str, - key: &str, - metadata: &HashMap, - principal: Option<&SseKmsPrincipal>, -) -> Result, ApiError> { - let result = apply_managed_decryption_material_inner(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 -} - -/// 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. -async fn resolve_stored_kms_key_id(stored: Option) -> String { - if let Some(key_id) = stored { - return key_id; - } - if let Some(service) = runtime_sources::current_encryption_service().await - && let Some(key_id) = service.get_default_key_id() - { - return key_id.clone(); - } - "default".to_string() -} - -async fn apply_managed_decryption_material_inner( - bucket: &str, - key: &str, - metadata: &HashMap, - principal: Option<&SseKmsPrincipal>, -) -> Result, ApiError> { - #[cfg(not(feature = "rio-v2"))] - let _ = (bucket, key); - if !contains_managed_encryption_metadata(metadata) { - return Ok(None); - } - - 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 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. - #[cfg(feature = "rio-v2")] - None => match infer_minio_managed_sse_type(metadata) { - Some(sse_type) => sse_type, - // Still fail-closed, and deliberately not an error raised here: the - // read plan independently classifies the object as encrypted from - // its markers and refuses to serve it without material, so an - // object whose scheme cannot be established never degrades into a - // plaintext read. - None => return Ok(None), - }, - // 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 => return Ok(None), - }; - - let normalized_metadata = normalize_managed_metadata(metadata, Some(recode_minio_kms_context)); - - // Extract KMS key ID from metadata (optional, used for provider context) - let kms_key_id = resolve_stored_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(), - ) - .await; - - // 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(principal, encryption_type, KmsAction::DecryptAction, &kms_key_id).await?; - - #[cfg(feature = "rio-v2")] - let minio_sealed_key = parse_minio_managed_sealed_key(metadata, encryption_type)?; - #[cfg(not(feature = "rio-v2"))] - let minio_sealed_key: Option = None; - - let (encrypted_data_key, iv, algorithm) = if minio_sealed_key.is_some() { - 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(|| ApiError::from(StorageError::other("Missing encrypted key in metadata")))?; - let encrypted_data_key = BASE64_STANDARD - .decode_to_vec(encrypted_key_b64) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to decode encrypted key: {e}"))))?; - ( - encrypted_data_key, - Vec::new(), - normalized_metadata - .get(INTERNAL_ENCRYPTION_ALGORITHM_HEADER) - .cloned() - .unwrap_or_else(|| "AES256".to_string()), - ) - } else if let Some(service) = runtime_sources::current_encryption_service().await { - // Production mode: use service for metadata parsing - let parsed = service - .headers_to_metadata(&normalized_metadata) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to parse encryption metadata: {e}"))))?; - - if parsed.iv.len() != 12 { - return Err(ApiError::from(StorageError::other("Invalid encryption nonce length; expected 12 bytes"))); - } - - (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(|| ApiError::from(StorageError::other("Missing encrypted key in metadata")))?; - let encrypted_data_key = BASE64_STANDARD - .decode_to_vec(encrypted_key_b64) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to decode encrypted key: {e}"))))?; - - let iv_b64 = normalized_metadata - .get(INTERNAL_ENCRYPTION_IV_HEADER) - .ok_or_else(|| ApiError::from(StorageError::other("Missing IV in metadata")))?; - let iv = BASE64_STANDARD - .decode_to_vec(iv_b64) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to decode IV: {e}"))))?; - - if iv.len() != 12 { - return Err(ApiError::from(StorageError::other("Invalid encryption nonce length; expected 12 bytes"))); - } - - let algorithm = normalized_metadata - .get(INTERNAL_ENCRYPTION_ALGORITHM_HEADER) - .cloned() - .unwrap_or_else(|| "AES256".to_string()); - - (encrypted_data_key, iv, algorithm) - }; - - 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()); - - // 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(&encrypted_data_key) || is_local_sse_dek(&encrypted_data_key) { - None - } else { - bare_data_key_kms_provider().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")] - let unenveloped_sealed_dek = if minio_sealed_key.is_some() && !is_rustfs_managed_data_key(&encrypted_data_key) { - Some( - decrypt_unenveloped_sealed_dek( - bare_kms.clone(), - get_local_sse_dek_provider().await, - &encrypted_data_key, - &kms_key_id, - &object_context, - ) - .await?, - ) - } else { - None - }; - #[cfg(not(feature = "rio-v2"))] - let unenveloped_sealed_dek: Option<[u8; 32]> = None; - - let decrypted_data_key = match unenveloped_sealed_dek { - Some(data_key) => data_key, - None => { - let provider: Arc = if is_data_key_envelope(&encrypted_data_key) { - kms_sse_dek_provider().await? - } else if let Some(kms_provider) = bare_kms { - kms_provider - } else { - get_local_sse_dek_provider().await? - }; - #[cfg(feature = "rio-v2")] - let decrypted_data_key = if is_legacy_rustfs_managed_metadata(&normalized_metadata) { - provider - .decrypt_legacy_sse_dek(&encrypted_data_key, &kms_key_id, &object_context) - .await - } else { - provider - .decrypt_sse_dek(&encrypted_data_key, &kms_key_id, &object_context) - .await - }; - #[cfg(not(feature = "rio-v2"))] - let decrypted_data_key = provider - .decrypt_sse_dek(&encrypted_data_key, &kms_key_id, &object_context) - .await; - decrypted_data_key? - } - }; - #[cfg(feature = "rio-v2")] - let (key_bytes, base_nonce, key_kind) = if let Some(sealed_key) = minio_sealed_key { - ( - unseal_object_key(&sealed_key, decrypted_data_key, encryption_type, bucket, key)?, - [0u8; 12], - EncryptionKeyKind::Object, - ) - } else { - let mut base_nonce = [0u8; 12]; - base_nonce.copy_from_slice(&iv[..12]); - (decrypted_data_key, base_nonce, EncryptionKeyKind::Direct) - }; - #[cfg(not(feature = "rio-v2"))] - let (key_bytes, base_nonce, key_kind) = { - let mut base_nonce = [0u8; 12]; - base_nonce.copy_from_slice(&iv[..12]); - (decrypted_data_key, base_nonce, EncryptionKeyKind::Direct) - }; - - Ok(Some(DecryptionMaterial { - sse_type: encryption_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 gate above had to infer it. MinIO synthesizes the same - // header onto its own responses. - server_side_encryption: managed_sse_public_header(encryption_type).to_string(), - kms_key_id: Some(kms_key_id), - algorithm, - customer_key_md5: None, - - key_bytes, - base_nonce, - key_kind, - })) -} - -// ============================================================================ -// Legacy Types (for backward compatibility) -// ============================================================================ - -/// Validated SSE-C parameters -#[derive(Debug, Clone)] -pub 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 struct SsecParams { - /// Encryption algorithm - pub algorithm: String, - /// Base64-encoded encryption key - pub key: String, - /// Base64-encoded MD5 of the key - pub key_md5: String, -} - -// ============================================================================ -// Object-level DEK rewrap adapter -// ============================================================================ - -/// 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(crate) 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 }, -} - -/// 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(crate) async fn rewrap_object_encryption_metadata( - bucket: &str, - key: &str, - metadata: &HashMap, -) -> Result { - 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| ApiError::from(StorageError::other(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().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(ApiError::from(StorageError::other( - "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 }) -} - -// ============================================================================ -// SSE DEK Provider Abstraction (Factory Pattern) -// ============================================================================ - -/// 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), ApiError>; - - /// 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], ApiError>; - - /// 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 { - Err(ApiError::from(StorageError::other( - "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], ApiError> { - 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], ApiError> { - Err(ApiError::from(StorageError::other( - "This KMS provider cannot unwrap a data key sealed by MinIO's builtin KMS", - ))) - } -} - -// ============================================================================ -// Production KMS-backed DEK Provider -// ============================================================================ - -/// Production KMS-backed DEK provider -/// Resolves the latest ObjectEncryptionService on each call. -struct KmsSseDekProvider { - #[cfg(test)] - service_manager: Option>, -} - -fn kms_operation_error(error: rustfs_kms::KmsError) -> ApiError { - let class = rustfs_kms::audit::error_class(&error); - let mut api_error = ApiError::from(StorageError::other(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. -fn kms_unwrap_error(error: rustfs_kms::KmsError) -> ApiError { - 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 KmsSseDekProvider { - /// Create a new KMS-backed provider - pub async fn new() -> Result { - let provider = Self { - #[cfg(test)] - service_manager: None, - }; - provider - .current_service() - .await - .ok_or_else(|| ApiError::from(StorageError::other(KmsUnavailableError)))?; - Ok(provider) - } - - #[cfg(test)] - async fn new_with_service_manager(service_manager: Arc) -> Result { - let provider = Self { - service_manager: Some(service_manager), - }; - provider - .current_service() - .await - .ok_or_else(|| ApiError::from(StorageError::other(KmsUnavailableError)))?; - Ok(provider) - } - - async fn current_service(&self) -> Option> { - #[cfg(test)] - if let Some(service_manager) = &self.service_manager { - return service_manager.get_encryption_service().await; - } - - runtime_sources::current_encryption_service().await - } -} - -#[async_trait] -impl SseDekProvider for KmsSseDekProvider { - async fn generate_sse_dek( - &self, - context: &ObjectEncryptionContext, - kms_key_id: &str, - ) -> Result<(DataKey, Vec), ApiError> { - let kms_key_option = Some(kms_key_id.to_string()); - let service = self - .current_service() - .await - .ok_or_else(|| ApiError::from(StorageError::other(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 { - let service = self - .current_service() - .await - .ok_or_else(|| ApiError::from(StorageError::other(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], ApiError> { - let service = self - .current_service() - .await - .ok_or_else(|| ApiError::from(StorageError::other(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], ApiError> { - let service = self - .current_service() - .await - .ok_or_else(|| ApiError::from(StorageError::other(KmsUnavailableError)))?; - let data_key = service - .decrypt_legacy_data_key(encrypted_dek) - .await - .map_err(kms_unwrap_error)?; - - Ok(data_key.plaintext_key) - } -} - -// ============================================================================ -// Test/Simple DEK Provider -// ============================================================================ - -/// 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= -/// ``` -pub(crate) struct LocalSseDekProvider { - master_key: [u8; 32], -} - -const LOCAL_SSE_DEK_FORMAT_VERSION: u8 = 1; - -#[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. -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::>(text).is_ok()) -} - -#[cfg(feature = "rio-v2")] -/// 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. -fn minio_kms_associated_data(context: &ObjectEncryptionContext) -> Result, ApiError> { - 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| ApiError::from(StorageError::other(format!("Failed to canonicalize MinIO KMS context: {e}")))) -} - -#[cfg(feature = "rio-v2")] -/// 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. -#[cfg(feature = "rio-v2")] -const MINIO_KMS_RANDOM_LEN: usize = 28; -#[cfg(feature = "rio-v2")] -const MINIO_KMS_IV_LEN: usize = 16; - -#[cfg(feature = "rio-v2")] -const MINIO_KMS_AEAD_AES_GCM: &str = "AES-256-GCM-HMAC-SHA-256"; -#[cfg(feature = "rio-v2")] -const MINIO_KMS_AEAD_CHACHA20: &str = "ChaCha20Poly1305"; - -#[cfg(feature = "rio-v2")] -/// 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. -fn decrypt_minio_kms_data_key(encrypted_dek: &[u8], master_key: &[u8; 32], aad: &[u8]) -> Result<[u8; 32], ApiError> { - 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::(text) => - { - let decode = |what: &str, value: &str| -> Result, ApiError> { - BASE64_STANDARD - .decode_to_vec(value) - .map_err(|e| ApiError::from(StorageError::other(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(ApiError::from(StorageError::other( - "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(|_| ApiError::from(StorageError::other("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(|_| ApiError::from(StorageError::other("MinIO KMS sealing key is not a valid AES-256 key")))?; - let nonce = aes_gcm::Nonce::try_from(nonce) - .map_err(|_| ApiError::from(StorageError::other("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(|_| ApiError::from(StorageError::other("MinIO KMS master key is not a valid ChaCha20 key")))?; - let nonce = chacha20poly1305::XNonce::try_from(extended.as_slice()) - .map_err(|_| ApiError::from(StorageError::other("MinIO KMS extended nonce is not 24 bytes")))?; - cipher.decrypt(&nonce, chacha20poly1305::aead::Payload { msg: sealed, aad }) - } - other => { - return Err(ApiError::from(StorageError::other(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(|_| ApiError::from(StorageError::other("MinIO KMS data key failed authentication")))?; - - plaintext.try_into().map_err(|value: Vec| { - ApiError::from(StorageError::other(format!("MinIO KMS data key must be 32 bytes, got {}", value.len()))) - }) -} - -#[derive(Debug, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct LocalSseDekEnvelope<'a> { - version: u8, - 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. -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)) -} - -/// 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")] -async fn decrypt_unenveloped_sealed_dek( - bare_kms: Option>, - local: Result, ApiError>, - encrypted_dek: &[u8], - kms_key_id: &str, - context: &ObjectEncryptionContext, -) -> Result<[u8; 32], ApiError> { - 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 without -/// an `AppContext`. 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. -async fn kms_sse_dek_provider() -> Result, ApiError> { - 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().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. -async fn bare_data_key_kms_provider() -> Option> { - let provider = kms_sse_dek_provider().await.ok()?; - provider.reads_bare_data_key_ciphertext().await.then_some(provider) -} - -/// Test-only alias so existing test code that references `TestSseDekProvider` -/// continues to compile without changes. #[cfg(test)] -#[allow(non_camel_case_types)] -pub(crate) 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(test)] -fn parse_simple_sse_cmk(cmk_value: &str) -> Result<[u8; 32], ApiError> { - let trimmed = cmk_value.trim(); - if trimmed.is_empty() { - return Err(ApiError::from(StorageError::other( - "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| ApiError::from(StorageError::other(format!("__RUSTFS_SSE_SIMPLE_CMK must be valid base64: {e}"))))?; - let master_key: [u8; 32] = decoded.try_into().map_err(|v: Vec| { - ApiError::from(StorageError::other(format!( - "__RUSTFS_SSE_SIMPLE_CMK must decode to exactly 32 bytes, got {} bytes", - v.len() - ))) - })?; - if master_key == [0u8; 32] { - return Err(ApiError::from(StorageError::other("__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(test)] - pub fn new_with_key(master_key: [u8; 32]) -> Self { - Self { master_key } - } - - /// Create a TestSseDekProvider from `__RUSTFS_SSE_SIMPLE_CMK` (test-only). - #[cfg(test)] - pub fn new() -> Result { - 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 { - fn sse_not_configured(message: impl Into) -> ApiError { - ApiError { - code: S3ErrorCode::InvalidRequest, - message: message.into(), - source: None, - } - } - - let Some(raw_value) = get_env_opt_str("RUSTFS_SSE_S3_MASTER_KEY").filter(|value| !value.trim().is_empty()) 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") - })?; - - tracing::info!("Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3 (KMS not configured)"); - Ok(Self { master_key }) - } - - // Simple encryption of DEK - pub(crate) fn encrypt_dek(dek: [u8; 32], cmk_value: [u8; 32]) -> Result { - // Use AES-256-GCM to encrypt DEK - let key = Key::::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(|_| ApiError::from(StorageError::other("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| ApiError::from(StorageError::other(format!("Failed to serialize encrypted DEK: {e}")))) - } - - // Simple decryption of DEK - pub(crate) fn decrypt_dek(encrypted_dek: &str, cmk_value: [u8; 32]) -> Result<[u8; 32], ApiError> { - let envelope = serde_json::from_str::>(encrypted_dek); - let (nonce, ciphertext) = match envelope { - Ok(envelope) => { - if envelope.version != LOCAL_SSE_DEK_FORMAT_VERSION { - return Err(ApiError::from(StorageError::other(format!( - "Unsupported encrypted DEK format version: {}", - envelope.version - )))); - } - (envelope.nonce, envelope.ciphertext) - } - Err(json_error) if encrypted_dek.trim_start().starts_with('{') => { - return Err(ApiError::from(StorageError::other(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(ApiError::from(StorageError::other("Invalid encrypted DEK format"))); - }; - if ciphertext.contains(':') { - return Err(ApiError::from(StorageError::other("Invalid encrypted DEK format"))); - } - (nonce, ciphertext) - } - }; - let nonce_vec = BASE64_STANDARD - .decode_to_vec(nonce) - .map_err(|_| ApiError::from(StorageError::other("Invalid nonce format")))?; - let ciphertext = BASE64_STANDARD - .decode_to_vec(ciphertext) - .map_err(|_| ApiError::from(StorageError::other("Invalid ciphertext format")))?; - - let key = Key::::from(cmk_value); - let cipher = Aes256Gcm::new(&key); - - let nonce_array: [u8; 12] = nonce_vec - .try_into() - .map_err(|_| ApiError::from(StorageError::other("Invalid nonce length")))?; - let nonce = Nonce::from(nonce_array); - - let plaintext = cipher - .decrypt(&nonce, ciphertext.as_slice()) - .map_err(|e| ApiError::from(StorageError::other(format!("Failed to decrypt DEK: {e}"))))?; - - let dek: [u8; 32] = plaintext - .try_into() - .map_err(|_| ApiError::from(StorageError::other("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), ApiError> { - // 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], ApiError> { - // Decrypt data key with master key - let encrypted_dek_str = std::str::from_utf8(encrypted_dek) - .map_err(|_| ApiError::from(StorageError::other("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], ApiError> { - let aad = minio_kms_associated_data(context)?; - decrypt_minio_kms_data_key(encrypted_dek, &self.master_key, &aad) - } -} - -// ============================================================================ -// Factory Function for SSE DEK 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. -static GLOBAL_SSE_DEK_PROVIDER: LazyLock>>> = 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>>> = 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().await?; -/// let (data_key, encrypted_dek) = provider -/// .generate_sse_dek("bucket", "key", "kms-key-id") -/// .await?; -/// ``` -pub async fn get_sse_dek_provider() -> Result, ApiError> { - if runtime_sources::current_encryption_service().await.is_some() { - debug!("Using KmsSseDekProvider (KMS configured)"); - return Ok(Arc::new(KmsSseDekProvider::new().await?)); - } - - get_local_sse_dek_provider().await -} - -async fn get_local_sse_dek_provider() -> Result, ApiError> { - // An explicitly injected test provider overrides both the cache and the - // environment-based selection below. - #[cfg(test)] - 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(|_| ApiError::from(StorageError::other("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(test)] - { - if std::env::var("__RUSTFS_SSE_SIMPLE_CMK").is_ok() { - debug!("Using LocalSseDekProvider (test mode) based on __RUSTFS_SSE_SIMPLE_CMK"); - let provider: Arc = Arc::new(LocalSseDekProvider::new()?); - let mut slot = GLOBAL_SSE_DEK_PROVIDER - .write() - .map_err(|_| ApiError::from(StorageError::other("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 = Arc::new(LocalSseDekProvider::new_from_env()?); - - let mut slot = GLOBAL_SSE_DEK_PROVIDER - .write() - .map_err(|_| ApiError::from(StorageError::other("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(test)] -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(test)] -pub fn set_sse_dek_provider_for_test(provider: Arc) { - 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(test)] -fn test_injected_sse_dek_provider() -> Option> { - GLOBAL_KMS_DEK_PROVIDER.read().ok().and_then(|guard| guard.as_ref().cloned()) -} - -// ============================================================================ -// Legacy Functions (SSE-S3 / SSE-KMS) -// ============================================================================ - -/// Check if the server_side_encryption is a managed SSE type (SSE-S3 or SSE-KMS) -#[inline] -pub fn is_managed_sse(server_side_encryption: &str) -> bool { - matches!(server_side_encryption, "AES256" | "aws:kms") -} - -/// 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) { - 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) { - metadata.insert(MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER.to_string(), String::new()); -} - -#[cfg(feature = "rio-v2")] -fn is_legacy_rustfs_managed_metadata(metadata: &HashMap) -> 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) -} - -/// 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(crate) fn stored_ssec_metadata(metadata: &HashMap) -> 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. -fn minio_sealed_ssec_metadata(metadata: &HashMap) -> bool { - cfg!(feature = "rio-v2") && metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER) -} - -#[cfg(feature = "rio-v2")] -/// 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. -fn infer_minio_managed_sse_type(metadata: &HashMap) -> Option { - 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 - } -} - -#[cfg(feature = "rio-v2")] -fn parse_minio_managed_sealed_key( - metadata: &HashMap, - sse_type: SSEType, -) -> Result, ApiError> { - 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 })) -} - -/// 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. -fn recode_minio_kms_context(value: &str) -> Option { - let decoded = BASE64_STANDARD.decode_to_vec(value).ok()?; - let context = serde_json::from_slice::>(&decoded).ok()?; - serde_json::to_string(&context).ok() -} - -// ============================================================================ -// SSE-C Functions -// ============================================================================ - -/// 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 fn validate_ssec_params(params: SsecParams) -> Result { - 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, - }) -} - -/// 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 fn generate_ssec_nonce(bucket: &str, key: &str) -> [u8; 12] { - let nonce_source = format!("{bucket}-{key}"); - let nonce_hash = md5_bytes(nonce_source.as_bytes()); - let mut nonce = [0u8; 12]; - nonce.copy_from_slice(&nonce_hash[..12]); - nonce -} - -/// 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 fn verify_ssec_key_match(provided_md5: &str, stored_md5: Option<&String>, minio_sealed_ssec: bool) -> Result<(), ApiError> { - 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.")), - } -} - -/// 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, - sse_customer_key: Option<&String>, - sse_customer_key_md5: Option<&String>, -) -> Result<(), ApiError> { - 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 `ApiError` with `InvalidRequest` (HTTP 400) for SSE-C related errors. -fn ssec_invalid_request(message: &str) -> ApiError { - ApiError { - code: S3ErrorCode::InvalidRequest, - message: message.to_string(), - source: None, - } -} - -#[cfg(test)] -#[allow(unused_imports)] -pub(crate) mod tests { +mod tests { use super::{ - ApiError, DataKey, DecryptionMaterial, DecryptionRequest, EncryptionKeyKind, EncryptionMaterial, EncryptionRequest, - EncryptionResolutionError, EncryptionResolutionErrorKind, INTERNAL_ENCRYPTION_ALGORITHM_HEADER, - INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER, INTERNAL_ENCRYPTION_KEY_ID_HEADER, KmsAction, - KmsKeyAuthorizer, KmsSseDekProvider, KmsUnavailableError, 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, ObjectDekRewrapOutcome, - ObjectEncryptionResolver, PrepareEncryptionRequest, ReadEncryptionMode, ReadEncryptionRequest, SSEC_ORIGINAL_SIZE_HEADER, - SSEType, SseDekProvider, SseKmsPrincipal, SseObjectEncryptionResolver, SsecParams, StorageError, TestSseDekProvider, - apply_managed_decryption_material, apply_managed_encryption_material, apply_managed_encryption_material_inner, - authorize_sse_kms_object_read, build_kms_request_context, classify_sse_read_response, encode_minio_kms_context, - encryption_material_to_metadata, extract_server_side_encryption_from_headers, extract_ssec_params_from_headers, - extract_ssekms_context_from_headers, generate_ssec_nonce, is_managed_sse, kms_operation_error, - map_get_object_reader_error, mark_encrypted_multipart_metadata, md5_base64, normalize_managed_metadata, - project_sse_read_response_headers, recode_minio_kms_context, reset_sse_dek_provider, resolve_effective_kms_key_id, - resolve_stored_kms_key_id, rewrap_object_encryption_metadata, sse_decryption, sse_encryption, sse_prepare_encryption, - strip_managed_encryption_metadata, validate_sse_headers_for_read, validate_sse_headers_for_write, validate_ssec_for_read, - validate_ssec_params, verify_ssec_key_match, + ApiError, Arc, EncryptionRequest, EncryptionResolutionError, EncryptionResolutionErrorKind, HashMap, HeaderMap, + KMS_KEY_NOT_FOUND_ERROR_CODE, KmsRequestAuditScope, ObjectEncryptionResolver, ReadEncryptionMode, ReadEncryptionRequest, + RecordingKmsKeyAuthorizer, S3ErrorCode, SseError, SseKmsPrincipal, SseKmsPrincipalExt, SseObjectEncryptionResolver, + StorageError, TestAuthorizationHooks, map_encryption_resolution_error, map_get_object_reader_error, + multipart_completion_authorization, sse_kms_object_metadata, validate_conditional_read, }; - #[cfg(feature = "rio-v2")] - use super::{ - DARE_CIPHER_AES_256_GCM, DARE_CIPHER_CHACHA20_POLY1305, MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM, SEALED_KEY_IV_SIZE, - SEALED_KEY_SIZE, is_legacy_rustfs_managed_metadata, is_supported_sealed_object_key_cipher, - }; - use rustfs_utils::http::headers::SSEC_ALGORITHM_HEADER; + use base64_simd::STANDARD as BASE64_STANDARD; + use http::HeaderValue; + use md5::{Digest, Md5}; + use rustfs_utils::http::object_encryption_keys::MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER; - /// backlog#1643 PR-B0 acceptance guard: the managed-SSE classifier must - /// have exactly one definition — in the shared encryption-keys module — - /// so the scanner and the S3 layer can never disagree on attribution. - /// This module may only re-export or call it. - #[test] - fn managed_sse_classifier_has_exactly_one_definition() { - let classifier_fns = [ - "contains_managed_encryption_metadata", - "normalize_managed_metadata", - "stored_managed_encryption_key", - ]; - - let sse_src = include_str!("sse.rs"); - let shared_src = - std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../crates/utils/src/http/object_encryption_keys.rs")) - .expect("shared encryption-keys module should be readable"); - - for name in classifier_fns { - // Built at runtime so this test's own source cannot satisfy the scan. - let definition = format!("fn {name}("); - assert!( - !sse_src.contains(&definition), - "{name} must not be redefined in storage/sse.rs; call the shared rustfs_utils::http::object_encryption_keys implementation instead" - ); - assert_eq!( - shared_src.matches(&definition).count(), - 1, - "{name} must be defined exactly once, in the shared encryption-keys module" - ); - } + fn md5_base64(input: impl AsRef<[u8]>) -> String { + let mut hasher = Md5::new(); + hasher.update(input.as_ref()); + BASE64_STANDARD.encode_to_string(hasher.finalize()) } - #[test] - fn ssec_read_headers_are_sensitive() { - let headers = super::build_ssec_read_headers( - Some(&"AES256".to_string()), - Some(&"dHJhbnNwb3J0LXNlY3JldA==".to_string()), - Some(&"bWQ1LXNlY3JldA==".to_string()), + fn principal_with_authorizer(enforced: bool, authorizer: Arc) -> SseKmsPrincipal { + SseKmsPrincipal::new("analyst".to_string(), None, false, HashMap::new(), HashMap::new()) + .with_test_hooks(Some(TestAuthorizationHooks { enforced, authorizer })) + } + + fn enforcing_principal(allowed: bool) -> (SseKmsPrincipal, Arc) { + let authorizer = RecordingKmsKeyAuthorizer::new(allowed); + (principal_with_authorizer(true, authorizer.clone()), authorizer) + } + + fn audit_tag(tags: &[(&'static str, serde_json::Value)], key: &str) -> Option { + tags.iter() + .find(|(candidate, _)| *candidate == key) + .and_then(|(_, value)| value.as_str().map(str::to_string)) + } + + fn ssec_read_headers(key_b64: &str, key_md5: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static("AES256")); + headers.insert( + "x-amz-server-side-encryption-customer-key", + HeaderValue::from_str(key_b64).expect("base64 key is a valid header"), ); + headers.insert( + "x-amz-server-side-encryption-customer-key-md5", + HeaderValue::from_str(key_md5).expect("base64 MD5 is a valid header"), + ); + headers + } - assert_eq!(headers.len(), 3); - assert!(headers.values().all(HeaderValue::is_sensitive)); - let debug = format!("{headers:?}"); - assert!(!debug.contains("dHJhbnNwb3J0LXNlY3JldA==")); - assert!(!debug.contains("bWQ1LXNlY3JldA==")); + fn multipart_ssec_request(key_byte: u8) -> EncryptionRequest<'static> { + let key_bytes = [key_byte; 32]; + EncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(BASE64_STANDARD.encode_to_string(key_bytes)), + sse_customer_key_md5: Some(md5_base64(key_bytes)), + content_size: 1, + principal: None, + } + } + + fn multipart_ssec_metadata(key_byte: u8) -> HashMap { + let key_bytes = [key_byte; 32]; + HashMap::from([ + ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()), + ("x-amz-server-side-encryption-customer-key-md5".to_string(), md5_base64(key_bytes)), + ]) + } + + /// The messages `rustfs-sse` attaches to the codes it classifies must be the + /// ones this server answers those codes with everywhere else. + #[test] + fn sse_errors_carry_this_servers_messages() { + let internal = ApiError::from(SseError::internal("plain failure")); + assert_eq!(internal.code, S3ErrorCode::InternalError); + assert_eq!(internal.message, ApiError::error_code_to_message(&S3ErrorCode::InternalError)); + + let unavailable = ApiError::from(SseError::internal(rustfs_kms::KmsUnavailableError)); + assert_eq!(unavailable.code, S3ErrorCode::ServiceUnavailable); + assert_eq!(unavailable.message, ApiError::error_code_to_message(&S3ErrorCode::ServiceUnavailable)); + + let denied = ApiError::from(SseError::internal(rustfs_kms::KmsError::access_denied("policy"))); + assert_eq!(denied.code, S3ErrorCode::AccessDenied); + assert_eq!(denied.message, ApiError::error_code_to_message(&S3ErrorCode::AccessDenied)); } #[test] @@ -4715,36 +691,9 @@ pub(crate) mod tests { ); let principal = SseKmsPrincipal::from_request(&envelope).expect("S3-boundary request should build a principal"); - assert!(principal.account.is_empty()); - assert!(principal.groups.is_none()); - assert!(principal.claims.is_empty()); - } - - #[test] - fn parse_simple_sse_cmk_rejects_bad_keys_without_crashing() { - // Empty / whitespace-only. - assert!(super::parse_simple_sse_cmk("").is_err()); - assert!(super::parse_simple_sse_cmk(" ").is_err()); - // Not valid base64. - assert!(super::parse_simple_sse_cmk("@@@not-base64@@@").is_err()); - // Valid base64 but wrong length (16 bytes). - let short = BASE64_STANDARD.encode_to_string([1u8; 16]); - assert!(super::parse_simple_sse_cmk(&short).is_err()); - // All-zero 32-byte key is rejected. - let zero = BASE64_STANDARD.encode_to_string([0u8; 32]); - assert!(super::parse_simple_sse_cmk(&zero).is_err()); - } - - #[test] - fn kms_operation_errors_preserve_retryability_classification() { - let unavailable = kms_operation_error(rustfs_kms::KmsError::backend_error("connection refused")); - let corrupt = kms_operation_error(rustfs_kms::KmsError::cryptographic_error("decrypt", "authentication failed")); - let missing = kms_operation_error(rustfs_kms::KmsError::key_not_found("no-such-key")); - - assert_eq!(unavailable.code, S3ErrorCode::ServiceUnavailable); - assert_eq!(corrupt.code, S3ErrorCode::InternalError); - assert_eq!(missing.code, S3ErrorCode::Custom(crate::error::KMS_KEY_NOT_FOUND_ERROR_CODE.into())); - assert_eq!(super::kms_data_plane_error_class(&missing), "key_not_found"); + assert!(principal.account().is_empty()); + assert!(principal.groups().is_none()); + assert!(principal.claims().is_empty()); } /// The read path squeezes the S3 classification through ecstore's @@ -4778,233 +727,11 @@ pub(crate) mod tests { ]; for (error, expected) in cases { let description = error.to_string(); - let resolution = super::map_encryption_resolution_error(kms_operation_error(error)); + let resolution = map_encryption_resolution_error(SseError::internal(error)); assert_eq!(resolution.kind(), expected, "{description}"); } } - /// An unwrap the backend rejects stays an internal error, but says why in - /// words an operator can act on rather than the generic 500 text. - #[test] - fn kms_unwrap_error_keeps_500_but_names_the_envelope_mismatch() { - let rejected = super::kms_unwrap_error(rustfs_kms::KmsError::cryptographic_error("decrypt", "authentication failed")); - assert_eq!(rejected.code, S3ErrorCode::InternalError); - assert!(rejected.message.contains("could not be unwrapped"), "message was {}", rejected.message); - assert_eq!(super::kms_data_plane_error_class(&rejected), "cryptographic"); - - let missing = super::kms_unwrap_error(rustfs_kms::KmsError::key_not_found("no-such-key")); - assert_eq!(missing.code, S3ErrorCode::Custom(crate::error::KMS_KEY_NOT_FOUND_ERROR_CODE.into())); - assert_eq!(missing.message, "KMS key not found: no-such-key"); - } - - #[test] - fn sse_kms_never_falls_back_to_the_local_sse_s3_provider() { - let unconfigured = super::sse_kms_unavailable_error(false); - assert_eq!(unconfigured.code, S3ErrorCode::InvalidRequest); - assert!(unconfigured.message.contains("SSE-KMS requires")); - - let stopped = super::sse_kms_unavailable_error(true); - assert_eq!(stopped.code, S3ErrorCode::ServiceUnavailable); - } - - fn managed_write(algorithm: &'static str, kms_key_id: Option<&str>) -> EncryptionRequest<'static> { - EncryptionRequest { - bucket: "finance", - key: "ledger.csv", - server_side_encryption: Some(String::from(algorithm)), - ssekms_key_id: kms_key_id.map(str::to_string), - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 128, - principal: None, - } - } - - /// A bucket default naming a KMS key, on a node with no KMS, used to write - /// the object under the local master key while stamping `aws:kms` and that - /// never-consulted key id into the metadata (backlog#2368 B4). - #[tokio::test] - async fn sse_kms_write_is_refused_when_only_a_local_master_key_is_available() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::), - ("RUSTFS_SSE_S3_MASTER_KEY", Some(BASE64_STANDARD.encode_to_string([9u8; 32]))), - ], - async { - let error = sse_encryption(managed_write(AMZ_ENCRYPTION_KMS, Some("arn:aws:kms:us-east-1:123:key/nonexistent"))) - .await - .expect_err("SSE-KMS must not be served by the local master key"); - - assert_eq!(error.code, S3ErrorCode::InvalidRequest); - assert!(error.message.contains("SSE-KMS requires"), "message was {}", error.message); - }, - ) - .await; - - reset_sse_dek_provider(); - } - - /// Without a master key the local fallback fails with an SSE-S3-worded - /// configuration error. An SSE-KMS request must not be told to set - /// `RUSTFS_SSE_S3_MASTER_KEY`. - #[tokio::test] - async fn sse_kms_refusal_names_sse_kms_rather_than_the_sse_s3_master_key() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::), - ("RUSTFS_SSE_S3_MASTER_KEY", None::), - ], - async { - let error = sse_encryption(managed_write(AMZ_ENCRYPTION_KMS, Some("finance-key"))) - .await - .expect_err("SSE-KMS must be refused when no KMS is configured"); - - assert_eq!(error.code, S3ErrorCode::InvalidRequest); - assert!(error.message.contains("SSE-KMS requires"), "message was {}", error.message); - assert!( - !error.message.contains("RUSTFS_SSE_S3_MASTER_KEY"), - "an SSE-KMS refusal must not name the SSE-S3 master key: {}", - error.message - ); - }, - ) - .await; - - reset_sse_dek_provider(); - } - - /// A bare `aws:kms` request (no key id, no bucket default) on a node with - /// no KMS has no key to resolve. It must get the same configuration - /// refusal as the keyed form, whether or not the SSE-S3 master key is - /// set, rather than an untyped internal error (backlog#2368 B4). - #[tokio::test] - async fn sse_kms_write_without_a_key_id_is_refused_like_the_keyed_form() { - let _guard = lock_sse_test_state().await; - - for master_key in [None, Some(BASE64_STANDARD.encode_to_string([9u8; 32]))] { - reset_sse_dek_provider(); - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::), - ("RUSTFS_SSE_S3_MASTER_KEY", master_key.clone()), - ], - async { - // Entered directly: `sse_encryption` consults the bucket - // default first, which needs a bucket metadata store. - let error = apply_managed_encryption_material( - "finance", - "ledger.csv", - String::from(AMZ_ENCRYPTION_KMS), - None, - None, - 128, - None, - ) - .await - .expect_err("SSE-KMS without a key id must be refused when no KMS is running"); - - assert_eq!( - error.code, - S3ErrorCode::InvalidRequest, - "master_key={master_key:?}: message was {}", - error.message - ); - assert!(error.message.contains("SSE-KMS requires"), "message was {}", error.message); - assert!( - !error.message.contains("RUSTFS_SSE_S3_MASTER_KEY"), - "an SSE-KMS refusal must not name the SSE-S3 master key: {}", - error.message - ); - }, - ) - .await; - } - - reset_sse_dek_provider(); - } - - /// The SSE-S3 local fallback itself is unchanged: refusing SSE-KMS must not - /// take the documented no-KMS deployment down with it. - #[tokio::test] - async fn sse_s3_write_still_uses_the_local_master_key_fallback() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::), - ("RUSTFS_SSE_S3_MASTER_KEY", Some(BASE64_STANDARD.encode_to_string([9u8; 32]))), - ], - async { - let material = sse_encryption(managed_write(AMZ_ENCRYPTION_AES, None)) - .await - .expect("SSE-S3 keeps its local master key fallback") - .expect("managed sse-s3 material"); - - assert_eq!(material.sse_type, SSEType::SseS3); - assert_eq!(material.algorithm, AMZ_ENCRYPTION_AES); - - // No object may claim aws:kms while its DEK is wrapped locally. - let metadata = encryption_material_to_metadata(&material).expect("sse-s3 metadata should serialize"); - assert!( - !metadata.iter().any(|(_, value)| value == AMZ_ENCRYPTION_KMS), - "local-master-key material must never be stamped aws:kms: {metadata:?}" - ); - }, - ) - .await; - - reset_sse_dek_provider(); - } - - #[test] - fn parse_simple_sse_cmk_accepts_valid_32_byte_key() { - let mut key = [0u8; 32]; - key[0] = 7; - let encoded = BASE64_STANDARD.encode_to_string(key); - let got = super::parse_simple_sse_cmk(&encoded).expect("valid 32-byte key must parse"); - assert_eq!(got, key); - } - 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 http::{HeaderMap, HeaderValue}; - use rustfs_kms::types::ObjectEncryptionContext; - use rustfs_rio::{DecryptReader, EncryptReader}; - use rustfs_s3_types::S3ErrorCode; - use rustfs_utils::http::headers::AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT; - use rustfs_utils::http::headers::{AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS}; - use std::collections::HashMap; - use std::sync::{Arc, OnceLock}; - use temp_env::async_with_vars; - use tokio::sync::Mutex; - - static SSE_TEST_LOCK: OnceLock> = OnceLock::new(); - static SSE_TEST_KMS_KEY_DIR: OnceLock = OnceLock::new(); - - async fn lock_sse_test_state() -> tokio::sync::MutexGuard<'static, ()> { - SSE_TEST_LOCK.get_or_init(|| Mutex::new(())).lock().await - } - - async fn configure_test_global_local_kms() -> Arc { - let key_dir = SSE_TEST_KMS_KEY_DIR.get_or_init(|| tempfile::TempDir::new().expect("create KMS key directory")); - let manager = rustfs_kms::init_global_kms_service_manager(); - manager - .reconfigure(rustfs_kms::KmsConfig::local(key_dir.path().to_path_buf()).with_insecure_development_defaults()) - .await - .expect("configure test KMS service"); - manager - } - #[tokio::test] async fn object_encryption_resolver_returns_ssec_read_material() { let key = [0x31; 32]; @@ -5016,16 +743,7 @@ pub(crate) mod tests { ("X-Amz-Server-Side-Encryption-Customer-Key-Md5".to_string(), key_md5.clone()), ("X-Rustfs-Encryption-Iv".to_string(), BASE64_STANDARD.encode_to_string(nonce)), ]); - let mut headers = HeaderMap::new(); - headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static("AES256")); - headers.insert( - "x-amz-server-side-encryption-customer-key", - HeaderValue::from_str(&key_b64).expect("base64 key is a valid header"), - ); - headers.insert( - "x-amz-server-side-encryption-customer-key-md5", - HeaderValue::from_str(&key_md5).expect("base64 MD5 is a valid header"), - ); + let headers = ssec_read_headers(&key_b64, &key_md5); let material = SseObjectEncryptionResolver .resolve_read_material(ReadEncryptionRequest { @@ -5053,18 +771,15 @@ pub(crate) mod tests { ]); for algorithm in [None, Some("AES128")] { - let mut headers = HeaderMap::new(); - if let Some(algorithm) = algorithm { - headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static(algorithm)); + let mut headers = ssec_read_headers(&key_b64, &key_md5); + match algorithm { + Some(algorithm) => { + headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static(algorithm)); + } + None => { + headers.remove("x-amz-server-side-encryption-customer-algorithm"); + } } - headers.insert( - "x-amz-server-side-encryption-customer-key", - HeaderValue::from_str(&key_b64).expect("base64 key is a valid header"), - ); - headers.insert( - "x-amz-server-side-encryption-customer-key-md5", - HeaderValue::from_str(&key_md5).expect("base64 MD5 is a valid header"), - ); let result = SseObjectEncryptionResolver .resolve_read_material(ReadEncryptionRequest { @@ -5192,3306 +907,6 @@ pub(crate) mod tests { assert!(api_error.message.contains("no decryption material could be resolved")); } - #[tokio::test] - async fn resolve_stored_kms_key_id_prefers_the_stored_id() { - assert_eq!(resolve_stored_kms_key_id(Some("app-key".to_string())).await, "app-key"); - } - - #[test] - fn normalize_encryption_metadata_case_accepts_lowercase_minio_internal_keys() { - let lowercase_key = MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_ascii_lowercase(); - let metadata = HashMap::from([(lowercase_key, "sealed-key".to_string())]); - - let normalized = super::normalize_encryption_metadata_case(&metadata).expect("metadata aliases should normalize"); - - assert_eq!( - normalized.get(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER), - Some(&"sealed-key".to_string()) - ); - } - - struct UnavailableSseDekProvider; - - #[async_trait::async_trait] - impl SseDekProvider for UnavailableSseDekProvider { - async fn generate_sse_dek( - &self, - _context: &ObjectEncryptionContext, - _kms_key_id: &str, - ) -> Result<(DataKey, Vec), ApiError> { - Err(ApiError::from(StorageError::other(KmsUnavailableError))) - } - - async fn decrypt_sse_dek( - &self, - _encrypted_dek: &[u8], - _kms_key_id: &str, - _context: &ObjectEncryptionContext, - ) -> Result<[u8; 32], ApiError> { - Err(ApiError::from(StorageError::other(KmsUnavailableError))) - } - } - - fn local_sse_master_key_b64() -> String { - BASE64_STANDARD.encode_to_string([0x24u8; 32]) - } - - #[test] - fn test_extract_ssec_params_from_headers() { - let mut headers = http::HeaderMap::new(); - let (algo, key, md5) = extract_ssec_params_from_headers(&headers).unwrap(); - assert!(algo.is_none()); - assert!(key.is_none()); - assert!(md5.is_none()); - - headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static("AES256")); - let (algo, key, md5) = extract_ssec_params_from_headers(&headers).unwrap(); - assert_eq!(algo.as_deref(), Some("AES256")); - assert!(key.is_none()); - assert!(md5.is_none()); - - headers.insert( - "x-amz-server-side-encryption-customer-key", - HeaderValue::from_static("pO3upElrwuEXSoFwCfnZPdSsmt/xWeFa0N9KgDijwVs="), - ); - headers.insert( - "x-amz-server-side-encryption-customer-key-md5", - HeaderValue::from_static("DWygnHRtgiJ77HCm+1rvHw=="), - ); - let (algo, key, md5) = extract_ssec_params_from_headers(&headers).unwrap(); - assert_eq!(algo.as_deref(), Some("AES256")); - assert!(key.is_some()); - assert!(md5.is_some()); - } - - #[test] - fn test_extract_ssec_params_from_headers_rejects_invalid_utf8() { - let mut headers = http::HeaderMap::new(); - // Header value with invalid UTF-8; to_str() will fail - let invalid_utf8 = HeaderValue::from_bytes(b"invalid-\x80-utf8").unwrap(); - headers.insert("x-amz-server-side-encryption-customer-algorithm", invalid_utf8); - let result = extract_ssec_params_from_headers(&headers); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[test] - fn test_extract_server_side_encryption_from_headers_rejects_invalid_utf8() { - let mut headers = http::HeaderMap::new(); - let invalid_utf8 = HeaderValue::from_bytes(b"aes:kms-\x80-invalid").unwrap(); - headers.insert("x-amz-server-side-encryption", invalid_utf8); - let result = extract_server_side_encryption_from_headers(&headers); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[test] - fn test_extract_ssekms_context_from_headers_decodes_base64_json() { - let mut headers = http::HeaderMap::new(); - let encoded = BASE64_STANDARD - .encode_to_string(serde_json::to_vec(&HashMap::from([("tenant".to_string(), "alpha".to_string())])).unwrap()); - headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT, HeaderValue::from_str(&encoded).unwrap()); - - let context = extract_ssekms_context_from_headers(&headers) - .expect("kms context header should parse") - .expect("kms context should exist"); - assert_eq!(context.get("tenant").map(String::as_str), Some("alpha")); - } - - #[test] - fn test_validate_sse_headers_for_write_rejects_algorithm_without_key() { - let algorithm = "AES256".to_string(); - let result = validate_sse_headers_for_write( - None, - None, - None, - Some(&algorithm), - None, - None, - true, // PutObject requires all three - ); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_sse_headers_for_write_rejects_algorithm_and_key_without_md5() { - let algorithm = "AES256".to_string(); - let key = "pO3upElrwuEXSoFwCfnZPdSsmt/xWeFa0N9KgDijwVs=".to_string(); - let result = validate_sse_headers_for_write( - None, - None, - None, - Some(&algorithm), - Some(&key), - None, - true, // PutObject requires all three - ); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_sse_headers_for_write_rejects_invalid_sse_algorithm() { - let bad_sse = String::from("aes:kms"); - let result = validate_sse_headers_for_write(Some(&bad_sse), None, None, None, None, None, true); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[test] - fn test_validate_sse_headers_for_write_rejects_ssec_with_managed_sse() { - let algorithm = "AES256".to_string(); - let key = "pO3upElrwuEXSoFwCfnZPdSsmt/xWeFa0N9KgDijwVs=".to_string(); - let key_md5 = "DWygnHRtgiJ77HCm+1rvHw==".to_string(); - let server_side_encryption = String::from(AMZ_ENCRYPTION_AES); - let result = validate_sse_headers_for_write( - Some(&server_side_encryption), - None, - None, - Some(&algorithm), - Some(&key), - Some(&key_md5), - true, - ); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[test] - fn test_is_managed_sse() { - assert!(is_managed_sse(&String::from("AES256"))); - assert!(is_managed_sse(&String::from("aws:kms"))); - } - - #[test] - fn test_generate_ssec_nonce() { - let nonce1 = generate_ssec_nonce("bucket1", "key1"); - let nonce2 = generate_ssec_nonce("bucket1", "key1"); - let nonce3 = generate_ssec_nonce("bucket1", "key2"); - - // Same inputs should produce same nonce - assert_eq!(nonce1, nonce2); - - // Different inputs should produce different nonce - assert_ne!(nonce1, nonce3); - - // Nonce should be exactly 12 bytes - assert_eq!(nonce1.len(), 12); - } - - #[test] - fn test_validate_ssec_params_success() { - let key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let key_md5 = md5_base64([42u8; 32]); - - let params = SsecParams { - algorithm: "AES256".to_string(), - key, - key_md5, - }; - - let result = validate_ssec_params(params); - assert!(result.is_ok()); - let validated = result.unwrap(); - assert_eq!(validated.key_bytes, [42u8; 32]); - } - - #[test] - fn test_validate_ssec_params_wrong_algorithm() { - let key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let key_md5 = md5_base64([42u8; 32]); - - let params = SsecParams { - algorithm: "AES128".to_string(), // Wrong algorithm - key, - key_md5, - }; - - let result = validate_ssec_params(params); - assert!(result.is_err()); - } - - #[test] - fn test_validate_ssec_params_wrong_key_length() { - let key = BASE64_STANDARD.encode_to_string([42u8; 16]); // Only 16 bytes - let key_md5 = md5_base64([42u8; 16]); - - let params = SsecParams { - algorithm: "AES256".to_string(), - key, - key_md5, - }; - - let result = validate_ssec_params(params); - assert!(result.is_err()); - } - - #[test] - fn test_validate_ssec_params_wrong_md5() { - let key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let key_md5 = BASE64_STANDARD.encode_to_string([99u8; 16]); // Wrong MD5 - - let params = SsecParams { - algorithm: "AES256".to_string(), - key, - key_md5, - }; - - let result = validate_ssec_params(params); - assert!(result.is_err()); - } - - #[tokio::test] - async fn test_sse_encryption_rejects_partial_ssec_headers() { - let bucket = "test-bucket"; - let key = "test-key"; - let sse_key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let sse_key_md5 = md5_base64([42u8; 32]); - let content_size = 1024; - - let request_missing_md5 = EncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(sse_key.clone()), - sse_customer_key_md5: None, - content_size, - principal: None, - }; - - let err = sse_encryption(request_missing_md5).await.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - - let request_missing_key = EncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: None, - sse_customer_key_md5: Some(sse_key_md5.clone()), - content_size, - principal: None, - }; - - let err = sse_encryption(request_missing_key).await.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - - let request_missing_algorithm = EncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: Some(sse_key), - sse_customer_key_md5: Some(sse_key_md5), - content_size, - principal: None, - }; - - let err = sse_encryption(request_missing_algorithm).await.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[tokio::test] - async fn test_sse_prepare_encryption_rejects_partial_ssec_headers() { - let bucket = "test-bucket"; - let key = "test-key"; - let sse_key_md5 = md5_base64([42u8; 32]); - - let request_missing_algorithm = PrepareEncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: Some(sse_key_md5), - principal: None, - }; - - let err = sse_prepare_encryption(request_missing_algorithm).await.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_sse_headers_for_write_allows_aws_kms_without_key_id() { - let server_side_encryption: String = "aws:kms".to_string(); - - let result = validate_sse_headers_for_write(Some(&server_side_encryption), None, None, None, None, None, true); - - assert!(result.is_ok()); - } - - #[tokio::test] - async fn test_sse_prepare_encryption_rejects_ssec_headers_without_customer_key() { - let bucket = "test-bucket"; - let key = "test-key"; - let sse_key_md5 = md5_base64([42u8; 32]); - - let request = PrepareEncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: None, - sse_customer_key_md5: Some(sse_key_md5), - principal: None, - }; - - let error = sse_prepare_encryption(request) - .await - .expect_err("multipart preparation must require possession of the customer key"); - assert_eq!(error.code, S3ErrorCode::InvalidRequest); - } - - // ------------------------------------------------------------------------ - // SSE-C Direct (default, non-`rio-v2` build) random-nonce persistence - // ------------------------------------------------------------------------ - - #[cfg(not(feature = "rio-v2"))] - async fn ssec_direct_put_metadata( - bucket: &str, - key: &str, - customer_key: &str, - customer_key_md5: &str, - ) -> HashMap { - let material = sse_encryption(EncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(customer_key.to_string()), - sse_customer_key_md5: Some(customer_key_md5.to_string()), - content_size: 128, - principal: None, - }) - .await - .expect("sse-c encryption") - .expect("sse-c material"); - assert_eq!(material.key_kind, EncryptionKeyKind::Direct); - encryption_material_to_metadata(&material).expect("sse-c metadata should serialize") - } - - // (a) Overwriting the same bucket/key under the same SSE-C key must persist a DIFFERENT - // random IV each time, and each stored IV must be read back on decrypt. This is the core - // of the fix: no (key, nonce) reuse across overwrites. - #[cfg(not(feature = "rio-v2"))] - #[tokio::test] - async fn test_ssec_direct_random_nonce_is_unique_per_put_and_read_back() { - let bucket = "bucket"; - let key = "object"; - let customer_key_bytes = [0x24u8; 32]; - let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); - let customer_key_md5 = md5_base64(customer_key_bytes); - - let metadata_one = ssec_direct_put_metadata(bucket, key, &customer_key, &customer_key_md5).await; - let metadata_two = ssec_direct_put_metadata(bucket, key, &customer_key, &customer_key_md5).await; - - let iv_one = metadata_one - .get(INTERNAL_ENCRYPTION_IV_HEADER) - .expect("first put persists a random IV"); - let iv_two = metadata_two - .get(INTERNAL_ENCRYPTION_IV_HEADER) - .expect("second put persists a random IV"); - - assert_ne!(iv_one, iv_two, "overwriting the same object must not reuse the nonce"); - - // Dual-key persistence for MinIO interop: both headers carry the same value. - assert_eq!(metadata_one.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER), Some(iv_one)); - assert_eq!(metadata_two.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER), Some(iv_two)); - - for (metadata, iv) in [(&metadata_one, iv_one), (&metadata_two, iv_two)] { - let decrypted = super::apply_ssec_decryption_material(bucket, key, metadata, &customer_key, &customer_key_md5) - .await - .expect("sse-c decryption material"); - assert_eq!( - BASE64_STANDARD.encode_to_string(decrypted.base_nonce), - *iv, - "decrypt must read the persisted random nonce back" - ); - assert_eq!(decrypted.key_bytes, customer_key_bytes); - } - } - - // (b) Legacy compatibility: objects encrypted before this change carry no IV header. Decrypt - // must fall back to the deterministic `generate_ssec_nonce(bucket, key)` they were encrypted - // with, so previously stored objects keep decrypting. - #[cfg(not(feature = "rio-v2"))] - #[tokio::test] - async fn test_ssec_direct_legacy_object_without_iv_falls_back_to_deterministic_nonce() { - let bucket = "bucket"; - let key = "object"; - let customer_key_bytes = [0x24u8; 32]; - let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); - let customer_key_md5 = md5_base64(customer_key_bytes); - - let mut metadata = HashMap::new(); - metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); - assert!(!metadata.contains_key(INTERNAL_ENCRYPTION_IV_HEADER)); - assert!(!metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_IV_HEADER)); - - let decrypted = super::apply_ssec_decryption_material(bucket, key, &metadata, &customer_key, &customer_key_md5) - .await - .expect("sse-c decryption material"); - - assert_eq!( - decrypted.base_nonce, - generate_ssec_nonce(bucket, key), - "legacy objects must decrypt via the deterministic nonce fallback" - ); - } - - // (c) Byte-level round trip: data encrypted with the material's key + persisted nonce must - // decrypt with the key + nonce resolved from the stored metadata. - #[cfg(not(feature = "rio-v2"))] - #[tokio::test] - async fn test_ssec_direct_persisted_nonce_round_trips_plaintext() { - use aes_gcm::{ - Aes256Gcm, Nonce, - aead::{Aead, KeyInit}, - }; - - let bucket = "bucket"; - let key = "object"; - let customer_key_bytes = [0x51u8; 32]; - let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); - let customer_key_md5 = md5_base64(customer_key_bytes); - let plaintext = b"attack at dawn - sse-c round trip".to_vec(); - - let metadata = ssec_direct_put_metadata(bucket, key, &customer_key, &customer_key_md5).await; - - // Encrypt with the key + nonce that were persisted at PUT time. - let enc_iv = BASE64_STANDARD - .decode_to_vec(metadata.get(INTERNAL_ENCRYPTION_IV_HEADER).expect("persisted IV")) - .expect("valid base64 IV"); - let cipher = Aes256Gcm::new_from_slice(&customer_key_bytes).expect("cipher"); - let ciphertext = cipher - .encrypt(&Nonce::try_from(enc_iv.as_slice()).expect("nonce"), plaintext.as_ref()) - .expect("encrypt"); - - // Resolve key + nonce purely from stored metadata (as decrypt does in production). - let decrypted_material = super::apply_ssec_decryption_material(bucket, key, &metadata, &customer_key, &customer_key_md5) - .await - .expect("sse-c decryption material"); - let dec_cipher = Aes256Gcm::new_from_slice(&decrypted_material.key_bytes).expect("cipher"); - let recovered = dec_cipher - .decrypt( - &Nonce::try_from(decrypted_material.base_nonce.as_slice()).expect("nonce"), - ciphertext.as_ref(), - ) - .expect("decrypt with resolved key + nonce"); - - assert_eq!(recovered, plaintext); - } - - // (d) Multipart: the random nonce generated at CreateMultipartUpload is persisted in the - // session metadata, and every part resolves the SAME nonce via `sse_decryption` on that - // session metadata. Parts must never diverge, and the value must not be deterministic. - #[cfg(not(feature = "rio-v2"))] - #[tokio::test] - async fn test_ssec_direct_multipart_all_parts_share_one_persisted_nonce() { - let bucket = "bucket"; - let key = "object"; - let customer_key_bytes = [0x33u8; 32]; - let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); - let customer_key_md5 = md5_base64(customer_key_bytes); - - let material = sse_prepare_encryption(PrepareEncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(customer_key.clone()), - sse_customer_key_md5: Some(customer_key_md5.clone()), - principal: None, - }) - .await - .expect("prepare ssec") - .expect("prepare material"); - assert_eq!(material.key_kind, EncryptionKeyKind::Direct); - - let session_metadata = encryption_material_to_metadata(&material).expect("session metadata should serialize"); - let session_iv = session_metadata - .get(INTERNAL_ENCRYPTION_IV_HEADER) - .expect("multipart session persists a random IV") - .clone(); - // Random, not the deterministic bucket/key derivation. - assert_ne!( - BASE64_STANDARD.decode_to_vec(&session_iv).expect("valid IV")[..], - generate_ssec_nonce(bucket, key)[..] - ); - - let resolve_part_nonce = |part_number: usize| { - let session_metadata = session_metadata.clone(); - let customer_key = customer_key.clone(); - let customer_key_md5 = customer_key_md5.clone(); - async move { - let _ = part_number; - sse_decryption(DecryptionRequest { - bucket, - key, - metadata: &session_metadata, - sse_customer_key: Some(&customer_key), - sse_customer_key_md5: Some(&customer_key_md5), - principal: None, - }) - .await - .expect("part decryption") - .expect("part material") - .base_nonce - } - }; - - let part_one_nonce = resolve_part_nonce(1).await; - let part_two_nonce = resolve_part_nonce(2).await; - - assert_eq!(part_one_nonce, part_two_nonce, "all parts of one upload must share the persisted nonce"); - assert_eq!(BASE64_STANDARD.encode_to_string(part_one_nonce), session_iv); - } - - #[cfg(feature = "rio-v2")] - #[tokio::test] - async fn test_sse_prepare_encryption_ssec_with_customer_key_stores_sealed_key_metadata() { - let bucket = "test-bucket"; - let key = "test-key"; - let customer_key_bytes = [0x24u8; 32]; - let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); - let sse_key_md5 = md5_base64(customer_key_bytes); - - let request = PrepareEncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(customer_key), - sse_customer_key_md5: Some(sse_key_md5), - principal: None, - }; - - let material = sse_prepare_encryption(request) - .await - .expect("prepare should accept full ssec headers") - .expect("ssec metadata should be generated"); - assert_eq!(material.key_kind, EncryptionKeyKind::Object); - - let metadata = encryption_material_to_metadata(&material).expect("ssec metadata should serialize"); - assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_IV_HEADER)); - assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)); - } - - #[test] - fn test_encryption_material_to_metadata_persists_ssec_original_size() { - let metadata = encryption_material_to_metadata(&EncryptionMaterial { - sse_type: SSEType::SseC, - server_side_encryption: String::from(AMZ_ENCRYPTION_AES), - kms_key_id: None, - algorithm: "AES256".to_string(), - key_bytes: [0u8; 32], - base_nonce: [0u8; 12], - encrypted_data_key: None, - customer_key_md5: Some("d41d8cd98f00b204e9800998ecf8427e".to_string()), - original_size: Some(1024), - key_kind: EncryptionKeyKind::Direct, - managed_kms_context: None, - managed_sealed_key: None, - }) - .expect("ssec original-size metadata should serialize"); - - assert_eq!(metadata.get(SSEC_ORIGINAL_SIZE_HEADER).map(String::as_str), Some("1024")); - } - - fn material_variant(sse_type: SSEType, key_kind: EncryptionKeyKind) -> EncryptionMaterial { - let (server_side_encryption, kms_key_id, encrypted_data_key, customer_key_md5, managed_kms_context) = match sse_type { - SSEType::SseC => ( - String::from(AMZ_ENCRYPTION_AES), - None, - None, - Some("d41d8cd98f00b204e9800998ecf8427e".to_string()), - None, - ), - SSEType::SseS3 => (String::from(AMZ_ENCRYPTION_AES), None, Some(vec![0u8; 32]), None, None), - SSEType::SseKms => ( - String::from(AMZ_ENCRYPTION_KMS), - Some("kms-key-1".to_string()), - Some(vec![0u8; 32]), - None, - Some(HashMap::from([("app".to_string(), "test".to_string())])), - ), - }; - EncryptionMaterial { - sse_type, - server_side_encryption, - kms_key_id, - algorithm: "AES256".to_string(), - key_bytes: [0u8; 32], - base_nonce: [0u8; 12], - encrypted_data_key, - customer_key_md5, - original_size: Some(1024), - key_kind, - managed_kms_context, - managed_sealed_key: None, - } - } - - #[test] - fn native_request_debug_withholds_encryption_customer_key() { - let mut request = managed_write(AMZ_ENCRYPTION_AES, None); - request.sse_customer_key = Some("fixture-key-must-stay-private".to_owned()); - let diagnostic = format!("{request:?}"); - assert!(!diagnostic.contains("sse_customer_key"), "customer keys must not be debug fields"); - } - - #[test] - fn native_request_debug_withholds_decryption_customer_key() { - let metadata = HashMap::new(); - let key = "fixture-key-must-stay-private".to_owned(); - let request = DecryptionRequest { - bucket: "bucket", - key: "object", - metadata: &metadata, - sse_customer_key: Some(&key), - sse_customer_key_md5: None, - principal: None, - }; - let diagnostic = format!("{request:?}"); - assert!(!diagnostic.contains("sse_customer_key"), "customer keys must not be debug fields"); - } - - #[test] - fn native_material_debug_withholds_encryption_keys() { - let material = material_variant(SSEType::SseC, EncryptionKeyKind::Direct); - let diagnostic = format!("{material:?}"); - assert!( - !diagnostic.contains("key_bytes") - && !diagnostic.contains("encrypted_data_key") - && !diagnostic.contains("managed_sealed_key"), - "encryption keys must not be debug fields" - ); - } - - #[test] - fn native_material_debug_withholds_decryption_keys() { - let material = DecryptionMaterial { - sse_type: SSEType::SseC, - server_side_encryption: String::from(AMZ_ENCRYPTION_AES), - kms_key_id: None, - algorithm: "AES256".to_owned(), - customer_key_md5: None, - key_bytes: [0; 32], - base_nonce: [0; 12], - key_kind: EncryptionKeyKind::Direct, - }; - let diagnostic = format!("{material:?}"); - assert!(!diagnostic.contains("key_bytes"), "decryption keys must not be debug fields"); - } - - #[test] - fn native_material_debug_withholds_customer_key() { - let material = - super::SseTypeV2::SseC("AES256".to_owned(), "fixture-key-must-stay-private".to_owned(), "fixture-md5".to_owned()); - let diagnostic = format!("{material:?}"); - assert!( - !diagnostic.contains("fixture-key-must-stay-private"), - "customer keys must not appear in diagnostics" - ); - } - - /// Reconciliation contract with the replication boundary (backlog#1783): - /// every metadata key this module persists must either be remapped by the - /// SSE-C transport table or be caught by the replication strip predicate. - /// A new stored key that is in neither turns this test red before it can - /// silently leak through outbound replication metadata. - #[test] - fn test_encryption_metadata_keys_reconcile_with_replication_transport_and_strip() { - use rustfs_utils::http::object_encryption_keys::{ - is_replication_stripped_encryption_key, ssec_replication_transport_header, - }; - - let variants = [ - (SSEType::SseC, EncryptionKeyKind::Direct), - (SSEType::SseS3, EncryptionKeyKind::Direct), - (SSEType::SseKms, EncryptionKeyKind::Direct), - ]; - - for (sse_type, key_kind) in variants { - let metadata = encryption_material_to_metadata(&material_variant(sse_type, key_kind)) - .expect("encryption material should serialize"); - assert!(!metadata.is_empty()); - - for key in metadata.keys() { - assert!( - ssec_replication_transport_header(key).is_some() || is_replication_stripped_encryption_key(key), - "stored key {key} ({sse_type:?}/{key_kind:?}) is neither transport-mapped nor stripped for replication" - ); - if !matches!(sse_type, SSEType::SseC) { - // Managed SSE never takes the transport mapping; every key - // must be structurally stripped so envelopes cannot leave - // the source site. - assert!( - is_replication_stripped_encryption_key(key), - "managed-SSE stored key {key} ({sse_type:?}) escapes the replication strip predicate" - ); - } - } - } - } - - #[tokio::test] - async fn test_sse_encryption_rejects_kms_key_with_invalid_algorithm() { - let bucket = "test-bucket"; - let key = "test-key"; - let content_size = 1024; - - let request = EncryptionRequest { - bucket, - key, - server_side_encryption: Some("AES256".to_string()), - ssekms_key_id: Some("test-key".to_string()), - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size, - principal: None, - }; - - let err = sse_encryption(request).await.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[tokio::test] - async fn test_sse_encryption_rejects_kms_key_without_algorithm() { - let bucket = "test-bucket"; - let key = "test-key"; - let content_size = 1024; - - let request = EncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: Some("test-key".to_string()), - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size, - principal: None, - }; - - let err = sse_encryption(request).await.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[tokio::test] - async fn test_sse_encryption_rejects_conflict_between_kms_and_ssec() { - let bucket = "test-bucket"; - let key = "test-key"; - let content_size = 1024; - let sse_key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let sse_key_md5 = md5_base64([42u8; 32]); - - let request = EncryptionRequest { - bucket, - key, - server_side_encryption: Some("aws:kms".to_string()), - ssekms_key_id: Some("test-key".to_string()), - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(sse_key), - sse_customer_key_md5: Some(sse_key_md5), - content_size, - principal: None, - }; - - let err = sse_encryption(request).await.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[test] - fn test_resolve_effective_kms_key_id_ignores_bucket_default_for_explicit_sse_s3() { - let effective_sse = String::from(AMZ_ENCRYPTION_AES); - - let kms_key_id = resolve_effective_kms_key_id(Some(&effective_sse), None, || Some("bucket-default".to_string())); - - assert_eq!(kms_key_id, None); - } - - #[test] - fn test_resolve_effective_kms_key_id_uses_bucket_default_for_sse_kms() { - let effective_sse = String::from(AMZ_ENCRYPTION_KMS); - - let kms_key_id = resolve_effective_kms_key_id(Some(&effective_sse), None, || Some("bucket-default".to_string())); - - assert_eq!(kms_key_id.as_deref(), Some("bucket-default")); - } - - /// One recorded rewrap call: (envelope bytes, bucket, object key, context). - type RecordedRewrapCall = (Vec, String, String, HashMap); - - /// Test double for the rewrap seam: records what it was asked to rewrap - /// and answers with a canned response. - struct RewrapProbeProvider { - rewrapped: bool, - new_ciphertext: Vec, - calls: std::sync::Mutex>, - } - - #[async_trait] - impl SseDekProvider for RewrapProbeProvider { - async fn generate_sse_dek( - &self, - _context: &ObjectEncryptionContext, - _kms_key_id: &str, - ) -> Result<(DataKey, Vec), ApiError> { - unreachable!("rewrap tests never generate keys") - } - - async fn decrypt_sse_dek( - &self, - _encrypted_dek: &[u8], - _kms_key_id: &str, - _context: &ObjectEncryptionContext, - ) -> Result<[u8; 32], ApiError> { - unreachable!("rewrap tests never decrypt keys") - } - - async fn rewrap_sse_dek( - &self, - encrypted_dek: &[u8], - context: &ObjectEncryptionContext, - ) -> Result { - self.calls.lock().expect("probe lock").push(( - encrypted_dek.to_vec(), - context.bucket.clone(), - context.object_key.clone(), - context.encryption_context.clone(), - )); - Ok(rustfs_kms::types::RewrapDataKeyResponse { - ciphertext: if self.rewrapped { - self.new_ciphertext.clone() - } else { - encrypted_dek.to_vec() - }, - key_id: "probe-key".to_string(), - source_key_version: Some(1), - destination_key_version: Some(2), - rewrapped: self.rewrapped, - }) - } - } - - /// A minimal but well-formed data-key envelope, the shape - /// `is_data_key_envelope` recognizes. - fn probe_envelope_json() -> Vec { - serde_json::to_vec(&serde_json::json!({ - "key_id": "dek-id", - "master_key_id": "master-key", - "key_spec": "AES_256", - "encrypted_key": [1, 2, 3, 4], - "nonce": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], - "encryption_context": {"bucket": "bucket/dir/object"}, - "created_at": "2024-01-01T00:00:00+00:00" - })) - .expect("serialize probe envelope") - } - - /// The adapter must replace every stored copy of the old envelope — under - /// whatever key casing the storage layer preserved — and leave slots - /// holding different bytes (a sealed object key) untouched. Its context - /// must be rebuilt exactly as the managed decrypt path rebuilds it. - #[tokio::test] - async fn rewrap_object_metadata_replaces_every_stored_envelope_copy() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - let envelope = probe_envelope_json(); - let envelope_b64 = BASE64_STANDARD.encode_to_string(&envelope); - let client_context = HashMap::from([("tenant".to_string(), "alpha".to_string())]); - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()), - // Mixed casing on the internal header, exactly as the storage layer - // can hand it back. - ("X-Rustfs-Encryption-Key".to_string(), envelope_b64.clone()), - (MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), envelope_b64.clone()), - // A sealed object key: different bytes, must not be rewritten. - ( - MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(b"sealed-object-key-not-the-envelope"), - ), - ( - MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), - encode_minio_kms_context(&client_context).expect("encode context"), - ), - ]); - - let new_ciphertext = b"rewrapped-envelope-bytes".to_vec(); - let provider = Arc::new(RewrapProbeProvider { - rewrapped: true, - new_ciphertext: new_ciphertext.clone(), - calls: std::sync::Mutex::new(Vec::new()), - }); - super::set_sse_dek_provider_for_test(provider.clone()); - - let outcome = rewrap_object_encryption_metadata("bucket", "dir/object", &metadata) - .await - .expect("rewrap must succeed"); - let ObjectDekRewrapOutcome::Rewrapped { metadata: overrides } = outcome else { - panic!("expected a rewrapped outcome, got {outcome:?}"); - }; - - let new_b64 = BASE64_STANDARD.encode_to_string(&new_ciphertext); - assert_eq!( - overrides, - HashMap::from([ - ("X-Rustfs-Encryption-Key".to_string(), new_b64.clone()), - (MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), new_b64), - ]), - "every envelope copy must be replaced under its stored name and nothing else touched" - ); - - let calls = provider.calls.lock().expect("probe lock"); - let (sent_envelope, bucket, object_key, sent_context) = calls.first().expect("the provider must be called"); - assert_eq!(*sent_envelope, envelope, "the decoded stored envelope must reach the provider"); - assert_eq!(bucket, "bucket"); - assert_eq!(object_key, "dir/object"); - assert_eq!( - *sent_context, - build_kms_request_context("bucket", "dir/object", Some(&client_context)), - "the context must be rebuilt exactly as the managed decrypt path rebuilds it" - ); - - reset_sse_dek_provider(); - } - - /// `rewrapped: false` from the backend means nothing to persist; the - /// adapter must answer AlreadyCurrent so a sweep re-run converges. - #[tokio::test] - async fn rewrap_object_metadata_converges_when_already_current() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - let envelope_b64 = BASE64_STANDARD.encode_to_string(probe_envelope_json()); - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), "AES256".to_string()), - (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), envelope_b64), - ]); - let provider = Arc::new(RewrapProbeProvider { - rewrapped: false, - new_ciphertext: Vec::new(), - calls: std::sync::Mutex::new(Vec::new()), - }); - super::set_sse_dek_provider_for_test(provider.clone()); - - let outcome = rewrap_object_encryption_metadata("bucket", "object", &metadata) - .await - .expect("rewrap must succeed"); - assert!(matches!(outcome, ObjectDekRewrapOutcome::AlreadyCurrent), "got {outcome:?}"); - assert_eq!(provider.calls.lock().expect("probe lock").len(), 1); - - reset_sse_dek_provider(); - } - - /// The KMS-backed provider's rewrap threads through the encryption - /// service to the backend. The Local test backend has no rewrap support, - /// so the capability refusal coming back proves the whole chain is wired — - /// a stub that silently succeeded would return Ok here. - #[tokio::test] - async fn kms_provider_rewrap_reaches_the_backend_through_the_service() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - let manager = configure_test_global_local_kms().await; - let provider = KmsSseDekProvider::new_with_service_manager(manager) - .await - .expect("kms provider should initialize from the configured test manager"); - - let context = super::build_object_encryption_context("bucket", "object", None); - let error = provider - .rewrap_sse_dek(b"{}", &context) - .await - .expect_err("the Local backend must refuse rewrap through the full chain"); - assert!( - error.to_string().contains("rewrap") || format!("{:?}", error.source).contains("rewrap_data_key"), - "the refusal must come from the backend capability gate: {error:?}" - ); - - reset_sse_dek_provider(); - } - - /// A write whose resolved key — from the request header or a bucket - /// default rule — is unknown to the KMS must come back as the client - /// error S3 uses for it, all the way from the backend lookup. Answering - /// 500 here made a bucket default pointing at a deleted or mistyped key - /// look like a server outage (rustfs/backlog#2330, KMS-312). - #[tokio::test] - async fn kms_provider_reports_an_unknown_key_as_kms_not_found() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - let manager = configure_test_global_local_kms().await; - let provider = KmsSseDekProvider::new_with_service_manager(manager) - .await - .expect("kms provider should initialize from the configured test manager"); - - let context = super::build_object_encryption_context("bucket", "object", None); - let error = provider - .generate_sse_dek(&context, "no-such-key") - .await - .expect_err("the Local backend must refuse a key it does not hold"); - assert_eq!( - error.code, - S3ErrorCode::Custom(crate::error::KMS_KEY_NOT_FOUND_ERROR_CODE.into()), - "got {error:?}" - ); - assert!(error.message.contains("no-such-key"), "the missing key must be named: {error:?}"); - assert_eq!(super::kms_data_plane_error_class(&error), "key_not_found"); - - reset_sse_dek_provider(); - } - - /// Objects without a rewrappable envelope — plaintext, SSE-C, or a - /// MinIO-sealed opaque data key — are reported NotApplicable without any - /// provider call. - #[tokio::test] - async fn rewrap_object_metadata_skips_objects_without_a_rustfs_envelope() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - let provider = Arc::new(RewrapProbeProvider { - rewrapped: true, - new_ciphertext: b"never-used".to_vec(), - calls: std::sync::Mutex::new(Vec::new()), - }); - super::set_sse_dek_provider_for_test(provider.clone()); - - // Plaintext object. - let outcome = rewrap_object_encryption_metadata("bucket", "object", &HashMap::new()) - .await - .expect("plaintext objects must not error"); - assert!(matches!(outcome, ObjectDekRewrapOutcome::NotApplicable), "got {outcome:?}"); - - // SSE-C object: customer-key encryption never reaches KMS. - let ssec = HashMap::from([ - ("X-Amz-Server-Side-Encryption-Customer-Algorithm".to_string(), "AES256".to_string()), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([1u8; 12])), - ]); - let outcome = rewrap_object_encryption_metadata("bucket", "object", &ssec) - .await - .expect("SSE-C objects must not error"); - assert!(matches!(outcome, ObjectDekRewrapOutcome::NotApplicable), "got {outcome:?}"); - - // MinIO builtin-KMS ciphertext: opaque bytes, not a RustFS envelope. - let minio = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()), - ( - MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(b"opaque-minio-sealed-bytes"), - ), - ]); - let outcome = rewrap_object_encryption_metadata("bucket", "object", &minio) - .await - .expect("MinIO-sealed objects must not error"); - assert!(matches!(outcome, ObjectDekRewrapOutcome::NotApplicable), "got {outcome:?}"); - - assert!( - provider.calls.lock().expect("probe lock").is_empty(), - "no provider call may happen for non-rewrappable objects" - ); - - reset_sse_dek_provider(); - } - - #[tokio::test] - async fn test_sse_encryption_persists_aws_kms_header_for_kms_objects() { - let material = EncryptionMaterial { - sse_type: SSEType::SseKms, - server_side_encryption: String::from(AMZ_ENCRYPTION_KMS), - kms_key_id: Some("test-key".to_string()), - algorithm: AMZ_ENCRYPTION_KMS.to_string(), - key_bytes: [7u8; 32], - base_nonce: [9u8; 12], - encrypted_data_key: Some(vec![1, 2, 3, 4]), - customer_key_md5: None, - original_size: Some(1024), - key_kind: EncryptionKeyKind::Direct, - managed_kms_context: None, - managed_sealed_key: None, - }; - // Only an aws:kms object names its key in write responses. - assert_eq!(material.response_kms_key_id().as_deref(), Some("test-key")); - let metadata = encryption_material_to_metadata(&material).expect("managed SSE metadata should serialize"); - - assert_eq!(metadata.get("x-amz-server-side-encryption").map(String::as_str), Some("aws:kms")); - assert_eq!( - metadata - .get("x-amz-server-side-encryption-aws-kms-key-id") - .map(String::as_str), - Some("test-key") - ); - } - - #[cfg(feature = "rio-v2")] - #[tokio::test] - async fn test_sse_kms_roundtrip_persists_and_uses_minio_context() { - use rustfs_kms::types::{CreateKeyRequest, KeyUsage}; - let _guard = lock_sse_test_state().await; - - reset_sse_dek_provider(); - let manager = configure_test_global_local_kms().await; - manager - .get_encryption_service() - .await - .expect("encryption service should exist") - .create_key(CreateKeyRequest { - key_name: Some("kms-test".to_string()), - key_usage: KeyUsage::EncryptDecrypt, - description: None, - policy: None, - tags: HashMap::new(), - origin: None, - }) - .await - .expect("kms test key should be created"); - - let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) - .await - .expect("kms provider should initialize from the configured test manager"); - super::set_sse_dek_provider_for_test(Arc::new(provider)); - - let client_context = HashMap::from([("tenant".to_string(), "alpha".to_string())]); - let request = EncryptionRequest { - bucket: "bucket", - key: "dir/object", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), - ssekms_key_id: Some("kms-test".to_string()), - ssekms_context: Some(client_context.clone()), - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 4096, - principal: None, - }; - - let material = sse_encryption(request) - .await - .expect("sse-kms encryption") - .expect("managed sse-kms material"); - let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); - let encoded_context = metadata - .get(MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER) - .expect("minio kms context header should exist"); - let decoded_context: HashMap = - serde_json::from_slice(&BASE64_STANDARD.decode_to_vec(encoded_context).expect("decode base64 context")) - .expect("decode json context"); - assert_eq!(decoded_context, client_context); - - let decrypted = sse_decryption(DecryptionRequest { - bucket: "bucket", - key: "dir/object", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect("sse-kms decryption should succeed") - .expect("sse-kms material should exist"); - assert_eq!(decrypted.key_bytes, material.key_bytes); - - let mut wrong_metadata = metadata.clone(); - wrong_metadata.insert( - MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), - BASE64_STANDARD - .encode_to_string(serde_json::to_vec(&HashMap::from([("tenant".to_string(), "beta".to_string())])).unwrap()), - ); - let err = sse_decryption(DecryptionRequest { - bucket: "bucket", - key: "dir/object", - metadata: &wrong_metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect_err("mismatched kms context should fail"); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - assert_eq!( - err.message, - "Encryption context mismatch: Context mismatch for key 'tenant': expected 'alpha', got 'beta'" - ); - assert_eq!(super::kms_data_plane_error_class(&err), "context_mismatch"); - - manager.stop().await.expect("kms service should stop cleanly"); - reset_sse_dek_provider(); - } - - #[cfg(feature = "rio-v2")] - #[test] - fn test_encryption_material_to_metadata_persists_minio_managed_headers() { - let encoded_nonce = BASE64_STANDARD.encode_to_string([9u8; 12]); - let encoded_key = BASE64_STANDARD.encode_to_string([1u8, 2, 3, 4]); - let metadata = encryption_material_to_metadata(&EncryptionMaterial { - sse_type: SSEType::SseKms, - server_side_encryption: String::from(AMZ_ENCRYPTION_KMS), - kms_key_id: Some("test-key".to_string()), - algorithm: AMZ_ENCRYPTION_KMS.to_string(), - key_bytes: [7u8; 32], - base_nonce: [9u8; 12], - encrypted_data_key: Some(vec![1, 2, 3, 4]), - customer_key_md5: None, - original_size: Some(1024), - key_kind: EncryptionKeyKind::Direct, - managed_kms_context: None, - managed_sealed_key: None, - }) - .expect("managed SSE metadata should serialize"); - - assert_eq!( - metadata.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER).map(String::as_str), - Some(encoded_nonce.as_str()) - ); - assert_eq!( - metadata - .get(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER) - .map(String::as_str), - Some(encoded_key.as_str()) - ); - assert_eq!( - metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER).map(String::as_str), - Some("test-key") - ); - assert_eq!( - metadata.get(MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER).map(String::as_str), - Some(MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM) - ); - } - - #[tokio::test] - async fn test_sse_encryption_omits_kms_header_for_sse_s3_objects() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - let local_sse_master_key = local_sse_master_key_b64(); - - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), - ("RUSTFS_SSE_S3_MASTER_KEY", Some(local_sse_master_key.as_str())), - ], - async { - let request = EncryptionRequest { - bucket: "test-bucket", - key: "test-key", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 1024, - principal: None, - }; - - let material = sse_encryption(request).await.expect("sse-s3 encryption should succeed"); - let material = material.expect("managed sse-s3 encryption should return material"); - let metadata = encryption_material_to_metadata(&material).expect("managed SSE-S3 metadata should serialize"); - - assert_eq!(material.kms_key_id.as_deref(), Some("default")); - // The wrapping key stays internal: no write response may - // advertise it for an AES256 object. - assert_eq!(material.response_kms_key_id(), None); - assert_eq!(metadata.get("x-amz-server-side-encryption").map(String::as_str), Some("AES256")); - assert!(!metadata.contains_key("x-amz-server-side-encryption-aws-kms-key-id")); - assert_eq!(metadata.get(INTERNAL_ENCRYPTION_KEY_ID_HEADER).map(String::as_str), Some("default")); - }, - ) - .await; - - reset_sse_dek_provider(); - } - - #[test] - fn test_strip_managed_encryption_metadata() { - let mut metadata = HashMap::new(); - metadata.insert("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()); - metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); - metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), "source-key-md5".to_string()); - metadata.insert(SSEC_ORIGINAL_SIZE_HEADER.to_string(), "123".to_string()); - metadata.insert("x-rustfs-encryption-key".to_string(), "encrypted_key".to_string()); - metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), "sealed".to_string()); - metadata.insert("content-type".to_string(), "text/plain".to_string()); - - strip_managed_encryption_metadata(&mut metadata); - - assert!(!metadata.contains_key("x-amz-server-side-encryption")); - assert!(!metadata.contains_key("x-amz-server-side-encryption-customer-algorithm")); - assert!(!metadata.contains_key("x-amz-server-side-encryption-customer-key-md5")); - assert!(!metadata.contains_key(SSEC_ORIGINAL_SIZE_HEADER)); - assert!(!metadata.contains_key("x-rustfs-encryption-key")); - assert!(!metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER)); - assert!(metadata.contains_key("content-type")); - } - - /// A copy destination must not inherit any key that `is_object_encryption_marker` - /// accepts as proof the payload is encrypted. - /// - /// Guards this chain: `ObjectInfo::is_encrypted` is keyed on that predicate, so a - /// single leftover marker makes a plaintext destination report itself encrypted. - /// `object_api::readers` then takes its encrypted branch and demands read material, - /// but the material itself was stripped, so `sse_decryption` reports no encryption - /// and the read fails closed on unresolvable encryption metadata — a destination - /// that CopyObject wrote successfully becomes permanently unreadable. - #[test] - fn test_strip_managed_encryption_metadata_clears_encryption_markers() { - let mut metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()), - ("x-amz-server-side-encryption-aws-kms-key-id".to_string(), "source-key".to_string()), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "source-key".to_string()), - (INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), "AES256".to_string()), - (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), "wrapped-dek".to_string()), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), "base-nonce".to_string()), - ("content-type".to_string(), "text/plain".to_string()), - ]); - - strip_managed_encryption_metadata(&mut metadata); - - let inherited: Vec<&str> = metadata - .keys() - .filter(|key| rustfs_utils::http::is_object_encryption_marker(key)) - .map(String::as_str) - .collect(); - assert!(inherited.is_empty(), "copy destination inherited encryption markers: {inherited:?}"); - assert!(metadata.contains_key("content-type")); - } - - /// A same-name CopyObject is normally serviced as a metadata-only update that reuses the - /// stored ciphertext, while the handler rebuilds the destination metadata around a *fresh* - /// DEK. `ObjectInfo::is_encrypted` — i.e. `is_object_encryption_marker` — is the guard that - /// keeps that shortcut away from encrypted objects (see the `metadata_only` decision in - /// `rustfs/src/app/object_usecase.rs`). Any encryption flavour whose headers - /// `strip_managed_encryption_metadata` drops must therefore also be *detected* there — a - /// flavour that is stripped but not detected would resurrect "new DEK + old ciphertext", - /// which leaves the object permanently undecryptable. - #[test] - fn every_strippable_encryption_shape_is_detected_as_encrypted() { - let shapes: [(&str, Vec<(&str, &str)>); 4] = [ - ( - "sse-s3", - vec![ - ("x-amz-server-side-encryption", "AES256"), - (MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER, "sealed"), - (MINIO_INTERNAL_ENCRYPTION_IV_HEADER, "iv"), - ], - ), - ( - "sse-kms", - vec![ - ("x-amz-server-side-encryption", "aws:kms"), - (MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER, "sealed"), - (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER, "key-1"), - ], - ), - ( - "legacy rustfs managed", - vec![ - ("x-amz-server-side-encryption", "AES256"), - (INTERNAL_ENCRYPTION_KEY_HEADER, "wrapped"), - (INTERNAL_ENCRYPTION_IV_HEADER, "iv"), - ], - ), - ( - "sse-c", - vec![ - (SSEC_ALGORITHM_HEADER, "AES256"), - (MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER, "sealed"), - ], - ), - ]; - - for (label, entries) in shapes { - let metadata: HashMap = entries - .iter() - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) - .collect(); - - assert!( - metadata - .keys() - .any(|key| rustfs_utils::http::is_object_encryption_marker(key)), - "{label}: an encrypted object must be detected, otherwise a same-name copy would re-key it \ - without rewriting the ciphertext" - ); - - let mut stripped = metadata.clone(); - strip_managed_encryption_metadata(&mut stripped); - assert_ne!( - stripped, metadata, - "{label}: the copy path strips this shape's encryption metadata, so the destination cannot \ - reuse the source ciphertext" - ); - } - } - - #[test] - fn plain_object_metadata_is_not_flagged_as_encrypted() { - // The metadata-only self-copy shortcut must stay available for unencrypted objects. - let metadata: HashMap = [("content-type", "text/plain"), ("x-amz-meta-stage", "before")] - .iter() - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) - .collect(); - - assert!( - !metadata - .keys() - .any(|key| rustfs_utils::http::is_object_encryption_marker(key)) - ); - } - - #[cfg(feature = "rio-v2")] - #[test] - fn test_legacy_managed_metadata_excludes_sealed_keys() { - let legacy_metadata = HashMap::from([ - (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), "encrypted-dek".to_string()), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), "nonce".to_string()), - ]); - assert!(is_legacy_rustfs_managed_metadata(&legacy_metadata)); - - let sealed_metadata = HashMap::from([ - (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), "encrypted-dek".to_string()), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), "nonce".to_string()), - (MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(), "sealed-key".to_string()), - ]); - assert!(!is_legacy_rustfs_managed_metadata(&sealed_metadata)); - } - - #[cfg(feature = "rio-v2")] - #[test] - fn test_normalize_managed_metadata_accepts_minio_only_headers() { - let metadata = HashMap::from([ - ( - MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(b"encrypted-key"), - ), - ( - MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(), - BASE64_STANDARD.encode_to_string([0x11u8; 12]), - ), - ( - MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), - MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.to_string(), - ), - (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_string(), "default".to_string()), - ]); - - let normalized = normalize_managed_metadata(&metadata, Some(recode_minio_kms_context)); - - assert_eq!( - normalized.get(INTERNAL_ENCRYPTION_KEY_HEADER), - Some(&BASE64_STANDARD.encode_to_string(b"encrypted-key")) - ); - assert_eq!( - normalized.get(INTERNAL_ENCRYPTION_IV_HEADER), - Some(&BASE64_STANDARD.encode_to_string([0x11u8; 12])) - ); - assert_eq!( - normalized.get(INTERNAL_ENCRYPTION_ALGORITHM_HEADER), - Some(&MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.to_string()) - ); - assert_eq!(normalized.get(INTERNAL_ENCRYPTION_KEY_ID_HEADER), Some(&"default".to_string())); - } - - #[cfg(feature = "rio-v2")] - #[tokio::test] - async fn test_managed_sse_rio_v2_uses_object_key_metadata_roundtrip() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - if let Some(manager) = rustfs_kms::get_global_kms_service_manager() { - let _ = manager.stop().await; - } - let local_sse_master_key = local_sse_master_key_b64(); - - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), - ("RUSTFS_SSE_S3_MASTER_KEY", Some(local_sse_master_key.as_str())), - ], - async { - let request = EncryptionRequest { - bucket: "bucket", - key: "object", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 4096, - principal: None, - }; - - let material = sse_encryption(request) - .await - .expect("managed sse encryption") - .expect("managed sse material"); - assert_eq!(material.key_kind, EncryptionKeyKind::Object); - - let metadata = encryption_material_to_metadata(&material).expect("managed SSE metadata should serialize"); - assert!(!metadata.contains_key(INTERNAL_ENCRYPTION_KEY_HEADER)); - assert!(!metadata.contains_key(INTERNAL_ENCRYPTION_IV_HEADER)); - - let sealing_iv = metadata - .get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER) - .expect("minio sealing iv should be stored"); - let sealed_key = metadata - .get(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER) - .expect("minio sealed key should be stored"); - assert_eq!(BASE64_STANDARD.decode_to_vec(sealing_iv).expect("decode iv").len(), SEALED_KEY_IV_SIZE); - assert_eq!( - BASE64_STANDARD.decode_to_vec(sealed_key).expect("decode sealed key").len(), - SEALED_KEY_SIZE - ); - - let decrypted = sse_decryption(DecryptionRequest { - bucket: "bucket", - key: "object", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect("managed sse decryption") - .expect("managed decryption material"); - - assert_eq!(decrypted.key_kind, EncryptionKeyKind::Object); - assert_eq!(decrypted.key_bytes, material.key_bytes); - - let resolved = SseObjectEncryptionResolver - .resolve_read_material(ReadEncryptionRequest { - bucket: "bucket", - object: "object", - metadata: &metadata, - headers: &HeaderMap::new(), - }) - .await - .expect("managed resolver") - .expect("managed material"); - assert_eq!(resolved.mode, ReadEncryptionMode::Object); - assert_eq!(resolved.key_bytes, material.key_bytes); - }, - ) - .await; - - reset_sse_dek_provider(); - } - - #[cfg(feature = "rio-v2")] - #[test] - fn test_supported_sealed_object_key_cipher_accepts_current_minio_fixture_value() { - assert!(is_supported_sealed_object_key_cipher(DARE_CIPHER_AES_256_GCM)); - assert!(is_supported_sealed_object_key_cipher(DARE_CIPHER_CHACHA20_POLY1305)); - assert!(!is_supported_sealed_object_key_cipher(0x02)); - } - - #[cfg(feature = "rio-v2")] - #[tokio::test] - async fn test_ssec_rio_v2_uses_sealed_object_key_metadata_roundtrip() { - let customer_key_bytes = [0x42u8; 32]; - let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); - let customer_key_md5 = md5_base64(customer_key_bytes); - - let material = sse_encryption(EncryptionRequest { - bucket: "bucket", - key: "object", - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(customer_key.clone()), - sse_customer_key_md5: Some(customer_key_md5.clone()), - content_size: 4096, - principal: None, - }) - .await - .expect("sse-c encryption") - .expect("sse-c material"); - - assert_eq!(material.key_kind, EncryptionKeyKind::Object); - - let metadata = encryption_material_to_metadata(&material).expect("sse-c metadata should serialize"); - assert_eq!( - metadata.get(MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER).map(String::as_str), - Some(MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM) - ); - assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_IV_HEADER)); - assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)); - - let decrypted = sse_decryption(DecryptionRequest { - bucket: "bucket", - key: "object", - metadata: &metadata, - sse_customer_key: Some(&customer_key), - sse_customer_key_md5: Some(&customer_key_md5), - principal: None, - }) - .await - .expect("sse-c decryption") - .expect("sse-c decryption material"); - - assert_eq!(decrypted.key_kind, EncryptionKeyKind::Object); - assert_eq!(decrypted.key_bytes, material.key_bytes); - - let mut headers = HeaderMap::new(); - headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static("AES256")); - headers.insert( - "x-amz-server-side-encryption-customer-key", - HeaderValue::from_str(&customer_key).expect("customer key header"), - ); - headers.insert( - "x-amz-server-side-encryption-customer-key-md5", - HeaderValue::from_str(&customer_key_md5).expect("customer key MD5 header"), - ); - let resolved = SseObjectEncryptionResolver - .resolve_read_material(ReadEncryptionRequest { - bucket: "bucket", - object: "object", - metadata: &metadata, - headers: &headers, - }) - .await - .expect("SSE-C resolver") - .expect("SSE-C material"); - assert_eq!(resolved.mode, ReadEncryptionMode::Object); - assert_eq!(resolved.key_bytes, material.key_bytes); - } - - /// Rewrites rio-v2 SSE-C metadata into the shape MinIO actually persists: - /// only the internal sealed-key slot, IV, and seal algorithm — the public - /// scheme, customer-algorithm, and customer-key-MD5 keys are synthesized - /// onto responses by MinIO and never hit disk (backlog#1638). - #[cfg(feature = "rio-v2")] - fn strip_to_minio_ssec_shape(metadata: &mut HashMap) { - metadata.remove("x-amz-server-side-encryption"); - metadata.remove("x-amz-server-side-encryption-customer-algorithm"); - metadata.remove("x-amz-server-side-encryption-customer-key-md5"); - } - - #[cfg(feature = "rio-v2")] - #[tokio::test] - async fn test_minio_shaped_ssec_metadata_decrypts_with_the_right_key_only() { - let customer_key_bytes = [0x42u8; 32]; - let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); - let customer_key_md5 = md5_base64(customer_key_bytes); - - let material = sse_encryption(EncryptionRequest { - bucket: "bucket", - key: "object", - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(customer_key.clone()), - sse_customer_key_md5: Some(customer_key_md5.clone()), - content_size: 4096, - principal: None, - }) - .await - .expect("sse-c encryption") - .expect("sse-c material"); - - let mut metadata = encryption_material_to_metadata(&material).expect("sse-c metadata should serialize"); - strip_to_minio_ssec_shape(&mut metadata); - assert!( - !metadata.contains_key("x-amz-server-side-encryption-customer-key-md5"), - "the MinIO shape stores no customer-key MD5" - ); - - // Correct key: detected via the sealed slot, proven by the unseal. - let decrypted = sse_decryption(DecryptionRequest { - bucket: "bucket", - key: "object", - metadata: &metadata, - sse_customer_key: Some(&customer_key), - sse_customer_key_md5: Some(&customer_key_md5), - principal: None, - }) - .await - .expect("minio-shaped sse-c decryption") - .expect("minio-shaped sse-c material"); - assert_eq!(decrypted.key_kind, EncryptionKeyKind::Object); - assert_eq!(decrypted.key_bytes, material.key_bytes); - - // Wrong key with a self-consistent MD5: the missing stored MD5 cannot - // catch it, so the AEAD unseal must — the relaxation is not a bypass. - let wrong_key_bytes = [0x43u8; 32]; - let wrong_key = BASE64_STANDARD.encode_to_string(wrong_key_bytes); - let wrong_key_md5 = md5_base64(wrong_key_bytes); - let result = sse_decryption(DecryptionRequest { - bucket: "bucket", - key: "object", - metadata: &metadata, - sse_customer_key: Some(&wrong_key), - sse_customer_key_md5: Some(&wrong_key_md5), - principal: None, - }) - .await; - assert!(result.is_err(), "a wrong customer key must fail the sealed-key unseal"); - - // No key at all: detected as SSE-C, so the caller is asked for the - // parameters instead of getting an opaque unreadable-object error. - let result = sse_decryption(DecryptionRequest { - bucket: "bucket", - key: "object", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await; - let error = result.expect_err("missing SSE-C parameters must fail closed"); - assert!(error.message.contains("must be provided"), "got: {}", error.message); - } - - #[cfg(feature = "rio-v2")] - #[tokio::test] - async fn test_minio_shaped_ssec_metadata_resolves_and_classifies() { - let customer_key_bytes = [0x51u8; 32]; - let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); - let customer_key_md5 = md5_base64(customer_key_bytes); - - let material = sse_encryption(EncryptionRequest { - bucket: "bucket", - key: "object", - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(customer_key.clone()), - sse_customer_key_md5: Some(customer_key_md5.clone()), - content_size: 4096, - principal: None, - }) - .await - .expect("sse-c encryption") - .expect("sse-c material"); - let mut metadata = encryption_material_to_metadata(&material).expect("sse-c metadata should serialize"); - strip_to_minio_ssec_shape(&mut metadata); - - let mut headers = HeaderMap::new(); - headers.insert("x-amz-server-side-encryption-customer-algorithm", HeaderValue::from_static("AES256")); - headers.insert( - "x-amz-server-side-encryption-customer-key", - HeaderValue::from_str(&customer_key).expect("customer key header"), - ); - headers.insert( - "x-amz-server-side-encryption-customer-key-md5", - HeaderValue::from_str(&customer_key_md5).expect("customer key MD5 header"), - ); - let resolved = SseObjectEncryptionResolver - .resolve_read_material(ReadEncryptionRequest { - bucket: "bucket", - object: "object", - metadata: &metadata, - headers: &headers, - }) - .await - .expect("minio-shaped SSE-C resolver") - .expect("minio-shaped SSE-C material"); - assert_eq!(resolved.mode, ReadEncryptionMode::Object); - assert_eq!(resolved.key_bytes, material.key_bytes); - - // HEAD-path key validation: no stored MD5 to compare against, so a - // self-consistent key passes here and the unseal remains the proof. - super::validate_ssec_for_read(&metadata, Some(&customer_key), Some(&customer_key_md5)) - .expect("self-consistent SSE-C parameters validate"); - super::validate_ssec_for_read(&metadata, None, None).expect_err("missing SSE-C parameters must be rejected"); - - // Response classification reports SSE-C, not managed SSE. - let classified = classify_sse_read_response(DecryptionRequest { - bucket: "bucket", - key: "object", - metadata: &metadata, - sse_customer_key: Some(&customer_key), - sse_customer_key_md5: Some(&customer_key_md5), - principal: None, - }) - .await - .expect("minio-shaped sse-c classification") - .expect("minio-shaped sse-c response headers"); - assert!(classified.sse_customer_algorithm.is_some()); - assert!(classified.ssekms_key_id.is_none()); - } - - #[cfg(feature = "rio-v2")] - #[test] - fn test_mark_encrypted_multipart_metadata_sets_minio_marker() { - let mut metadata = HashMap::new(); - mark_encrypted_multipart_metadata(&mut metadata); - assert!(metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER)); - } - - #[test] - fn test_verify_ssec_key_match_tolerates_missing_md5_only_for_minio_sealed_ssec() { - // MinIO SSE-C objects store no customer-key MD5; the AEAD unseal is the - // real key proof, so the early check stands down for that shape only. - assert!(verify_ssec_key_match("provided_md5", None, true).is_ok()); - // A stored MD5 always wins, even on the MinIO shape: a mismatch is a - // mismatch. - let stored = "stored_md5".to_string(); - assert!(verify_ssec_key_match("provided_md5", Some(&stored), true).is_err()); - } - - #[test] - fn test_verify_ssec_key_match_success() { - let md5 = "test_md5".to_string(); - let result = verify_ssec_key_match("test_md5", Some(&md5), false); - assert!(result.is_ok()); - } - - #[test] - fn test_verify_ssec_key_match_mismatch() { - let md5 = "stored_md5".to_string(); - let result = verify_ssec_key_match("provided_md5", Some(&md5), false); - assert!(result.is_err()); - } - - #[test] - fn test_verify_ssec_key_match_no_stored() { - let result = verify_ssec_key_match("provided_md5", None, false); - assert!(result.is_err()); - } - - fn multipart_ssec_request(key_byte: u8) -> EncryptionRequest<'static> { - let key_bytes = [key_byte; 32]; - EncryptionRequest { - bucket: "bucket", - key: "object", - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(BASE64_STANDARD.encode_to_string(key_bytes)), - sse_customer_key_md5: Some(md5_base64(key_bytes)), - content_size: 1, - principal: None, - } - } - - fn multipart_ssec_metadata(key_byte: u8) -> HashMap { - let key_bytes = [key_byte; 32]; - HashMap::from([ - ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()), - ("x-amz-server-side-encryption-customer-key-md5".to_string(), md5_base64(key_bytes)), - ]) - } - - #[test] - fn test_validate_multipart_ssec_exact_match() { - assert!( - multipart_ssec_request(42) - .validate_multipart_ssec(&multipart_ssec_metadata(42)) - .is_ok() - ); - } - - #[test] - fn test_validate_complete_multipart_ssec_allows_omitted_parameters() { - let no_ssec = EncryptionRequest { - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - ..multipart_ssec_request(42) - }; - - assert!(no_ssec.validate_complete_multipart_ssec(&multipart_ssec_metadata(42)).is_ok()); - assert!(no_ssec.validate_complete_multipart_ssec(&HashMap::new()).is_ok()); - - for invalid_metadata in [ - HashMap::from([("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string())]), - HashMap::from([ - ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES128".to_string()), - ("x-amz-server-side-encryption-customer-key-md5".to_string(), md5_base64([42u8; 32])), - ]), - HashMap::from([ - ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()), - ("x-amz-server-side-encryption-customer-key-md5".to_string(), "invalid".to_string()), - ]), - ] { - assert_eq!( - no_ssec - .validate_complete_multipart_ssec(&invalid_metadata) - .expect_err("corrupt SSE-C session metadata must fail closed") - .code, - S3ErrorCode::InvalidRequest - ); - } - } - - #[test] - fn ssec_checksum_completion_requires_key_for_both_metadata_aliases() { - let no_key = EncryptionRequest { - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - ..multipart_ssec_request(42) - }; - for prefix in ["x-rustfs-internal-", "x-minio-internal-"] { - let mut metadata = multipart_ssec_metadata(42); - metadata.insert(format!("{prefix}plaintext-checksum"), "true".to_string()); - assert_eq!( - no_key - .validate_complete_multipart_ssec(&metadata) - .expect_err("no key cannot compare or reveal plaintext checksums") - .code, - S3ErrorCode::InvalidRequest - ); - multipart_ssec_request(42) - .validate_complete_multipart_ssec(&metadata) - .expect("correct key"); - assert!( - multipart_ssec_request(43) - .validate_complete_multipart_ssec(&metadata) - .is_err() - ); - } - } - - #[test] - fn test_validate_complete_multipart_ssec_still_validates_present_parameters() { - let partial = EncryptionRequest { - sse_customer_key: None, - ..multipart_ssec_request(42) - }; - assert_eq!( - partial - .validate_complete_multipart_ssec(&multipart_ssec_metadata(42)) - .expect_err("partial SSE-C parameters must fail") - .code, - S3ErrorCode::InvalidRequest - ); - assert_eq!( - multipart_ssec_request(43) - .validate_complete_multipart_ssec(&multipart_ssec_metadata(42)) - .expect_err("wrong SSE-C parameters must fail") - .code, - S3ErrorCode::InvalidRequest - ); - } - - #[test] - fn test_validate_multipart_ssec_rejects_wrong_key_without_leaking_it() { - let request = multipart_ssec_request(43); - let encoded_key = request.sse_customer_key.clone().expect("fixture key"); - let encoded_md5 = request.sse_customer_key_md5.clone().expect("fixture MD5"); - - let error = request - .validate_multipart_ssec(&multipart_ssec_metadata(42)) - .expect_err("wrong key must fail"); - - assert_eq!(error.code, S3ErrorCode::InvalidRequest); - assert!(!error.message.contains(&encoded_key)); - assert!(!error.message.contains(&encoded_md5)); - } - - #[test] - fn test_validate_multipart_ssec_rejects_missing_or_unexpected_parameters() { - let no_ssec = EncryptionRequest { - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - ..multipart_ssec_request(42) - }; - assert_eq!( - no_ssec - .validate_multipart_ssec(&multipart_ssec_metadata(42)) - .expect_err("SSE-C session requires all parameters") - .code, - S3ErrorCode::InvalidRequest - ); - assert_eq!( - multipart_ssec_request(42) - .validate_multipart_ssec(&HashMap::new()) - .expect_err("plaintext session rejects SSE-C parameters") - .code, - S3ErrorCode::InvalidRequest - ); - let incomplete_session = HashMap::from([( - "x-amz-server-side-encryption-customer-key-md5".to_string(), - multipart_ssec_request(42).sse_customer_key_md5.expect("fixture MD5"), - )]); - assert_eq!( - multipart_ssec_request(42) - .validate_multipart_ssec(&incomplete_session) - .expect_err("incomplete stored SSE-C metadata must fail closed") - .code, - S3ErrorCode::InvalidRequest - ); - } - - // ============================================================================ - // Integration Tests - Encrypt/Decrypt with SimpleSseDekProvider - // ============================================================================ - - #[tokio::test] - async fn test_simple_sse_dek_provider_encrypt_decrypt() { - use std::io::Cursor; - use tokio::io::AsyncReadExt; - - // 1. Setup: Create SimpleSseDekProvider with test master key - let provider = TestSseDekProvider::new_with_key([42u8; 32]); - - // 2. Generate a data encryption key - let bucket = "test-bucket"; - let key = "test-key"; - let kms_key_id = "default"; // Key ID is ignored in simple provider - let context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string()); - - let (data_key, _encrypted_dek) = provider - .generate_sse_dek(&context, kms_key_id) - .await - .expect("Failed to generate DEK"); - - // 3. Prepare test data (plaintext) - let plaintext = b"Hello, World! This is a test message for encryption and decryption."; - println!("Original plaintext: {:?}", String::from_utf8_lossy(plaintext)); - println!("Plaintext length: {} bytes", plaintext.len()); - - // 4. Encrypt with EncryptReader. - let plaintext_reader = Cursor::new(plaintext.to_vec()); - let mut encrypt_reader = EncryptReader::new(plaintext_reader, data_key.plaintext_key, data_key.nonce); - - // Read encrypted data - let mut encrypted_data = Vec::new(); - encrypt_reader - .read_to_end(&mut encrypted_data) - .await - .expect("Failed to read encrypted data"); - - println!("Encrypted data length: {} bytes", encrypted_data.len()); - println!( - "First 16 bytes of encrypted data: {:02x?}", - &encrypted_data[..16.min(encrypted_data.len())] - ); - - // Verify encrypted data is different from plaintext - assert_ne!( - &encrypted_data[..plaintext.len()], - plaintext, - "Encrypted data should be different from plaintext" - ); - - // 5. Decrypt with DecryptReader. - let encrypted_reader = Cursor::new(encrypted_data); - let mut decrypt_reader = DecryptReader::new(encrypted_reader, data_key.plaintext_key, data_key.nonce); - - // Read decrypted data - let mut decrypted_data = Vec::new(); - decrypt_reader - .read_to_end(&mut decrypted_data) - .await - .expect("Failed to read decrypted data"); - - println!("Decrypted data: {:?}", String::from_utf8_lossy(&decrypted_data)); - println!("Decrypted length: {} bytes", decrypted_data.len()); - - // 6. Verify decrypted data matches original plaintext - assert_eq!(decrypted_data, plaintext, "Decrypted data should match original plaintext"); - - println!("✅ Encryption/Decryption test passed!"); - } - - #[tokio::test] - async fn test_simple_sse_dek_provider_encrypt_decrypt_large_data() { - use std::io::Cursor; - use tokio::io::AsyncReadExt; - - // 1. Setup: Create SimpleSseDekProvider with test master key - let provider = TestSseDekProvider::new_with_key([42u8; 32]); - - let bucket = "test-bucket"; - let key = "test-key-large"; - let kms_key_id = "default"; - let context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string()); - - let (data_key, _encrypted_dek) = provider - .generate_sse_dek(&context, kms_key_id) - .await - .expect("Failed to generate DEK"); - - // Create 1MB of test data - let plaintext_size = 1024 * 1024; // 1MB - let plaintext: Vec = (0..plaintext_size).map(|i| (i % 256) as u8).collect(); - println!("Testing with {} bytes of data", plaintext.len()); - - // Encrypt. - let plaintext_reader = Cursor::new(plaintext.clone()); - let mut encrypt_reader = EncryptReader::new(plaintext_reader, data_key.plaintext_key, data_key.nonce); - - let mut encrypted_data = Vec::new(); - encrypt_reader - .read_to_end(&mut encrypted_data) - .await - .expect("Failed to encrypt large data"); - - println!("Encrypted {} bytes to {} bytes", plaintext.len(), encrypted_data.len()); - - // Decrypt. - let encrypted_reader = Cursor::new(encrypted_data); - let mut decrypt_reader = DecryptReader::new(encrypted_reader, data_key.plaintext_key, data_key.nonce); - - let mut decrypted_data = Vec::new(); - decrypt_reader - .read_to_end(&mut decrypted_data) - .await - .expect("Failed to decrypt large data"); - - // Verify - assert_eq!(decrypted_data.len(), plaintext.len(), "Decrypted size should match original"); - assert_eq!(decrypted_data, plaintext, "Decrypted data should match original plaintext"); - - println!("✅ Large data encryption/decryption test passed!"); - } - - #[tokio::test] - async fn test_simple_sse_dek_provider_different_nonces() { - use std::io::Cursor; - use tokio::io::AsyncReadExt; - - // 1. Setup: Create SimpleSseDekProvider with test master key - let provider = TestSseDekProvider::new_with_key([42u8; 32]); - - let bucket = "test-bucket"; - let key = "test-key"; - let kms_key_id = "default"; - let context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string()); - - // Generate two different keys (with different nonces) - let (data_key1, _) = provider - .generate_sse_dek(&context, kms_key_id) - .await - .expect("Failed to generate DEK 1"); - - let (data_key2, _) = provider - .generate_sse_dek(&context, kms_key_id) - .await - .expect("Failed to generate DEK 2"); - - // Verify nonces are different - assert_ne!(data_key1.nonce, data_key2.nonce, "Different keys should have different nonces"); - - // Same plaintext - let plaintext = b"Same plaintext"; - - // Encrypt with first key. - let reader1 = Cursor::new(plaintext.to_vec()); - let mut encrypt_reader1 = EncryptReader::new(reader1, data_key1.plaintext_key, data_key1.nonce); - let mut encrypted1 = Vec::new(); - encrypt_reader1.read_to_end(&mut encrypted1).await.unwrap(); - - // Encrypt with second key. - let reader2 = Cursor::new(plaintext.to_vec()); - let mut encrypt_reader2 = EncryptReader::new(reader2, data_key2.plaintext_key, data_key2.nonce); - let mut encrypted2 = Vec::new(); - encrypt_reader2.read_to_end(&mut encrypted2).await.unwrap(); - - // Verify ciphertexts are different (due to different nonces/keys) - assert_ne!( - encrypted1, encrypted2, - "Same plaintext with different nonces should produce different ciphertext" - ); - - println!("✅ Different nonces produce different ciphertext - test passed!"); - } - - #[test] - fn test_encrypt_dek_writes_json_with_random_nonces() { - let dek = [0x11u8; 32]; - let cmk = [0x22u8; 32]; - - let encrypted_a = TestSseDekProvider::encrypt_dek(dek, cmk).expect("first DEK wrap should succeed"); - let encrypted_b = TestSseDekProvider::encrypt_dek(dek, cmk).expect("second DEK wrap should succeed"); - - let envelope_a: super::LocalSseDekEnvelope = - serde_json::from_str(&encrypted_a).expect("first wrapped DEK should be a JSON envelope"); - let envelope_b: super::LocalSseDekEnvelope = - serde_json::from_str(&encrypted_b).expect("second wrapped DEK should be a JSON envelope"); - - assert_eq!(envelope_a.version, super::LOCAL_SSE_DEK_FORMAT_VERSION); - assert_eq!(envelope_b.version, super::LOCAL_SSE_DEK_FORMAT_VERSION); - assert_ne!(envelope_a.nonce, envelope_b.nonce, "each DEK wrap should use a distinct nonce"); - assert_eq!( - TestSseDekProvider::decrypt_dek(&encrypted_a, cmk).expect("first JSON envelope should decrypt"), - dek - ); - } - - #[test] - fn test_decrypt_dek_accepts_legacy_zero_nonce_payload() { - let dek = [0x33u8; 32]; - let cmk = [0x44u8; 32]; - let cipher = Aes256Gcm::new(&Key::::from(cmk)); - let legacy_nonce = Nonce::from([0u8; 12]); - let ciphertext = cipher - .encrypt(&legacy_nonce, dek.as_slice()) - .expect("legacy wrap should succeed"); - let legacy_payload = format!( - "{}:{}", - BASE64_STANDARD.encode_to_string(legacy_nonce), - BASE64_STANDARD.encode_to_string(ciphertext) - ); - - let decrypted = TestSseDekProvider::decrypt_dek(&legacy_payload, cmk).expect("legacy payload should remain decryptable"); - assert_eq!(decrypted, dek); - } - - #[test] - fn test_decrypt_dek_rejects_unknown_json_version() { - let envelope = serde_json::json!({ - "version": super::LOCAL_SSE_DEK_FORMAT_VERSION + 1, - "nonce": BASE64_STANDARD.encode_to_string([0u8; 12]), - "ciphertext": BASE64_STANDARD.encode_to_string([0u8; 48]), - }) - .to_string(); - - let error = TestSseDekProvider::decrypt_dek(&envelope, [0x55u8; 32]) - .expect_err("unknown JSON envelope versions must fail closed"); - assert_eq!(error.code, S3ErrorCode::InternalError); - assert_eq!(error.message, ApiError::error_code_to_message(&S3ErrorCode::InternalError)); - let source = error - .source - .as_deref() - .and_then(|source| source.downcast_ref::()) - .expect("API error should retain the storage error source"); - assert!(matches!(source, StorageError::Io(io_error) if io_error - .to_string() - .contains("Unsupported encrypted DEK format version"))); - } - - #[tokio::test] - async fn test_sse_encryption_fails_closed_without_local_sse_master_key() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), - ("RUSTFS_SSE_S3_MASTER_KEY", None::<&str>), - ], - async { - let err = sse_encryption(EncryptionRequest { - bucket: "test-bucket", - key: "test-key", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 1024, - principal: None, - }) - .await - .expect_err("SSE-S3 should fail closed without a configured local master key"); - - assert!(err.message.contains("RUSTFS_SSE_S3_MASTER_KEY")); - assert_eq!( - err.code, - S3ErrorCode::InvalidRequest, - "missing local SSE master key is a configuration error, not a 500 (rustfs#4844)" - ); - }, - ) - .await; - reset_sse_dek_provider(); - } - - #[tokio::test] - async fn test_sse_encryption_fails_closed_with_invalid_local_sse_master_key() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), - ("RUSTFS_SSE_S3_MASTER_KEY", Some("not-base64")), - ], - async { - let err = sse_encryption(EncryptionRequest { - bucket: "test-bucket", - key: "test-key", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 1024, - principal: None, - }) - .await - .expect_err("SSE-S3 should fail closed with an invalid local master key"); - - assert!(err.message.contains("valid base64")); - assert_eq!( - err.code, - S3ErrorCode::InvalidRequest, - "invalid local SSE master key is a configuration error, not a 500 (rustfs#4844)" - ); - }, - ) - .await; - reset_sse_dek_provider(); - } - - #[tokio::test] - async fn test_simple_sse_dek_provider_decrypt_with_encrypted_dek() { - use std::io::Cursor; - use tokio::io::AsyncReadExt; - - // 1. Setup: Create SimpleSseDekProvider with test master key - let provider = TestSseDekProvider::new_with_key([42u8; 32]); - - let bucket = "test-bucket"; - let key = "test-key"; - let kms_key_id = "default"; - let context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string()); - - // 1. Generate DEK and get encrypted DEK - let (data_key, encrypted_dek) = provider - .generate_sse_dek(&context, kms_key_id) - .await - .expect("Failed to generate DEK"); - - let original_plaintext_key = data_key.plaintext_key; - let original_nonce = data_key.nonce; - - // 2. Simulate storing encrypted_dek and nonce in metadata - // In real scenario, nonce would be stored separately in metadata - - // 3. Later, decrypt the DEK - let decrypted_plaintext_key = provider - .decrypt_sse_dek(&encrypted_dek, kms_key_id, &context) - .await - .expect("Failed to decrypt DEK"); - - // 4. Verify decrypted key matches original - assert_eq!( - decrypted_plaintext_key, original_plaintext_key, - "Decrypted DEK should match original plaintext key" - ); - - // 5. Use decrypted key to encrypt/decrypt data - let plaintext = b"Test data with decrypted DEK"; - - // Encrypt with original key. - let reader = Cursor::new(plaintext.to_vec()); - let mut encrypt_reader = EncryptReader::new(reader, original_plaintext_key, original_nonce); - let mut encrypted_data = Vec::new(); - encrypt_reader.read_to_end(&mut encrypted_data).await.unwrap(); - - // Decrypt with recovered key (simulating GET operation). - let reader = Cursor::new(encrypted_data); - let mut decrypt_reader = DecryptReader::new( - reader, - decrypted_plaintext_key, - original_nonce, // In real scenario, read from metadata - ); - let mut decrypted_data = Vec::new(); - decrypt_reader.read_to_end(&mut decrypted_data).await.unwrap(); - - // Verify - assert_eq!(decrypted_data, plaintext, "Data decrypted with recovered key should match original"); - - println!("✅ Full cycle (generate -> encrypt DEK -> decrypt DEK -> decrypt data) test passed!"); - } - - #[tokio::test] - async fn test_managed_decryption_selects_provider_from_persisted_dek() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - let manager = configure_test_global_local_kms().await; - - let local_master_key = [7u8; 32]; - let local_provider = TestSseDekProvider::new_with_key(local_master_key); - let context = ObjectEncryptionContext::new("bucket".to_string(), "object".to_string()); - let (data_key, encrypted_dek) = local_provider - .generate_sse_dek(&context, "legacy-local-key") - .await - .expect("generate beta.5 local DEK"); - - async_with_vars( - [ - ("__RUSTFS_SSE_SIMPLE_CMK", None::), - ("RUSTFS_SSE_S3_MASTER_KEY", Some(BASE64_STANDARD.encode_to_string(local_master_key))), - ], - async { - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_KMS.to_string()), - ( - INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(encrypted_dek), - ), - ( - INTERNAL_ENCRYPTION_IV_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(data_key.nonce), - ), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "legacy-local-key".to_string()), - ]); - - let material = apply_managed_decryption_material("bucket", "object", &metadata, None) - .await - .expect("legacy local DEK should not be routed to the running KMS") - .expect("managed metadata should produce decryption material"); - assert_eq!(material.key_bytes, data_key.plaintext_key); - assert_eq!(material.sse_type, SSEType::SseKms); - }, - ) - .await; - - manager.stop().await.expect("stop test KMS service"); - reset_sse_dek_provider(); - - let kms_envelope = br#"{ - "key_id": "test-key-id", - "master_key_id": "master-key-id", - "key_spec": "AES_256", - "encrypted_key": [1, 2, 3, 4], - "nonce": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], - "encryption_context": {}, - "created_at": "2024-01-01T00:00:00+00:00" - }"#; - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.to_string()), - (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string(kms_envelope)), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([0x14; 12])), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "test-key-id".to_string()), - ]); - let error = match apply_managed_decryption_material("bucket", "object", &metadata, None).await { - Ok(_) => panic!("KMS envelope must not fall back to the local provider"), - Err(error) => error, - }; - assert_eq!(error.code, S3ErrorCode::ServiceUnavailable); - - reset_sse_dek_provider(); - } - - /// A loopback stand-in for AWS KMS, so the real AWS backend — SDK client, - /// service manager and all — sits behind the SSE entry points under test. - /// - /// It issues data keys the way AWS does: a binary blob that is not UTF-8 - /// and carries nothing RustFS could recognize, decryptable only with the - /// encryption context it was generated under. - struct FakeAwsKms { - endpoint: String, - state: Arc, - server: tokio::task::JoinHandle<()>, - } - - /// Plaintext data key and the encryption context it was generated under. - type FakeAwsDataKey = ([u8; 32], serde_json::Value); - - #[derive(Default)] - struct FakeAwsKmsState { - data_keys: std::sync::Mutex, FakeAwsDataKey>>, - decrypt_calls: std::sync::atomic::AtomicUsize, - } - - impl Drop for FakeAwsKms { - fn drop(&mut self) { - self.server.abort(); - } - } - - impl FakeAwsKms { - const KEY_ARN: &'static str = "arn:aws:kms:us-east-1:111122223333:key/test-key"; - - async fn start() -> Self { - let state = Arc::new(FakeAwsKmsState::default()); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind fake AWS KMS listener"); - let endpoint = format!("http://{}", listener.local_addr().expect("fake AWS KMS address")); - let app = axum::Router::new().fallback(Self::handle).with_state(state.clone()); - let server = tokio::spawn(async move { - axum::serve(listener, app).await.expect("serve fake AWS KMS"); - }); - Self { endpoint, state, server } - } - - fn decrypt_calls(&self) -> usize { - self.state.decrypt_calls.load(std::sync::atomic::Ordering::SeqCst) - } - - async fn handle( - axum::extract::State(state): axum::extract::State>, - headers: axum::http::HeaderMap, - body: axum::body::Bytes, - ) -> axum::response::Response { - let operation = headers - .get("x-amz-target") - .and_then(|target| target.to_str().ok()) - .and_then(|target| target.rsplit('.').next()) - .unwrap_or_default(); - let request: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); - let context = request - .get("EncryptionContext") - .cloned() - .unwrap_or_else(|| serde_json::json!({})); - - let reply = match operation { - "ListKeys" => Ok(serde_json::json!({ "Keys": [], "Truncated": false })), - "DescribeKey" => Ok(serde_json::json!({ - "KeyMetadata": { - "KeyId": "test-key", - "Arn": Self::KEY_ARN, - "CreationDate": 1_700_000_000, - "Enabled": true, - "KeyUsage": "ENCRYPT_DECRYPT", - "KeyState": "Enabled", - "Origin": "AWS_KMS", - "KeyManager": "CUSTOMER", - } - })), - "GenerateDataKey" => { - let mut plaintext = [0u8; 32]; - rand::Rng::fill_bytes(&mut rand::rng(), &mut plaintext); - // A continuation byte straight after ASCII is never valid - // UTF-8, like the real blob in practice. - let mut blob = vec![0x01, 0x02, 0x02, 0x00, 0x78]; - let mut tail = [0u8; 48]; - rand::Rng::fill_bytes(&mut rand::rng(), &mut tail); - blob.extend(tail.map(|byte| 0x80 | (byte & 0x3f))); - state - .data_keys - .lock() - .expect("fake AWS KMS state") - .insert(blob.clone(), (plaintext, context)); - Ok(serde_json::json!({ - "KeyId": Self::KEY_ARN, - "Plaintext": BASE64_STANDARD.encode_to_string(plaintext), - "CiphertextBlob": BASE64_STANDARD.encode_to_string(&blob), - })) - } - "Decrypt" => { - state.decrypt_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let blob = request - .get("CiphertextBlob") - .and_then(serde_json::Value::as_str) - .and_then(|blob| BASE64_STANDARD.decode_to_vec(blob).ok()) - .unwrap_or_default(); - match state.data_keys.lock().expect("fake AWS KMS state").get(&blob) { - Some((plaintext, sealed_context)) if *sealed_context == context => Ok(serde_json::json!({ - "KeyId": Self::KEY_ARN, - "Plaintext": BASE64_STANDARD.encode_to_string(plaintext), - "EncryptionAlgorithm": "SYMMETRIC_DEFAULT", - })), - _ => Err("InvalidCiphertextException"), - } - } - _ => Err("UnsupportedOperationException"), - }; - - let (status, body) = match reply { - Ok(body) => (axum::http::StatusCode::OK, body), - Err(code) => ( - axum::http::StatusCode::BAD_REQUEST, - serde_json::json!({ "__type": code, "message": code }), - ), - }; - axum::response::Response::builder() - .status(status) - .header("content-type", "application/x-amz-json-1.1") - .body(axum::body::Body::from(body.to_string())) - .expect("fake AWS KMS response") - } - } - - /// Run `test` with the global KMS service on the AWS backend, pointed at a - /// [`FakeAwsKms`], and no SSE provider injected — the wiring a deployment - /// with `RUSTFS_KMS_BACKEND=aws` and no local master key has. - async fn with_aws_kms_backend(test: F) - where - F: FnOnce(Arc) -> Fut, - Fut: std::future::Future, - { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - let fake = Arc::new(FakeAwsKms::start().await); - - async_with_vars( - [ - ("AWS_ACCESS_KEY_ID", Some("AKIDTEST")), - ("AWS_SECRET_ACCESS_KEY", Some("secret")), - ("AWS_SESSION_TOKEN", None), - ("AWS_PROFILE", None), - ("AWS_EC2_METADATA_DISABLED", Some("true")), - ("HTTP_PROXY", None), - ("HTTPS_PROXY", None), - ("http_proxy", None), - ("https_proxy", None), - ("RUSTFS_SSE_S3_MASTER_KEY", None), - ("__RUSTFS_SSE_SIMPLE_CMK", None), - ], - async { - let mut config = rustfs_kms::KmsConfig::aws(Some("us-east-1".to_string())).with_insecure_development_defaults(); - let rustfs_kms::BackendConfig::Aws(aws) = &mut config.backend_config else { - panic!("the AWS constructor must create an AWS backend configuration"); - }; - aws.endpoint_url = Some(fake.endpoint.clone()); - let manager = rustfs_kms::init_global_kms_service_manager(); - manager.reconfigure(config).await.expect("start the AWS KMS backend"); - let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) - .await - .expect("kms provider should initialize from the AWS-backed manager"); - super::set_sse_dek_provider_for_test(Arc::new(provider)); - - test(fake.clone()).await; - - manager.stop().await.expect("stop the AWS KMS backend"); - }, - ) - .await; - - reset_sse_dek_provider(); - } - - fn aws_sse_kms_write() -> EncryptionRequest<'static> { - EncryptionRequest { - bucket: "bucket", - key: "dir/object", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), - ssekms_key_id: Some("test-key".to_string()), - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 4096, - principal: None, - } - } - - async fn read_managed_object(metadata: &HashMap) -> Result { - sse_decryption(DecryptionRequest { - bucket: "bucket", - key: "dir/object", - metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .map(|material| material.expect("an SSE-KMS object must yield decryption material")) - } - - /// An SSE-KMS object written through the AWS backend must be readable. - /// - /// It was not: the AWS data key reached storage as a bare blob, the read - /// path took the unrecognized bytes for a locally wrapped key, and every - /// GET failed asking for `RUSTFS_SSE_S3_MASTER_KEY` without AWS ever being - /// asked to decrypt. - #[tokio::test] - async fn sse_kms_object_written_through_the_aws_backend_reads_back() { - with_aws_kms_backend(|aws| async move { - let material = sse_encryption(aws_sse_kms_write()) - .await - .expect("sse-kms encryption") - .expect("managed sse-kms material"); - let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); - // The rio-v2 writer keeps the wrapped data key in MinIO's slot only. - let stored_key = metadata - .get(INTERNAL_ENCRYPTION_KEY_HEADER) - .or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER)) - .expect("stored data key"); - let stored_key = BASE64_STANDARD.decode_to_vec(stored_key).expect("stored data key is base64"); - assert!( - rustfs_kms::is_data_key_envelope(&stored_key), - "the stored data key must identify itself as KMS-wrapped" - ); - - let decrypted = read_managed_object(&metadata) - .await - .expect("an object written through the AWS backend must decrypt"); - - assert_eq!(decrypted.key_bytes, material.key_bytes); - assert_eq!(decrypted.sse_type, SSEType::SseKms); - assert_eq!(aws.decrypt_calls(), 1, "the read must be served by AWS Decrypt"); - }) - .await; - } - - /// Objects written by releases through 1.0.5 keep the AWS blob bare in - /// their metadata. They are intact and must decrypt as they are, without - /// being rewritten. A `rio-v2` build stored the same bare blob beside a - /// sealed object key, which is the shape MinIO's own objects have, so the - /// route has to hold there too. - #[tokio::test] - async fn sse_kms_object_with_a_bare_aws_data_key_reads_back() { - with_aws_kms_backend(|aws| async move { - let material = sse_encryption(aws_sse_kms_write()) - .await - .expect("sse-kms encryption") - .expect("managed sse-kms material"); - let mut metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); - - // Rebuild what those releases persisted: the same headers, with - // the blob AWS issued in place of the envelope around it. - let envelope_b64 = metadata - .get(INTERNAL_ENCRYPTION_KEY_HEADER) - .or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER)) - .expect("stored data key") - .clone(); - let envelope: serde_json::Value = serde_json::from_slice( - &BASE64_STANDARD - .decode_to_vec(&envelope_b64) - .expect("stored data key is base64"), - ) - .expect("stored data key is an envelope"); - let bare: Vec = serde_json::from_value(envelope["encrypted_key"].clone()).expect("envelope carries the AWS blob"); - let bare_b64 = BASE64_STANDARD.encode_to_string(&bare); - let mut replaced = 0; - for value in metadata.values_mut().filter(|value| **value == envelope_b64) { - *value = bare_b64.clone(); - replaced += 1; - } - assert!(replaced > 0, "the stored data key must have been replaced"); - assert!(!rustfs_kms::is_data_key_envelope(&bare)); - - let decrypted = read_managed_object(&metadata) - .await - .expect("an object carrying a bare AWS data key must decrypt"); - - assert_eq!(decrypted.key_bytes, material.key_bytes); - assert_eq!(aws.decrypt_calls(), 1, "the read must be served by AWS Decrypt"); - }) - .await; - } - - /// The bare-blob route exists for AWS alone. No other backend claims an - /// unrecognized data key, and without a KMS it still belongs to the local - /// provider, which is the one that can say what is wrong with it. - #[tokio::test] - async fn bare_data_key_stays_with_the_local_provider_without_an_aws_backend() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - let local_kms = KmsSseDekProvider::new_with_service_manager(configure_test_global_local_kms().await) - .await - .expect("kms provider should initialize from the Local-backed manager"); - assert!(!local_kms.reads_bare_data_key_ciphertext().await); - assert!( - !TestSseDekProvider::new_with_key([9u8; 32]) - .reads_bare_data_key_ciphertext() - .await - ); - - async_with_vars([("RUSTFS_SSE_S3_MASTER_KEY", None::<&str>), ("__RUSTFS_SSE_SIMPLE_CMK", None)], async { - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_KMS.to_string()), - ( - INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), - BASE64_STANDARD.encode_to_string([0x01, 0x02, 0x02, 0x00, 0x78, 0x80, 0x81]), - ), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([0x14; 12])), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "test-key".to_string()), - ]); - - let error = read_managed_object(&metadata) - .await - .expect_err("a bare blob has no owner without a KMS"); - - assert!( - error.message.contains("RUSTFS_SSE_S3_MASTER_KEY"), - "the local provider must still own the diagnosis: {}", - error.message - ); - }) - .await; - - reset_sse_dek_provider(); - } - - /// A KMS stand-in that owns bare data keys and records what it is asked to unwrap. - #[cfg(feature = "rio-v2")] - struct BareKmsProvider { - data_key: [u8; 32], - unwrapped: std::sync::Mutex>>, - } - - #[cfg(feature = "rio-v2")] - #[async_trait::async_trait] - impl SseDekProvider for BareKmsProvider { - async fn generate_sse_dek( - &self, - _context: &ObjectEncryptionContext, - _kms_key_id: &str, - ) -> Result<(DataKey, Vec), ApiError> { - Err(ApiError::from(StorageError::other("not exercised"))) - } - - async fn decrypt_sse_dek( - &self, - encrypted_dek: &[u8], - _kms_key_id: &str, - _context: &ObjectEncryptionContext, - ) -> Result<[u8; 32], ApiError> { - self.unwrapped.lock().expect("unwrap log").push(encrypted_dek.to_vec()); - Ok(self.data_key) - } - - async fn reads_bare_data_key_ciphertext(&self) -> bool { - true - } - } - - /// Seal a data key the way MinIO's builtin KMS does, in its raw layout: - /// `sealed || iv[16] || nonce[12]`, AES-256-GCM under `HMAC-SHA256(master, iv)`. - #[cfg(feature = "rio-v2")] - fn seal_minio_kms_data_key(data_key: &[u8; 32], master_key: &[u8; 32], context: &ObjectEncryptionContext) -> Vec { - use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead}; - use hmac::Mac; - let (iv, nonce) = ([0x21u8; 16], [0x42u8; 12]); - let mut mac = super::HmacSha256::new_from_slice(master_key).expect("hmac key"); - mac.update(&iv); - let sealing_key: [u8; 32] = mac.finalize().into_bytes().into(); - let aad = super::minio_kms_associated_data(context).expect("associated data"); - let mut sealed = Aes256Gcm::new_from_slice(&sealing_key) - .expect("sealing key") - .encrypt( - &aes_gcm::Nonce::from(nonce), - aes_gcm::aead::Payload { - msg: data_key, - aad: &aad, - }, - ) - .expect("seal"); - sealed.extend_from_slice(&iv); - sealed.extend_from_slice(&nonce); - sealed - } - - /// A sealed object key with no RustFS envelope comes from MinIO or from a - /// `rio-v2` build on a backend that stored its ciphertext bare. Opening it - /// as MinIO's is an authenticated proof, so the genuine MinIO object keeps - /// its route and only the remainder reaches the KMS. - #[cfg(feature = "rio-v2")] - #[tokio::test] - async fn unenveloped_sealed_data_key_goes_to_minio_first_and_the_kms_otherwise() { - let context = ObjectEncryptionContext::new("bucket".to_string(), "dir/object".to_string()); - let master_key = [0x5Au8; 32]; - let minio_data_key = [0x11u8; 32]; - let minio_ciphertext = seal_minio_kms_data_key(&minio_data_key, &master_key, &context); - let aws_blob = vec![ - 0x01, 0x02, 0x02, 0x00, 0x78, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, - ]; - let kms = || { - Arc::new(BareKmsProvider { - data_key: [0x22u8; 32], - unwrapped: std::sync::Mutex::new(Vec::new()), - }) - }; - let local = - || -> Result, ApiError> { Ok(Arc::new(TestSseDekProvider::new_with_key(master_key))) }; - let no_local = || -> Result, ApiError> { - Err(ApiError { - code: S3ErrorCode::InvalidRequest, - message: "no local master key".to_string(), - source: None, - }) - }; - - // MinIO's own object on a deployment whose backend also reads bare keys. - let provider = kms(); - let data_key = super::decrypt_unenveloped_sealed_dek(Some(provider.clone()), local(), &minio_ciphertext, "key", &context) - .await - .expect("a MinIO-sealed data key must open under the local master key"); - assert_eq!(data_key, minio_data_key); - assert!( - provider.unwrapped.lock().expect("unwrap log").is_empty(), - "a MinIO-sealed data key must never be sent to the KMS" - ); - - // A bare backend blob: with a local master key that cannot open it, and with none at all. - for local in [local(), no_local()] { - let provider = kms(); - let data_key = super::decrypt_unenveloped_sealed_dek(Some(provider.clone()), local, &aws_blob, "key", &context) - .await - .expect("a bare backend blob must be unwrapped by the KMS"); - assert_eq!(data_key, [0x22u8; 32]); - assert_eq!(*provider.unwrapped.lock().expect("unwrap log"), vec![aws_blob.clone()]); - } - - // Without a backend that reads bare keys, the MinIO route is the only one. - let data_key = super::decrypt_unenveloped_sealed_dek(None, local(), &minio_ciphertext, "key", &context) - .await - .expect("the MinIO route is unchanged"); - assert_eq!(data_key, minio_data_key); - super::decrypt_unenveloped_sealed_dek(None, local(), &aws_blob, "key", &context) - .await - .expect_err("bytes MinIO did not seal have no owner without such a backend"); - let error = super::decrypt_unenveloped_sealed_dek(None, no_local(), &minio_ciphertext, "key", &context) - .await - .expect_err("a missing local master key is still reported as such"); - assert_eq!((error.code, error.message.as_str()), (S3ErrorCode::InvalidRequest, "no local master key")); - } - - #[test] - fn local_sse_dek_recognition_covers_exactly_the_local_formats() { - let wrapped = TestSseDekProvider::encrypt_dek([7u8; 32], [9u8; 32]).expect("local wrap"); - assert!(super::is_local_sse_dek(wrapped.as_bytes())); - assert!(super::is_local_sse_dek(b"bm9uY2U=:Y2lwaGVydGV4dA==")); - // A damaged local envelope is still the local provider's to diagnose. - assert!(super::is_local_sse_dek(br#" {"version": 9"#)); - - // An AWS blob: binary, and not UTF-8. - assert!(!super::is_local_sse_dek(&[0x01, 0x02, 0x02, 0x00, 0x78, 0x80, 0x81])); - // Text that merely contains a colon is not the legacy pair. - assert!(!super::is_local_sse_dek(b"vault:v1:Y2lwaGVydGV4dA==")); - assert!(!super::is_local_sse_dek(b"not base64:Y2lwaGVydGV4dA==")); - assert!(!super::is_local_sse_dek(b"")); - } - - /// Regression test for "local provider cached → dynamically enable KMS → decrypt KMS envelope". - /// - /// Verifies that a `TestSseDekProvider` previously cached in `GLOBAL_SSE_DEK_PROVIDER` - /// is NEVER selected to unwrap a KMS data-key envelope. The KMS-envelope branch must - /// read `GLOBAL_KMS_DEK_PROVIDER` (or fall back to `KmsSseDekProvider::new()`), not - /// the local-provider cache. - #[tokio::test] - async fn test_kms_envelope_never_routes_to_cached_local_provider() { - let _guard = lock_sse_test_state().await; - reset_sse_dek_provider(); - - // 1. Populate GLOBAL_SSE_DEK_PROVIDER with a local provider — the kind - // that `get_local_sse_dek_provider` would cache when KMS is absent. - let local_master_key = [0xAAu8; 32]; - *super::GLOBAL_SSE_DEK_PROVIDER - .write() - .expect("write local provider into local cache") = Some(Arc::new(TestSseDekProvider::new_with_key(local_master_key))); - - // 2. Start a KMS service (dynamic enable). - let manager = configure_test_global_local_kms().await; - - // 3. Construct a KMS JSON envelope — the persisted format of a KMS-wrapped DEK. - // is_data_key_envelope() will return true for this payload. - let kms_envelope = br#"{ - "key_id": "envelope-key", - "master_key_id": "master-key-id", - "key_spec": "AES_256", - "encrypted_key": [10, 20, 30, 40], - "nonce": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], - "encryption_context": {}, - "created_at": "2024-01-01T00:00:00+00:00" - }"#; - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.to_string()), - (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string(kms_envelope)), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([0x14; 12])), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "envelope-key".to_string()), - ]); - - // 4. Decrypt the KMS envelope. Before the fix, this would pick up the cached - // TestSseDekProvider from GLOBAL_SSE_DEK_PROVIDER and either panic (wrong - // format) or produce garbage. After the fix, it routes to KmsSseDekProvider, - // which fails because the envelope contains dummy encrypted bytes that the - // test KMS cannot decrypt — but crucially the error code is NOT a local- - // provider error. - let error = match apply_managed_decryption_material("bucket", "object", &metadata, None).await { - Ok(_) => panic!("dummy KMS envelope must not produce valid decryption material"), - Err(error) => error, - }; - // The KMS service was reached (ServiceUnavailable or the KMS's own decrypt - // failure), not a local-provider format error. - assert!( - error.code == S3ErrorCode::ServiceUnavailable || error.code == S3ErrorCode::InternalError, - "KMS envelope must be routed to KMS provider, not local; got code {:?} msg '{}'", - error.code, - error.message, - ); - - manager.stop().await.expect("stop test KMS service"); - reset_sse_dek_provider(); - } - - #[tokio::test] - async fn test_managed_encryption_preserves_provider_unavailable_error() { - let _guard = lock_sse_test_state().await; - let manager = rustfs_kms::init_global_kms_service_manager(); - manager.stop().await.expect("stop global KMS service"); - reset_sse_dek_provider(); - *super::GLOBAL_SSE_DEK_PROVIDER.write().expect("update SSE DEK provider cache") = - Some(Arc::new(UnavailableSseDekProvider)); - - let error = - match apply_managed_encryption_material("bucket", "object", String::from(AMZ_ENCRYPTION_AES), None, None, 0, None) - .await - { - Ok(_) => panic!("provider unavailability must fail managed encryption"), - Err(error) => error, - }; - assert_eq!(error.code, S3ErrorCode::ServiceUnavailable); - - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.to_string()), - ( - INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), - BASE64_STANDARD.encode_to_string(b"local-provider-format"), - ), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([0x14; 12])), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "test-key-id".to_string()), - ]); - let error = match apply_managed_decryption_material("bucket", "object", &metadata, None).await { - Ok(_) => panic!("provider unavailability must fail managed decryption"), - Err(error) => error, - }; - assert_eq!(error.code, S3ErrorCode::ServiceUnavailable); - - reset_sse_dek_provider(); - } - - #[tokio::test] - async fn test_kms_sse_dek_provider_uses_latest_reconfigured_service() { - use rustfs_kms::config::KmsConfig; - let _guard = lock_sse_test_state().await; - - let manager = Arc::new(rustfs_kms::KmsServiceManager::new()); - - manager - .reconfigure(KmsConfig::static_kms( - "first-key".to_string(), - BASE64_STANDARD.encode_to_string([0x11; 32]), - )) - .await - .expect("first KMS reconfigure should succeed"); - - let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) - .await - .expect("provider should initialize"); - let context = ObjectEncryptionContext::new("bucket".to_string(), "object".to_string()); - provider - .generate_sse_dek(&context, "first-key") - .await - .expect("provider should use the initial service"); - - manager - .reconfigure(KmsConfig::static_kms( - "second-key".to_string(), - BASE64_STANDARD.encode_to_string([0x22; 32]), - )) - .await - .expect("second KMS reconfigure should succeed"); - - provider - .generate_sse_dek(&context, "second-key") - .await - .expect("provider should resolve the latest reconfigured service"); - - manager.stop().await.expect("kms service should stop cleanly"); - let generate_error = provider - .generate_sse_dek(&context, "second-key") - .await - .expect_err("stopped KMS must reject data-key generation"); - assert_eq!(generate_error.code, S3ErrorCode::ServiceUnavailable); - let decrypt_error = provider - .decrypt_sse_dek(b"{}", "second-key", &context) - .await - .expect_err("stopped KMS must reject data-key decryption"); - assert_eq!(decrypt_error.code, S3ErrorCode::ServiceUnavailable); - #[cfg(feature = "rio-v2")] - { - let legacy_error = provider - .decrypt_legacy_sse_dek(b"{}", "second-key", &context) - .await - .expect_err("stopped KMS must reject legacy data-key decryption"); - assert_eq!(legacy_error.code, S3ErrorCode::ServiceUnavailable); - } - } - - #[test] - fn test_encryption_type_enum() { - // Test EncryptionType enum - assert_eq!(SSEType::SseS3, SSEType::SseS3); - assert_eq!(SSEType::SseKms, SSEType::SseKms); - assert_eq!(SSEType::SseC, SSEType::SseC); - assert_ne!(SSEType::SseS3, SSEType::SseKms); - - // Test Debug format - let debug_str = format!("{:?}", SSEType::SseKms); - assert!(debug_str.contains("SseKms")); - } - - #[test] - fn test_verify_ssec_key_match_returns_invalid_request() { - let stored = "stored_md5".to_string(); - let err = verify_ssec_key_match("wrong_md5", Some(&stored), false).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_verify_ssec_key_match_no_stored_returns_invalid_request() { - let err = verify_ssec_key_match("any_md5", None, false).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_ssec_for_read_non_encrypted_object() { - let metadata = HashMap::new(); - let result = validate_ssec_for_read(&metadata, None, None); - assert!(result.is_ok()); - } - - #[test] - fn test_validate_ssec_for_read_missing_customer_key() { - let mut metadata = HashMap::new(); - metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); - metadata.insert( - "x-amz-server-side-encryption-customer-key-md5".to_string(), - "DWygnHRtgiJ77HCm+1rvHw==".to_string(), - ); - - let err = validate_ssec_for_read(&metadata, None, None).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_ssec_for_read_wrong_key() { - // Key A is used to "encrypt" the object (stored MD5 is from key A). - let key_a = [42u8; 32]; - let stored_md5 = md5_base64(key_a); - - let mut metadata = HashMap::new(); - metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); - metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), stored_md5); - - // Key B is a different key; its MD5 won't match stored MD5. - let key_b = [99u8; 32]; - let key_b_b64 = BASE64_STANDARD.encode_to_string(key_b); - let key_b_md5 = md5_base64(key_b); - - let err = validate_ssec_for_read(&metadata, Some(&key_b_b64), Some(&key_b_md5)).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_ssec_for_read_correct_key() { - let key_bytes = [42u8; 32]; - let key_b64 = BASE64_STANDARD.encode_to_string(key_bytes); - let key_md5 = md5_base64(key_bytes); - - let mut metadata = HashMap::new(); - metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); - metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), key_md5.clone()); - - let result = validate_ssec_for_read(&metadata, Some(&key_b64), Some(&key_md5)); - assert!(result.is_ok()); - } - - #[test] - fn test_validate_ssec_for_read_spoofed_md5() { - // A client provides the correct stored MD5 in the header but with a - // DIFFERENT key. The server must recompute MD5 from the key bytes and - // reject the request because the recomputed MD5 won't match the header. - let real_key = [42u8; 32]; - let stored_md5 = md5_base64(real_key); - - let mut metadata = HashMap::new(); - metadata.insert("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()); - metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), stored_md5.clone()); - - // Attacker has a different key but tries to pass the stored MD5 as their header - let fake_key = [99u8; 32]; - let fake_key_b64 = BASE64_STANDARD.encode_to_string(fake_key); - - let err = validate_ssec_for_read(&metadata, Some(&fake_key_b64), Some(&stored_md5)).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_sse_headers_for_read_rejects_kms_on_plain_object() { - let mut headers = HeaderMap::new(); - headers.insert("x-amz-server-side-encryption", http::HeaderValue::from_static("aws:kms")); - headers.insert("x-amz-server-side-encryption-aws-kms-key-id", http::HeaderValue::from_static("test-key")); - - let metadata = HashMap::new(); - let err = validate_sse_headers_for_read(&metadata, &headers).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[test] - fn test_validate_sse_headers_for_read_rejects_ssec_on_plain_object() { - let mut headers = HeaderMap::new(); - headers.insert( - "x-amz-server-side-encryption-customer-algorithm", - http::HeaderValue::from_static("AES256"), - ); - headers.insert("x-amz-server-side-encryption-customer-key", http::HeaderValue::from_static("test-key")); - headers.insert( - "x-amz-server-side-encryption-customer-key-md5", - http::HeaderValue::from_static("test-key-md5"), - ); - - let metadata = HashMap::new(); - let err = validate_sse_headers_for_read(&metadata, &headers).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_sse_headers_for_read_rejects_ssec_on_managed_object() { - let mut headers = HeaderMap::new(); - headers.insert( - "x-amz-server-side-encryption-customer-algorithm", - http::HeaderValue::from_static("AES256"), - ); - headers.insert("x-amz-server-side-encryption-customer-key", http::HeaderValue::from_static("test-key")); - headers.insert( - "x-amz-server-side-encryption-customer-key-md5", - http::HeaderValue::from_static("test-key-md5"), - ); - - let metadata = HashMap::from([("x-amz-server-side-encryption".to_string(), "aws:kms".to_string())]); - let err = validate_sse_headers_for_read(&metadata, &headers).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - - #[test] - fn test_validate_sse_headers_for_read_allows_encrypted_object_without_request_headers() { - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), "aws:kms".to_string()), - ("x-rustfs-encryption-key".to_string(), "encrypted-key".to_string()), - ]); - let headers = HeaderMap::new(); - assert!(validate_sse_headers_for_read(&metadata, &headers).is_ok()); - } - - #[test] - fn test_validate_sse_headers_for_read_rejects_sse_on_ssec_object() { - let mut headers = HeaderMap::new(); - headers.insert("x-amz-server-side-encryption", http::HeaderValue::from_static("aws:kms")); - headers.insert("x-amz-server-side-encryption-aws-kms-key-id", http::HeaderValue::from_static("test-key")); - - let metadata = HashMap::from([("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string())]); - let err = validate_sse_headers_for_read(&metadata, &headers).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - } - #[test] fn test_map_get_object_reader_error_converts_missing_ssec_headers_to_invalid_request() { let err = map_get_object_reader_error(StorageError::other("missing SSE-C algorithm header")); @@ -8515,7 +930,7 @@ pub(crate) mod tests { #[test] fn test_map_get_object_reader_error_preserves_typed_service_unavailable() { let resolution_error = - super::EncryptionResolutionError::new(EncryptionResolutionErrorKind::ServiceUnavailable, "KMS unavailable"); + EncryptionResolutionError::new(EncryptionResolutionErrorKind::ServiceUnavailable, "KMS unavailable"); let err = map_get_object_reader_error(StorageError::other(resolution_error)); assert_eq!(err.code, S3ErrorCode::ServiceUnavailable); assert_eq!(err.message, "KMS unavailable"); @@ -8527,20 +942,20 @@ pub(crate) mod tests { #[test] fn test_map_get_object_reader_error_reports_missing_kms_key_as_client_error() { let resolution_error = - super::EncryptionResolutionError::new(EncryptionResolutionErrorKind::KeyNotFound, "KMS key not found: finance-key"); + EncryptionResolutionError::new(EncryptionResolutionErrorKind::KeyNotFound, "KMS key not found: finance-key"); let err = map_get_object_reader_error(StorageError::other(resolution_error)); - assert_eq!(err.code, S3ErrorCode::Custom(crate::error::KMS_KEY_NOT_FOUND_ERROR_CODE.into())); + assert_eq!(err.code, S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into())); assert_eq!(err.message, "KMS key not found: finance-key"); let s3_error = rustfs_s3_types::S3Error::from(err); assert_eq!(s3_error.status_code(), Some(http::StatusCode::BAD_REQUEST)); - let denied = map_get_object_reader_error(StorageError::other(super::EncryptionResolutionError::new( + let denied = map_get_object_reader_error(StorageError::other(EncryptionResolutionError::new( EncryptionResolutionErrorKind::AccessDenied, "Access Denied", ))); assert_eq!(denied.code, S3ErrorCode::AccessDenied); - let unsupported = map_get_object_reader_error(StorageError::other(super::EncryptionResolutionError::new( + let unsupported = map_get_object_reader_error(StorageError::other(EncryptionResolutionError::new( EncryptionResolutionErrorKind::NotImplemented, "backend cannot unwrap legacy envelopes", ))); @@ -8568,368 +983,12 @@ pub(crate) mod tests { assert!(matches!(source, StorageError::Io(io_error) if io_error.to_string().contains("plain io failure"))); } - #[test] - fn test_validate_ssec_params_returns_invalid_request_on_bad_algorithm() { - let key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let key_md5 = md5_base64([42u8; 32]); - let params = SsecParams { - algorithm: "AES128".to_string(), - key, - key_md5, - }; - let err = validate_ssec_params(params).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn test_validate_ssec_params_returns_invalid_request_on_bad_md5() { - let key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let params = SsecParams { - algorithm: "AES256".to_string(), - key, - key_md5: BASE64_STANDARD.encode_to_string([99u8; 16]), - }; - let err = validate_ssec_params(params).unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - } - - // ======================================================================== - // Unit tests for issue #2041: no mandatory KMS when encryption not used - // ======================================================================== - - /// When SSE-C params are not present and no managed SSE is requested, - /// encryption should be skipped (Ok(None)). Ensures we do not require KMS - /// when the client sends no encryption headers. - #[tokio::test] - async fn test_sse_encryption_skip_when_no_ssec_and_no_managed_sse_requested() { - let request = EncryptionRequest { - bucket: "test-bucket", - key: "test-key", - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 1024, - principal: None, - }; - let result = sse_encryption(request).await; - match &result { - Ok(None) => {} - Ok(Some(_)) => panic!("expected no encryption material when no SSE params provided"), - Err(e) => { - assert!( - !e.message.contains("No KMS key"), - "must not require KMS when no encryption requested; got: {}", - e.message - ); - } - } - } - - /// When SSE-C params are partial or invalid, sse_encryption must return an error. - #[tokio::test] - async fn test_sse_encryption_errors_on_invalid_ssec_params() { - let bucket = "test-bucket"; - let key = "test-key"; - let sse_key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let wrong_md5 = BASE64_STANDARD.encode_to_string([99u8; 16]); - - let request_wrong_md5 = EncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(sse_key.clone()), - sse_customer_key_md5: Some(wrong_md5), - content_size: 1024, - principal: None, - }; - let err = sse_encryption(request_wrong_md5).await.unwrap_err(); - assert_eq!(err.code, S3ErrorCode::InvalidRequest); - - let request_unsupported_algorithm = EncryptionRequest { - bucket, - key, - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("unsupported-algo".to_string()), - sse_customer_key: Some(sse_key), - sse_customer_key_md5: Some(md5_base64([42u8; 32])), - content_size: 1024, - principal: None, - }; - let err = sse_encryption(request_unsupported_algorithm).await.unwrap_err(); - assert!(err.code == S3ErrorCode::InvalidRequest || err.code == S3ErrorCode::InvalidArgument); - } - - /// When bucket has no SSE-S3/aws:kms setting and request has no SSE headers, - /// encryption should be skipped (Ok(None)). Ensures no mandatory bucket default SSE. - #[tokio::test] - async fn test_sse_prepare_encryption_skip_when_no_params_and_no_bucket_sse() { - let request = PrepareEncryptionRequest { - bucket: "test-bucket-no-sse-config", - key: "test-key", - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }; - let result = sse_prepare_encryption(request).await; - match &result { - Ok(None) => {} - Ok(Some(_)) => panic!("expected no encryption when bucket has no SSE config and no request SSE"), - Err(e) => { - assert!( - !e.message.contains("No KMS key"), - "must not require KMS when no bucket SSE and no request SSE; got: {}", - e.message - ); - } - } - } - - // ------------------------------------------------------------------------ - // Per-key KMS authorization on the SSE-KMS data path (rustfs/backlog#1582) - // ------------------------------------------------------------------------ - - pub(crate) struct RecordingKmsKeyAuthorizer { - allowed: bool, - calls: std::sync::Mutex>, - } - - impl RecordingKmsKeyAuthorizer { - pub(crate) fn new(allowed: bool) -> Arc { - Arc::new(Self { - allowed, - calls: std::sync::Mutex::new(Vec::new()), - }) - } - - pub(crate) fn calls(&self) -> Vec<(KmsAction, String)> { - self.calls.lock().expect("authorizer call log").clone() - } - } - - #[async_trait] - impl KmsKeyAuthorizer for RecordingKmsKeyAuthorizer { - async fn is_allowed(&self, _principal: &SseKmsPrincipal, action: KmsAction, key_id: &str) -> Result { - self.calls - .lock() - .expect("authorizer call log") - .push((action, key_id.to_string())); - Ok(self.allowed) - } - } - - fn enforcing_principal(allowed: bool) -> (SseKmsPrincipal, Arc) { - let authorizer = RecordingKmsKeyAuthorizer::new(allowed); - (SseKmsPrincipal::for_test("analyst", true, authorizer.clone()), authorizer) - } - - fn permissive_principal_with_enforcement_off() -> (SseKmsPrincipal, Arc) { - let authorizer = RecordingKmsKeyAuthorizer::new(false); - (SseKmsPrincipal::for_test("analyst", false, authorizer.clone()), authorizer) - } - - fn sse_kms_write(principal: Option<&SseKmsPrincipal>) -> EncryptionRequest<'_> { - EncryptionRequest { - bucket: "finance", - key: "ledger.csv", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), - ssekms_key_id: Some("finance-key".to_string()), - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 128, - principal, - } - } - - pub(crate) fn sse_kms_object_metadata() -> HashMap { - 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()), - ]) - } - - fn sse_s3_object_metadata() -> HashMap { - HashMap::from([ - ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.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(), "AES256".to_string()), - ]) - } - - #[test] - fn kms_authorization_subject_scopes_to_enforced_sse_kms_requests_only() { - let (principal, _) = enforcing_principal(true); - - assert!(super::kms_authorization_subject(true, Some(&principal), SSEType::SseKms).is_some()); - // Compatibility switch off keeps the pre-enforcement behaviour. - assert!(super::kms_authorization_subject(false, Some(&principal), SSEType::SseKms).is_none()); - // SSE-S3 and SSE-C are exempt, matching AWS. - assert!(super::kms_authorization_subject(true, Some(&principal), SSEType::SseS3).is_none()); - assert!(super::kms_authorization_subject(true, Some(&principal), SSEType::SseC).is_none()); - // No principal means an internal caller. - assert!(super::kms_authorization_subject(true, None, SSEType::SseKms).is_none()); - } - - #[tokio::test] - async fn sse_kms_write_without_generate_data_key_is_denied() { - let (principal, authorizer) = enforcing_principal(false); - - let error = sse_encryption(sse_kms_write(Some(&principal))) - .await - .expect_err("SSE-KMS write must fail without kms:GenerateDataKey on the key"); - - assert_eq!(error.code, S3ErrorCode::AccessDenied); - assert_eq!(authorizer.calls(), vec![(KmsAction::GenerateDataKeyAction, "finance-key".to_string())]); - } - - #[tokio::test] - async fn sse_kms_write_with_generate_data_key_clears_the_gate() { - let (principal, authorizer) = enforcing_principal(true); - - let outcome = sse_encryption(sse_kms_write(Some(&principal))).await; - - assert!( - !matches!(&outcome, Err(error) if error.code == S3ErrorCode::AccessDenied), - "granting kms:GenerateDataKey on the key must clear the authorization gate" - ); - assert_eq!(authorizer.calls(), vec![(KmsAction::GenerateDataKeyAction, "finance-key".to_string())]); - } - - #[tokio::test] - async fn sse_kms_read_without_decrypt_is_denied() { - let (principal, authorizer) = enforcing_principal(false); - let metadata = sse_kms_object_metadata(); - - let error = 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("SSE-KMS read must fail without kms:Decrypt on the key"); - - assert_eq!(error.code, S3ErrorCode::AccessDenied); - assert_eq!(authorizer.calls(), vec![(KmsAction::DecryptAction, "finance-key".to_string())]); - } - - #[tokio::test] - async fn sse_s3_objects_are_exempt_from_kms_key_authorization() { - let (principal, authorizer) = enforcing_principal(false); - let metadata = sse_s3_object_metadata(); - - let write = sse_encryption(EncryptionRequest { - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), - ssekms_key_id: None, - ..sse_kms_write(Some(&principal)) - }) - .await; - let read = sse_decryption(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: Some(&principal), - }) - .await; - - assert!(!matches!(&write, Err(error) if error.code == S3ErrorCode::AccessDenied)); - assert!(!matches!(&read, Err(error) if error.code == S3ErrorCode::AccessDenied)); - assert!(authorizer.calls().is_empty(), "SSE-S3 must never consult KMS key policy"); - } - - #[tokio::test] - async fn ssec_requests_are_exempt_from_kms_key_authorization() { - let (principal, authorizer) = enforcing_principal(false); - let customer_key = BASE64_STANDARD.encode_to_string([42u8; 32]); - let customer_key_md5 = md5_base64([42u8; 32]); - - let outcome = sse_encryption(EncryptionRequest { - server_side_encryption: None, - ssekms_key_id: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(customer_key), - sse_customer_key_md5: Some(customer_key_md5), - ..sse_kms_write(Some(&principal)) - }) - .await; - - assert!(outcome.is_ok(), "SSE-C must not be gated on KMS key policy"); - assert!(authorizer.calls().is_empty(), "SSE-C never reaches KMS"); - } - - #[tokio::test] - async fn internal_callers_bypass_kms_key_authorization() { - let metadata = sse_kms_object_metadata(); - - // No principal: replication, lifecycle transition, heal and scanner reach the SSE - // layer below the S3 authorization boundary and must not be interrupted. - let write = sse_encryption(sse_kms_write(None)).await; - let read = sse_decryption(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await; - - assert!(!matches!(&write, Err(error) if error.code == S3ErrorCode::AccessDenied)); - assert!(!matches!(&read, Err(error) if error.code == S3ErrorCode::AccessDenied)); - } - - #[tokio::test] - async fn enforcement_switch_off_preserves_current_behaviour() { - let (principal, authorizer) = permissive_principal_with_enforcement_off(); - let metadata = sse_kms_object_metadata(); - - let write = sse_encryption(sse_kms_write(Some(&principal))).await; - let read = sse_decryption(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: Some(&principal), - }) - .await; - - assert!(!matches!(&write, Err(error) if error.code == S3ErrorCode::AccessDenied)); - assert!(!matches!(&read, Err(error) if error.code == S3ErrorCode::AccessDenied)); - assert!( - authorizer.calls().is_empty(), - "with the switch off the data path must not evaluate KMS key policy at all" - ); - } - #[tokio::test] async fn completion_authorization_preserves_typed_denials_and_redacts_customer_keys() { let key = multipart_ssec_request(42).sse_customer_key.expect("test key"); let mut metadata = multipart_ssec_metadata(42); rustfs_utils::http::insert_str(&mut metadata, rustfs_utils::http::SUFFIX_PLAINTEXT_CHECKSUM, "true".to_string()); - let no_key = super::multipart_completion_authorization( + let no_key = multipart_completion_authorization( EncryptionRequest { sse_customer_algorithm: None, sse_customer_key: None, @@ -8941,7 +1000,7 @@ pub(crate) mod tests { let error = no_key.authorize(&metadata).await.expect_err("customer key required"); assert_eq!(map_get_object_reader_error(error).code, S3ErrorCode::InvalidRequest); let (denied, _) = enforcing_principal(false); - let denied = super::multipart_completion_authorization( + let denied = multipart_completion_authorization( EncryptionRequest { principal: Some(&denied), ..multipart_ssec_request(42) @@ -8950,7 +1009,7 @@ pub(crate) mod tests { ); let error = denied.authorize(&sse_kms_object_metadata()).await.expect_err("KMS denied"); assert_eq!(map_get_object_reader_error(error).code, S3ErrorCode::AccessDenied); - let valid = super::multipart_completion_authorization(multipart_ssec_request(42), false); + let valid = multipart_completion_authorization(multipart_ssec_request(42), false); valid.authorize(&metadata).await.expect("correct customer key"); let opts = crate::storage::ObjectOptions { multipart_completion_authorization: Some(valid), @@ -8962,517 +1021,16 @@ pub(crate) mod tests { ); } - #[tokio::test] - async fn multipart_write_authorization_uses_stored_key_and_current_principal() { - let (denied, denied_authorizer) = enforcing_principal(false); - let (allowed, allowed_authorizer) = enforcing_principal(true); - let metadata = sse_kms_object_metadata(); - let error = super::authorize_sse_kms_multipart_write(Some(&denied), &metadata) - .await - .expect_err("upload ID must not grant its creator's KMS permission"); - assert_eq!(error.code, S3ErrorCode::AccessDenied); - assert_eq!( - denied_authorizer.calls(), - vec![(KmsAction::GenerateDataKeyAction, "finance-key".to_string())] - ); - super::authorize_sse_kms_multipart_write(Some(&allowed), &metadata) - .await - .expect("authorized writer"); - assert_eq!( - allowed_authorizer.calls(), - vec![(KmsAction::GenerateDataKeyAction, "finance-key".to_string())] - ); - for metadata in [HashMap::new(), sse_s3_object_metadata(), multipart_ssec_metadata(42)] { - super::authorize_sse_kms_multipart_write(Some(&denied), &metadata) - .await - .expect("non-KMS upload"); - } - assert_eq!(denied_authorizer.calls().len(), 1); - let (off, off_authorizer) = permissive_principal_with_enforcement_off(); - super::authorize_sse_kms_multipart_write(Some(&off), &metadata) - .await - .expect("enforcement off"); - super::authorize_sse_kms_multipart_write(None, &metadata) - .await - .expect("trusted internal writer"); - assert!(off_authorizer.calls().is_empty()); - } - - #[tokio::test] - async fn copy_source_read_authorization_targets_the_source_key() { - let (denied, denied_authorizer) = enforcing_principal(false); - let (allowed, allowed_authorizer) = enforcing_principal(true); - let metadata = sse_kms_object_metadata(); - - let error = authorize_sse_kms_object_read(Some(&denied), &metadata) - .await - .expect_err("copying an SSE-KMS source must require kms:Decrypt on the source key"); - assert_eq!(error.code, S3ErrorCode::AccessDenied); - assert_eq!(denied_authorizer.calls(), vec![(KmsAction::DecryptAction, "finance-key".to_string())]); - - authorize_sse_kms_object_read(Some(&allowed), &metadata) - .await - .expect("kms:Decrypt on the source key must allow the copy"); - assert_eq!(allowed_authorizer.calls(), vec![(KmsAction::DecryptAction, "finance-key".to_string())]); - } - - #[tokio::test] - async fn copy_source_read_authorization_skips_unencrypted_and_sse_s3_sources() { - let (principal, authorizer) = enforcing_principal(false); - - authorize_sse_kms_object_read(Some(&principal), &HashMap::new()) - .await - .expect("plaintext sources are not gated"); - authorize_sse_kms_object_read(Some(&principal), &sse_s3_object_metadata()) - .await - .expect("SSE-S3 sources are not gated"); - - assert!(authorizer.calls().is_empty()); - } - - // ======================================================================== - // Data-plane KMS audit attachment - // ======================================================================== - - fn audited_principal(enforced: bool, allowed: bool) -> (SseKmsPrincipal, Arc) { - let audit = Arc::new(super::KmsRequestAudit::default()); - let authorizer = RecordingKmsKeyAuthorizer::new(allowed); - let principal = SseKmsPrincipal::for_test("analyst", enforced, authorizer).with_request_audit(audit.clone()); - (principal, audit) - } - - fn audit_tag(tags: &[(&'static str, serde_json::Value)], key: &str) -> Option { - tags.iter() - .find(|(candidate, _)| *candidate == key) - .and_then(|(_, value)| value.as_str().map(str::to_string)) - } - - #[tokio::test] - async fn sse_kms_write_and_read_summarise_key_id_and_outcome_for_the_audit_entry() { - use rustfs_kms::types::{CreateKeyRequest, KeyUsage}; - let _guard = lock_sse_test_state().await; - - reset_sse_dek_provider(); - let manager = configure_test_global_local_kms().await; - manager - .get_encryption_service() - .await - .expect("encryption service should exist") - .create_key(CreateKeyRequest { - key_name: Some("audit-key".to_string()), - key_usage: KeyUsage::EncryptDecrypt, - description: None, - policy: None, - tags: HashMap::new(), - origin: None, - }) - .await - .expect("kms test key should be created"); - let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) - .await - .expect("kms provider should initialize from the configured test manager"); - super::set_sse_dek_provider_for_test(Arc::new(provider)); - - let (write_principal, write_audit) = audited_principal(false, true); - let material = sse_encryption(EncryptionRequest { - bucket: "finance", - key: "ledger.csv", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), - ssekms_key_id: Some("audit-key".to_string()), - ssekms_context: Some(HashMap::from([("tenant".to_string(), "acct-4711".to_string())])), - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 128, - principal: Some(&write_principal), - }) - .await - .expect("sse-kms encryption should succeed") - .expect("managed sse-kms material"); - - let write_tags = write_audit.audit_tags(); - assert_eq!(audit_tag(&write_tags, "sseType").as_deref(), Some("SSE-KMS")); - assert_eq!(audit_tag(&write_tags, "kmsKeyId").as_deref(), Some("audit-key")); - assert_eq!(audit_tag(&write_tags, "kmsOutcome").as_deref(), Some("success")); - assert_eq!(audit_tag(&write_tags, "kmsErrorClass"), None, "a successful request has no error class"); - - // The audit entry reaches every configured target: no encoding of the data - // key, and no caller-supplied encryption-context value, may appear in it. - let rendered = format!("{write_tags:?}"); - let encrypted_data_key = material.encrypted_data_key.clone().expect("managed sse wraps a data key"); - for secret in [ - BASE64_STANDARD.encode_to_string(&encrypted_data_key), - BASE64_STANDARD.encode_to_string(material.key_bytes), - format!("{:?}", material.key_bytes), - format!("{encrypted_data_key:?}"), - "acct-4711".to_string(), - ] { - assert!(!rendered.contains(&secret), "audit tags must not carry key material: {rendered}"); - } - - let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); - let (read_principal, read_audit) = audited_principal(false, true); - sse_decryption(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: Some(&read_principal), - }) - .await - .expect("sse-kms decryption should succeed") - .expect("managed sse-kms material"); - - let read_tags = read_audit.audit_tags(); - assert_eq!(audit_tag(&read_tags, "sseType").as_deref(), Some("SSE-KMS")); - assert_eq!(audit_tag(&read_tags, "kmsKeyId").as_deref(), Some("audit-key")); - assert_eq!(audit_tag(&read_tags, "kmsOutcome").as_deref(), Some("success")); - } - - async fn install_test_kms_provider(key_name: &str) { - use rustfs_kms::types::{CreateKeyRequest, KeyUsage}; - - reset_sse_dek_provider(); - let manager = configure_test_global_local_kms().await; - manager - .get_encryption_service() - .await - .expect("encryption service should exist") - .create_key(CreateKeyRequest { - key_name: Some(key_name.to_string()), - key_usage: KeyUsage::EncryptDecrypt, - description: None, - policy: None, - tags: HashMap::new(), - origin: None, - }) - .await - .expect("kms test key should be created"); - let provider = KmsSseDekProvider::new_with_service_manager(manager) - .await - .expect("kms provider should initialize from the configured test manager"); - super::set_sse_dek_provider_for_test(Arc::new(provider)); - } - - fn sse_kms_request<'a>(bucket: &'a str, key: &'a str, context: HashMap) -> EncryptionRequest<'a> { - EncryptionRequest { - bucket, - key, - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), - ssekms_key_id: Some("binding-key".to_string()), - ssekms_context: Some(context), - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 64, - principal: None, - } - } - - #[tokio::test] - async fn sse_kms_write_rejects_a_context_key_equal_to_the_bucket_name() { - let _guard = lock_sse_test_state().await; - install_test_kms_provider("binding-key").await; - let context = HashMap::from([("finance".to_string(), "finance/elsewhere".to_string())]); - - let err = sse_encryption(sse_kms_request("finance", "ledger.csv", context.clone())) - .await - .expect_err("a context entry under the bucket name must be rejected"); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - assert!( - err.message.contains("\"finance\""), - "the message must name the offending key: {}", - err.message - ); - - // CreateMultipartUpload generates the session data key through the - // prepare path; it must refuse the same context. - let err = sse_prepare_encryption(PrepareEncryptionRequest { - bucket: "finance", - key: "ledger.csv", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), - ssekms_key_id: Some("binding-key".to_string()), - ssekms_context: Some(context), - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect_err("the multipart prepare path must reject the same context"); - assert_eq!(err.code, S3ErrorCode::InvalidArgument); - - reset_sse_dek_provider(); - } - - #[tokio::test] - async fn sse_kms_write_keeps_the_location_binding_when_the_context_names_another_bucket() { - let _guard = lock_sse_test_state().await; - install_test_kms_provider("binding-key").await; - let context = HashMap::from([ - ("archive".to_string(), "archive/ledger.csv".to_string()), - ("tenant".to_string(), "acct-4711".to_string()), - ]); - - let material = sse_encryption(sse_kms_request("finance", "ledger.csv", context)) - .await - .expect("a key naming a different bucket is an ordinary context entry") - .expect("managed sse-kms material"); - let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); - - let read = |key: &'static str| { - let metadata = metadata.clone(); - async move { - sse_decryption(DecryptionRequest { - bucket: "finance", - key, - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - } - }; - let decrypted = read("ledger.csv") - .await - .expect("the object decrypts at its own location") - .expect("managed sse-kms material"); - assert_eq!(decrypted.key_bytes, material.key_bytes); - read("relocated.csv") - .await - .expect_err("the data key stays bound to the object's location"); - - reset_sse_dek_provider(); - } - - #[tokio::test] - async fn sse_kms_objects_stored_with_a_bucket_keyed_context_stay_readable() { - let _guard = lock_sse_test_state().await; - install_test_kms_provider("binding-key").await; - let context = HashMap::from([("finance".to_string(), "finance/elsewhere".to_string())]); - - // Objects written before the write-side rejection reached the inner - // routine without validation; reproduce that stored shape directly. - let material = apply_managed_encryption_material_inner( - "finance", - "ledger.csv", - String::from(AMZ_ENCRYPTION_KMS), - Some("binding-key".to_string()), - Some(context), - 64, - None, - ) - .await - .expect("the inner routine does not validate the client context"); - let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); - - let decrypted = sse_decryption(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect("an existing object must stay readable after the write-side rejection") - .expect("managed sse-kms material"); - assert_eq!(decrypted.key_bytes, material.key_bytes); - - reset_sse_dek_provider(); - } - - #[tokio::test] - async fn sse_c_requests_produce_no_kms_audit_summary() { - let key = [0x21u8; 32]; - let (principal, audit) = audited_principal(false, true); - - sse_encryption(EncryptionRequest { - bucket: "finance", - key: "ledger.csv", - server_side_encryption: None, - ssekms_key_id: None, - ssekms_context: None, - sse_customer_algorithm: Some("AES256".to_string()), - sse_customer_key: Some(BASE64_STANDARD.encode_to_string(key)), - sse_customer_key_md5: Some(md5_base64(key)), - content_size: 128, - principal: Some(&principal), - }) - .await - .expect("sse-c encryption should succeed") - .expect("sse-c material"); - - assert!( - audit.audit_tags().is_empty(), - "SSE-C keys never reach KMS, so the request has no KMS outcome to report" - ); - } - - #[tokio::test] - async fn denied_sse_kms_read_is_summarised_as_an_access_denied_failure() { - let (principal, audit) = audited_principal(true, false); - - authorize_sse_kms_object_read(Some(&principal), &sse_kms_object_metadata()) - .await - .expect_err("an unauthorized principal must not read the source key"); - - let tags = audit.audit_tags(); - assert_eq!(audit_tag(&tags, "sseType").as_deref(), Some("SSE-KMS")); - assert_eq!(audit_tag(&tags, "kmsKeyId").as_deref(), Some("finance-key")); - assert_eq!(audit_tag(&tags, "kmsOutcome").as_deref(), Some("failure")); - assert_eq!(audit_tag(&tags, "kmsErrorClass").as_deref(), Some("access_denied")); - } - - // ======================================================================== - // Read-side response classification (single-decrypt GET path) - // ======================================================================== - - /// An AES256 object is read under the same key-id resolution as aws:kms - /// (authorization needs it), but the response must not advertise that - /// internal wrapping key. - #[tokio::test] - async fn classification_withholds_the_wrapping_key_for_sse_s3_reads() { - let metadata = HashMap::from([ - ("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_AES.to_string()), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "service-default".to_string()), - (INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string([1u8; 16])), - (INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([2u8; 12])), - ]); - let headers = super::classify_sse_read_response(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect("sse-s3 classification should succeed") - .expect("managed metadata should classify"); - assert_eq!(headers.server_side_encryption.as_str(), AMZ_ENCRYPTION_AES); - assert_eq!(headers.ssekms_key_id, None); - } - - #[tokio::test] - async fn classification_reproduces_managed_read_headers_and_audit_without_a_kms_unwrap() { - use rustfs_kms::types::{CreateKeyRequest, KeyUsage}; - let _guard = lock_sse_test_state().await; - - reset_sse_dek_provider(); - let manager = configure_test_global_local_kms().await; - manager - .get_encryption_service() - .await - .expect("encryption service should exist") - .create_key(CreateKeyRequest { - key_name: Some("classify-key".to_string()), - key_usage: KeyUsage::EncryptDecrypt, - description: None, - policy: None, - tags: HashMap::new(), - origin: None, - }) - .await - .expect("kms test key should be created"); - let provider = KmsSseDekProvider::new_with_service_manager(manager.clone()) - .await - .expect("kms provider should initialize from the configured test manager"); - super::set_sse_dek_provider_for_test(Arc::new(provider)); - - let material = sse_encryption(EncryptionRequest { - bucket: "finance", - key: "ledger.csv", - server_side_encryption: Some(String::from(AMZ_ENCRYPTION_KMS)), - ssekms_key_id: Some("classify-key".to_string()), - ssekms_context: None, - sse_customer_algorithm: None, - sse_customer_key: None, - sse_customer_key_md5: None, - content_size: 128, - principal: None, - }) - .await - .expect("sse-kms encryption should succeed") - .expect("managed sse-kms material"); - let metadata = encryption_material_to_metadata(&material).expect("kms metadata should serialize"); - - // Header parity against the unwrap-based path, on the same metadata. - let unwrapped = sse_decryption(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect("sse-kms decryption should succeed") - .expect("managed sse-kms material"); - - // Classification must not need a data-key unwrap at all: drop the - // provider before classifying, so any KMS round trip would fail loudly. - reset_sse_dek_provider(); - - let (read_principal, read_audit) = audited_principal(false, true); - let headers = classify_sse_read_response(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: Some(&read_principal), - }) - .await - .expect("classification should succeed without a dek provider") - .expect("managed metadata must classify as encrypted"); - - assert_eq!(headers.server_side_encryption, unwrapped.server_side_encryption); - assert_eq!(headers.ssekms_key_id, unwrapped.kms_key_id); - assert_eq!(headers.sse_customer_algorithm, None); - assert_eq!(headers.sse_customer_key_md5, None); - - // Audit parity: the same summary fields the unwrap-based read recorded. - let read_tags = read_audit.audit_tags(); - assert_eq!(audit_tag(&read_tags, "sseType").as_deref(), Some("SSE-KMS")); - assert_eq!(audit_tag(&read_tags, "kmsKeyId").as_deref(), Some("classify-key")); - assert_eq!(audit_tag(&read_tags, "kmsOutcome").as_deref(), Some("success")); - assert_eq!(audit_tag(&read_tags, "kmsErrorClass"), None); - } - - #[tokio::test] - async fn classification_denies_an_unauthorized_principal_with_the_same_audit_summary() { - let (principal, audit) = audited_principal(true, false); - - let error = classify_sse_read_response(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &sse_kms_object_metadata(), - sse_customer_key: None, - sse_customer_key_md5: None, - principal: Some(&principal), - }) - .await - .expect_err("an unauthorized principal must not classify against the key"); - assert_eq!(error.code, S3ErrorCode::AccessDenied); - - let tags = audit.audit_tags(); - assert_eq!(audit_tag(&tags, "sseType").as_deref(), Some("SSE-KMS")); - assert_eq!(audit_tag(&tags, "kmsKeyId").as_deref(), Some("finance-key")); - assert_eq!(audit_tag(&tags, "kmsOutcome").as_deref(), Some("failure")); - assert_eq!(audit_tag(&tags, "kmsErrorClass").as_deref(), Some("access_denied")); - } - #[tokio::test] async fn conditional_read_denies_kms_before_unwrap_with_normalized_metadata() { - let (principal, audit) = audited_principal(true, false); + let request_id = "conditional-read-denies-kms-before-unwrap"; + let audit = KmsRequestAuditScope::register(request_id); + let principal = principal_with_authorizer(true, RecordingKmsKeyAuthorizer::new(false)).with_request_id(request_id); let metadata = sse_kms_object_metadata() .into_iter() .map(|(name, value)| (name.to_ascii_uppercase(), value)) .collect(); - let error = super::validate_conditional_read("finance", "ledger.csv", &metadata, &HeaderMap::new(), Some(&principal)) + let error = validate_conditional_read("finance", "ledger.csv", &metadata, &HeaderMap::new(), Some(&principal)) .await .expect_err("conditional read must authorize the real key before unwrap"); assert_eq!(error.code, S3ErrorCode::AccessDenied); @@ -9480,361 +1038,167 @@ pub(crate) mod tests { } #[cfg(feature = "rio-v2")] - #[tokio::test] - async fn conditional_read_denies_minio_only_kms_before_unwrap() { - let (principal, authorizer) = enforcing_principal(false); - let metadata = HashMap::from([ - (super::MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_owned(), "sealed-key".to_owned()), - (super::MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_owned(), "finance-key".to_owned()), - ]); - let error = super::validate_conditional_read("finance", "ledger.csv", &metadata, &HeaderMap::new(), Some(&principal)) - .await - .expect_err("MinIO metadata must not bypass KMS authorization"); - assert_eq!(error.code, S3ErrorCode::AccessDenied); - assert_eq!(authorizer.calls(), vec![(KmsAction::DecryptAction, "finance-key".to_owned())]); - } + mod rio_v2 { + use super::{BASE64_STANDARD, enforcing_principal, md5_base64, ssec_read_headers}; + use crate::storage::sse::{ + EncryptionKeyKind, EncryptionRequest, ObjectEncryptionResolver, ReadEncryptionMode, ReadEncryptionRequest, + SseObjectEncryptionResolver, encryption_material_to_metadata, reset_sse_dek_provider, sse_encryption, + validate_conditional_read, + }; + use http::HeaderMap; + use rustfs_policy::policy::action::KmsAction; + use rustfs_s3_types::S3ErrorCode; + use rustfs_utils::http::headers::AMZ_ENCRYPTION_AES; + use rustfs_utils::http::object_encryption_keys::{ + MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER, + }; + use std::collections::HashMap; + use std::sync::OnceLock; + use temp_env::async_with_vars; + use tokio::sync::Mutex; - #[test] - fn read_response_projection_uses_shared_managed_metadata_compatibility() { - let context_json = r#"{"tenant":"s3-select"}"#; - let context = BASE64_STANDARD.encode_to_string(context_json); - let key_id = "arn:aws:kms:us-east-1:123456789012:key/select"; - let kms_metadata = HashMap::from([ - (super::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), super::AMZ_ENCRYPTION_KMS.to_string()), - (super::AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID.to_string(), key_id.to_string()), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), key_id.to_string()), - (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_string(), key_id.to_string()), - (MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), context.clone()), - ]); + static SSE_TEST_LOCK: OnceLock> = OnceLock::new(); - let headers = project_sse_read_response_headers(&kms_metadata, None, None) - .expect("valid SSE-KMS metadata should project response headers"); - assert_eq!( - headers.get(super::X_AMZ_SERVER_SIDE_ENCRYPTION).expect("SSE-KMS algorithm"), - super::AMZ_ENCRYPTION_KMS - ); - assert_eq!( - headers - .get(super::X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID) - .expect("SSE-KMS key ID"), - key_id - ); - assert_eq!( - headers - .get(super::X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT) - .expect("SSE-KMS context"), - context.as_str() - ); + async fn lock_sse_test_state() -> tokio::sync::MutexGuard<'static, ()> { + SSE_TEST_LOCK.get_or_init(|| Mutex::new(())).lock().await + } - let s3_metadata = HashMap::from([ - (super::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), super::AMZ_ENCRYPTION_AES.to_string()), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "default".to_string()), - (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_string(), "default".to_string()), - ( - super::INTERNAL_ENCRYPTION_CONTEXT_HEADER.to_string(), - r#"{"bucket":"select"}"#.to_string(), - ), - ("x-amz-meta-private".to_string(), "private".to_string()), - ]); - let headers = project_sse_read_response_headers(&s3_metadata, None, None) - .expect("valid SSE-S3 metadata should project response headers"); - assert_eq!(headers.len(), 1); - assert_eq!( - headers.get(super::X_AMZ_SERVER_SIDE_ENCRYPTION).expect("SSE-S3 algorithm"), - super::AMZ_ENCRYPTION_AES - ); - - let plaintext = project_sse_read_response_headers(&HashMap::new(), None, None) - .expect("plaintext metadata should not produce SSE headers"); - assert!(plaintext.is_empty()); - } - - #[test] - fn read_response_projection_returns_only_validated_ssec_values() { - let key_md5 = "customer-key-md5"; - let metadata = HashMap::from([ - ( - super::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM.to_string(), - super::AMZ_ENCRYPTION_AES.to_string(), - ), - (super::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5.to_string(), key_md5.to_string()), - ]); - let algorithm = String::from(super::AMZ_ENCRYPTION_AES); - let key_md5 = String::from(key_md5); - - let headers = project_sse_read_response_headers(&metadata, Some(&algorithm), Some(&key_md5)) - .expect("validated SSE-C values should project response headers"); - assert_eq!(headers.len(), 2); - assert_eq!( - headers - .get(super::X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM) - .expect("SSE-C algorithm"), - super::AMZ_ENCRYPTION_AES - ); - assert_eq!( - headers - .get(super::X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5) - .expect("SSE-C key MD5"), - key_md5.as_str() - ); - assert!(headers.get(super::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY).is_none()); - - let missing_algorithm = project_sse_read_response_headers(&metadata, None, Some(&key_md5)) - .expect_err("missing SSE-C algorithm must fail before streaming"); - assert_eq!(missing_algorithm.code, S3ErrorCode::InvalidRequest); - } - - #[test] - fn read_response_projection_rejects_unvalidated_or_sensitive_metadata() { - let invalid_context = "not-base64"; - let persisted_context = "must-not-leak-context"; - let persisted_key = "must-not-leak-key"; - let corrupt_metadata = [ - HashMap::from([ - ( - super::AMZ_SERVER_SIDE_ENCRYPTION.to_ascii_lowercase(), - super::AMZ_ENCRYPTION_AES.to_string(), - ), - ( - super::AMZ_SERVER_SIDE_ENCRYPTION.to_ascii_uppercase(), - super::AMZ_ENCRYPTION_KMS.to_string(), - ), - ]), - HashMap::from([ - (super::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), super::AMZ_ENCRYPTION_KMS.to_string()), - ( - super::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM.to_string(), - super::AMZ_ENCRYPTION_AES.to_string(), - ), - ]), - HashMap::from([ - (super::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), super::AMZ_ENCRYPTION_KMS.to_string()), - (super::AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID.to_string(), "key-1".to_string()), - (INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "key-2".to_string()), - ]), - HashMap::from([ - (super::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), super::AMZ_ENCRYPTION_KMS.to_string()), - (super::AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID.to_string(), "key-1".to_string()), - (MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), invalid_context.to_string()), - ]), - HashMap::from([ - (super::AMZ_SERVER_SIDE_ENCRYPTION.to_string(), super::AMZ_ENCRYPTION_KMS.to_string()), - (super::AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID.to_string(), "key-1".to_string()), - (super::AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT.to_string(), persisted_context.to_string()), - ]), - HashMap::from([ - ( - super::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM.to_string(), - super::AMZ_ENCRYPTION_AES.to_string(), - ), - ( - super::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5.to_string(), - "customer-key-md5".to_string(), - ), - ( - super::AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY.to_ascii_uppercase(), - persisted_key.to_string(), - ), - ]), - ]; - - for metadata in corrupt_metadata { - let error = project_sse_read_response_headers(&metadata, None, None) - .expect_err("corrupt encryption metadata must fail closed"); - assert_eq!(error.code, S3ErrorCode::InternalError); - for sensitive in [invalid_context, persisted_context, persisted_key] { - assert!(!error.to_string().contains(sensitive)); + fn ssec_write(customer_key: &str, customer_key_md5: &str) -> EncryptionRequest<'static> { + EncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: None, + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: Some("AES256".to_string()), + sse_customer_key: Some(customer_key.to_string()), + sse_customer_key_md5: Some(customer_key_md5.to_string()), + content_size: 4096, + principal: None, } } - let marker_only_kms = - HashMap::from([(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), "sealed".to_string())]); - let marker_error = project_sse_read_response_headers(&marker_only_kms, None, None) - .expect_err("marker-only KMS metadata must not bypass the existing authorization classifier"); - assert_eq!(marker_error.code, S3ErrorCode::InternalError); - } - - #[tokio::test] - async fn classification_matches_ssec_validation_and_headers() { - let key = [0x42u8; 32]; - let key_b64 = BASE64_STANDARD.encode_to_string(key); - let key_md5 = md5_base64(key); - let metadata = HashMap::from([ - ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()), - ("x-amz-server-side-encryption-customer-key-md5".to_string(), key_md5.clone()), - ]); - - let headers = classify_sse_read_response(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: Some(&key_b64.clone()), - sse_customer_key_md5: Some(&key_md5.clone()), - principal: None, - }) - .await - .expect("a matching customer key should classify") - .expect("SSE-C metadata must classify as encrypted"); - assert_eq!(headers.server_side_encryption.as_str(), AMZ_ENCRYPTION_AES); - assert_eq!(headers.sse_customer_algorithm.as_deref(), Some("AES256")); - assert_eq!(headers.sse_customer_key_md5.as_deref(), Some(key_md5.as_str())); - assert_eq!(headers.ssekms_key_id, None); - - // Same error and precedence as `sse_decryption` when the key is absent… - let missing = classify_sse_read_response(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect_err("an SSE-C object must not classify without the customer key"); - assert_eq!(missing.code, S3ErrorCode::InvalidRequest); - - // …and when the provided key does not match the stored digest. - let other_key = [0x43u8; 32]; - let mismatch = classify_sse_read_response(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: Some(&BASE64_STANDARD.encode_to_string(other_key)), - sse_customer_key_md5: Some(&md5_base64(other_key)), - principal: None, - }) - .await - .expect_err("a mismatched customer key must not classify"); - let parity = sse_decryption(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &metadata, - sse_customer_key: Some(&BASE64_STANDARD.encode_to_string(other_key)), - sse_customer_key_md5: Some(&md5_base64(other_key)), - principal: None, - }) - .await - .expect_err("the unwrap-based path rejects the same mismatch"); - assert_eq!(mismatch.code, parity.code); - } - - #[tokio::test] - async fn classification_reports_plaintext_objects_as_unencrypted() { - let result = classify_sse_read_response(DecryptionRequest { - bucket: "finance", - key: "ledger.csv", - metadata: &HashMap::new(), - sse_customer_key: None, - sse_customer_key_md5: None, - principal: None, - }) - .await - .expect("plaintext metadata should classify cleanly"); - assert!(result.is_none(), "objects without SSE metadata carry no SSE response headers"); - } - - #[test] - fn kms_backend_failures_keep_the_kms_audit_error_class() { - assert_eq!( - super::kms_data_plane_error_class(&kms_operation_error(rustfs_kms::KmsError::key_not_found("finance-key"))), - "key_not_found" - ); - assert_eq!( - super::kms_data_plane_error_class(&kms_operation_error(rustfs_kms::KmsError::access_denied("nope"))), - "access_denied" - ); - // Failures raised by the SSE layer itself never saw a KmsError; they are - // classified by the boundary they surfaced through. - assert_eq!( - super::kms_data_plane_error_class(&ApiError { - code: S3ErrorCode::AccessDenied, - message: "Access Denied".to_string(), - source: None, - }), - "access_denied" - ); - assert_eq!( - super::kms_data_plane_error_class(&ApiError::from(StorageError::other("no KMS key available"))), - "sse_internal" - ); - } - - #[test] - fn a_request_audit_slot_is_reachable_only_while_its_scope_lives() { - let scope = super::KmsRequestAuditScope::register("request-under-audit"); - let slot = super::kms_request_audit("request-under-audit").expect("a registered request must resolve its slot"); - slot.record(SSEType::SseKms, Some("finance-key"), None, None); - assert_eq!(audit_tag(&scope.audit_tags(), "kmsKeyId").as_deref(), Some("finance-key")); - - drop(scope); - assert!( - super::kms_request_audit("request-under-audit").is_none(), - "the slot must not outlive the audit entry it belongs to" - ); - } - - #[test] - fn a_request_that_did_no_kms_work_reports_no_tags() { - let scope = super::KmsRequestAuditScope::register("quiet-request"); - assert!(scope.audit_tags().is_empty()); - } - - /// The canonical seven-field envelope, with `master_key_version` grafted on - /// when a wrapping version is wanted. - fn audit_test_envelope(master_key_version: Option) -> Vec { - let mut envelope = serde_json::json!({ - "key_id": "test-key-id", - "master_key_id": "master-key-id", - "key_spec": "AES_256", - "encrypted_key": [1, 2, 3, 4], - "nonce": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], - "encryption_context": {}, - "created_at": "2024-01-01T00:00:00+00:00" - }); - if let Some(version) = master_key_version { - envelope - .as_object_mut() - .expect("envelope is an object") - .insert("master_key_version".to_string(), serde_json::json!(version)); + #[tokio::test] + async fn conditional_read_denies_minio_only_kms_before_unwrap() { + let (principal, authorizer) = enforcing_principal(false); + let metadata = HashMap::from([ + (MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_owned(), "sealed-key".to_owned()), + (MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_owned(), "finance-key".to_owned()), + ]); + let error = validate_conditional_read("finance", "ledger.csv", &metadata, &HeaderMap::new(), Some(&principal)) + .await + .expect_err("MinIO metadata must not bypass KMS authorization"); + assert_eq!(error.code, S3ErrorCode::AccessDenied); + assert_eq!(authorizer.calls(), vec![(KmsAction::DecryptAction, "finance-key".to_owned())]); } - serde_json::to_vec(&envelope).expect("encode envelope") - } - #[test] - fn envelope_master_key_version_reads_only_true_envelopes() { - // A versioned envelope reports the wrapping version. - assert_eq!(super::envelope_master_key_version(&audit_test_envelope(Some(3))), Some(3)); - // A pre-versioning envelope has no version to report. - assert_eq!(super::envelope_master_key_version(&audit_test_envelope(None)), None); - // Opaque backend ciphertext (Transit, AWS) is not an envelope. - assert_eq!(super::envelope_master_key_version(b"vault:v2:abcdefgh"), None); - // JSON that is not the envelope shape must not be probed for a version. - assert_eq!(super::envelope_master_key_version(br#"{"master_key_version": 9}"#), None); - } + #[tokio::test] + async fn object_encryption_resolver_reads_managed_object_keys_in_object_mode() { + let _guard = lock_sse_test_state().await; + reset_sse_dek_provider(); + if let Some(manager) = rustfs_kms::get_global_kms_service_manager() { + let _ = manager.stop().await; + } + let local_sse_master_key = BASE64_STANDARD.encode_to_string([0x24u8; 32]); - #[test] - fn stored_envelope_master_key_version_reads_both_metadata_families() { - let envelope = BASE64_STANDARD.encode_to_string(audit_test_envelope(Some(2))); + async_with_vars( + [ + ("__RUSTFS_SSE_SIMPLE_CMK", None::<&str>), + ("RUSTFS_SSE_S3_MASTER_KEY", Some(local_sse_master_key.as_str())), + ], + async { + let material = sse_encryption(EncryptionRequest { + bucket: "bucket", + key: "object", + server_side_encryption: Some(String::from(AMZ_ENCRYPTION_AES)), + ssekms_key_id: None, + ssekms_context: None, + sse_customer_algorithm: None, + sse_customer_key: None, + sse_customer_key_md5: None, + content_size: 4096, + principal: None, + }) + .await + .expect("managed sse encryption") + .expect("managed sse material"); + assert_eq!(material.key_kind, EncryptionKeyKind::Object); + let metadata = encryption_material_to_metadata(&material).expect("managed SSE metadata should serialize"); - // RustFS-branded stored key. - let metadata = HashMap::from([(INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), envelope.clone())]); - assert_eq!(super::stored_envelope_master_key_version(&metadata), Some(2)); + let resolved = SseObjectEncryptionResolver + .resolve_read_material(ReadEncryptionRequest { + bucket: "bucket", + object: "object", + metadata: &metadata, + headers: &HeaderMap::new(), + }) + .await + .expect("managed resolver") + .expect("managed material"); + assert_eq!(resolved.mode, ReadEncryptionMode::Object); + assert_eq!(resolved.key_bytes, material.key_bytes); + }, + ) + .await; - // MinIO-branded stored key reaches the same answer through - // normalize_managed_metadata — the dual internal metadata key rule. - let metadata = HashMap::from([(super::MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), envelope)]); - assert_eq!(super::stored_envelope_master_key_version(&metadata), Some(2)); + reset_sse_dek_provider(); + } - assert_eq!(super::stored_envelope_master_key_version(&HashMap::new()), None); - } + #[tokio::test] + async fn object_encryption_resolver_reads_sealed_ssec_object_keys_in_object_mode() { + let customer_key_bytes = [0x42u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); - #[test] - fn recorded_key_versions_reach_the_audit_tags() { - let scope = super::KmsRequestAuditScope::register("versioned-request"); - let slot = super::kms_request_audit("versioned-request").expect("a registered request must resolve its slot"); - slot.record(SSEType::SseKms, Some("finance-key"), Some(3), None); - let tags = scope.audit_tags(); - assert_eq!(audit_tag(&tags, "kmsKeyVersion").as_deref(), Some("3")); - assert_eq!(audit_tag(&tags, "kmsOutcome").as_deref(), Some("success")); + let material = sse_encryption(ssec_write(&customer_key, &customer_key_md5)) + .await + .expect("sse-c encryption") + .expect("sse-c material"); + assert_eq!(material.key_kind, EncryptionKeyKind::Object); + let metadata = encryption_material_to_metadata(&material).expect("sse-c metadata should serialize"); + + let resolved = SseObjectEncryptionResolver + .resolve_read_material(ReadEncryptionRequest { + bucket: "bucket", + object: "object", + metadata: &metadata, + headers: &ssec_read_headers(&customer_key, &customer_key_md5), + }) + .await + .expect("SSE-C resolver") + .expect("SSE-C material"); + assert_eq!(resolved.mode, ReadEncryptionMode::Object); + assert_eq!(resolved.key_bytes, material.key_bytes); + } + + /// A MinIO-written SSE-C object keeps only the internal sealed-key slots. + #[tokio::test] + async fn object_encryption_resolver_reads_minio_shaped_ssec_metadata() { + let customer_key_bytes = [0x51u8; 32]; + let customer_key = BASE64_STANDARD.encode_to_string(customer_key_bytes); + let customer_key_md5 = md5_base64(customer_key_bytes); + + let material = sse_encryption(ssec_write(&customer_key, &customer_key_md5)) + .await + .expect("sse-c encryption") + .expect("sse-c material"); + let mut metadata = encryption_material_to_metadata(&material).expect("sse-c metadata should serialize"); + metadata.remove("x-amz-server-side-encryption"); + metadata.remove("x-amz-server-side-encryption-customer-algorithm"); + metadata.remove("x-amz-server-side-encryption-customer-key-md5"); + + let resolved = SseObjectEncryptionResolver + .resolve_read_material(ReadEncryptionRequest { + bucket: "bucket", + object: "object", + metadata: &metadata, + headers: &ssec_read_headers(&customer_key, &customer_key_md5), + }) + .await + .expect("minio-shaped SSE-C resolver") + .expect("minio-shaped SSE-C material"); + assert_eq!(resolved.mode, ReadEncryptionMode::Object); + assert_eq!(resolved.key_bytes, material.key_bytes); + } } } diff --git a/rustfs/src/storage/sse_test.rs b/rustfs/src/storage/sse_test.rs index 8ca6ff5db6..3d14f816a1 100644 --- a/rustfs/src/storage/sse_test.rs +++ b/rustfs/src/storage/sse_test.rs @@ -252,4 +252,237 @@ mod tests { println!("✅ Full cycle (generate -> encrypt DEK -> decrypt DEK -> decrypt data) test passed!"); } + + #[tokio::test] + async fn test_simple_sse_dek_provider_encrypt_decrypt() { + use std::io::Cursor; + use tokio::io::AsyncReadExt; + + // 1. Setup: Create SimpleSseDekProvider with test master key + let provider = TestSseDekProvider::new_with_key([42u8; 32]); + + // 2. Generate a data encryption key + let bucket = "test-bucket"; + let key = "test-key"; + let kms_key_id = "default"; // Key ID is ignored in simple provider + let context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string()); + + let (data_key, _encrypted_dek) = provider + .generate_sse_dek(&context, kms_key_id) + .await + .expect("Failed to generate DEK"); + + // 3. Prepare test data (plaintext) + let plaintext = b"Hello, World! This is a test message for encryption and decryption."; + println!("Original plaintext: {:?}", String::from_utf8_lossy(plaintext)); + println!("Plaintext length: {} bytes", plaintext.len()); + + // 4. Encrypt with EncryptReader. + let plaintext_reader = Cursor::new(plaintext.to_vec()); + let mut encrypt_reader = EncryptReader::new(plaintext_reader, data_key.plaintext_key, data_key.nonce); + + // Read encrypted data + let mut encrypted_data = Vec::new(); + encrypt_reader + .read_to_end(&mut encrypted_data) + .await + .expect("Failed to read encrypted data"); + + println!("Encrypted data length: {} bytes", encrypted_data.len()); + println!( + "First 16 bytes of encrypted data: {:02x?}", + &encrypted_data[..16.min(encrypted_data.len())] + ); + + // Verify encrypted data is different from plaintext + assert_ne!( + &encrypted_data[..plaintext.len()], + plaintext, + "Encrypted data should be different from plaintext" + ); + + // 5. Decrypt with DecryptReader. + let encrypted_reader = Cursor::new(encrypted_data); + let mut decrypt_reader = DecryptReader::new(encrypted_reader, data_key.plaintext_key, data_key.nonce); + + // Read decrypted data + let mut decrypted_data = Vec::new(); + decrypt_reader + .read_to_end(&mut decrypted_data) + .await + .expect("Failed to read decrypted data"); + + println!("Decrypted data: {:?}", String::from_utf8_lossy(&decrypted_data)); + println!("Decrypted length: {} bytes", decrypted_data.len()); + + // 6. Verify decrypted data matches original plaintext + assert_eq!(decrypted_data, plaintext, "Decrypted data should match original plaintext"); + + println!("✅ Encryption/Decryption test passed!"); + } + + #[tokio::test] + async fn test_simple_sse_dek_provider_encrypt_decrypt_large_data() { + use std::io::Cursor; + use tokio::io::AsyncReadExt; + + // 1. Setup: Create SimpleSseDekProvider with test master key + let provider = TestSseDekProvider::new_with_key([42u8; 32]); + + let bucket = "test-bucket"; + let key = "test-key-large"; + let kms_key_id = "default"; + let context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string()); + + let (data_key, _encrypted_dek) = provider + .generate_sse_dek(&context, kms_key_id) + .await + .expect("Failed to generate DEK"); + + // Create 1MB of test data + let plaintext_size = 1024 * 1024; // 1MB + let plaintext: Vec = (0..plaintext_size).map(|i| (i % 256) as u8).collect(); + println!("Testing with {} bytes of data", plaintext.len()); + + // Encrypt. + let plaintext_reader = Cursor::new(plaintext.clone()); + let mut encrypt_reader = EncryptReader::new(plaintext_reader, data_key.plaintext_key, data_key.nonce); + + let mut encrypted_data = Vec::new(); + encrypt_reader + .read_to_end(&mut encrypted_data) + .await + .expect("Failed to encrypt large data"); + + println!("Encrypted {} bytes to {} bytes", plaintext.len(), encrypted_data.len()); + + // Decrypt. + let encrypted_reader = Cursor::new(encrypted_data); + let mut decrypt_reader = DecryptReader::new(encrypted_reader, data_key.plaintext_key, data_key.nonce); + + let mut decrypted_data = Vec::new(); + decrypt_reader + .read_to_end(&mut decrypted_data) + .await + .expect("Failed to decrypt large data"); + + // Verify + assert_eq!(decrypted_data.len(), plaintext.len(), "Decrypted size should match original"); + assert_eq!(decrypted_data, plaintext, "Decrypted data should match original plaintext"); + + println!("✅ Large data encryption/decryption test passed!"); + } + + #[tokio::test] + async fn test_simple_sse_dek_provider_different_nonces() { + use std::io::Cursor; + use tokio::io::AsyncReadExt; + + // 1. Setup: Create SimpleSseDekProvider with test master key + let provider = TestSseDekProvider::new_with_key([42u8; 32]); + + let bucket = "test-bucket"; + let key = "test-key"; + let kms_key_id = "default"; + let context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string()); + + // Generate two different keys (with different nonces) + let (data_key1, _) = provider + .generate_sse_dek(&context, kms_key_id) + .await + .expect("Failed to generate DEK 1"); + + let (data_key2, _) = provider + .generate_sse_dek(&context, kms_key_id) + .await + .expect("Failed to generate DEK 2"); + + // Verify nonces are different + assert_ne!(data_key1.nonce, data_key2.nonce, "Different keys should have different nonces"); + + // Same plaintext + let plaintext = b"Same plaintext"; + + // Encrypt with first key. + let reader1 = Cursor::new(plaintext.to_vec()); + let mut encrypt_reader1 = EncryptReader::new(reader1, data_key1.plaintext_key, data_key1.nonce); + let mut encrypted1 = Vec::new(); + encrypt_reader1.read_to_end(&mut encrypted1).await.unwrap(); + + // Encrypt with second key. + let reader2 = Cursor::new(plaintext.to_vec()); + let mut encrypt_reader2 = EncryptReader::new(reader2, data_key2.plaintext_key, data_key2.nonce); + let mut encrypted2 = Vec::new(); + encrypt_reader2.read_to_end(&mut encrypted2).await.unwrap(); + + // Verify ciphertexts are different (due to different nonces/keys) + assert_ne!( + encrypted1, encrypted2, + "Same plaintext with different nonces should produce different ciphertext" + ); + + println!("✅ Different nonces produce different ciphertext - test passed!"); + } + + #[tokio::test] + async fn test_simple_sse_dek_provider_decrypt_with_encrypted_dek() { + use std::io::Cursor; + use tokio::io::AsyncReadExt; + + // 1. Setup: Create SimpleSseDekProvider with test master key + let provider = TestSseDekProvider::new_with_key([42u8; 32]); + + let bucket = "test-bucket"; + let key = "test-key"; + let kms_key_id = "default"; + let context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string()); + + // 1. Generate DEK and get encrypted DEK + let (data_key, encrypted_dek) = provider + .generate_sse_dek(&context, kms_key_id) + .await + .expect("Failed to generate DEK"); + + let original_plaintext_key = data_key.plaintext_key; + let original_nonce = data_key.nonce; + + // 2. Simulate storing encrypted_dek and nonce in metadata + // In real scenario, nonce would be stored separately in metadata + + // 3. Later, decrypt the DEK + let decrypted_plaintext_key = provider + .decrypt_sse_dek(&encrypted_dek, kms_key_id, &context) + .await + .expect("Failed to decrypt DEK"); + + // 4. Verify decrypted key matches original + assert_eq!( + decrypted_plaintext_key, original_plaintext_key, + "Decrypted DEK should match original plaintext key" + ); + + // 5. Use decrypted key to encrypt/decrypt data + let plaintext = b"Test data with decrypted DEK"; + + // Encrypt with original key. + let reader = Cursor::new(plaintext.to_vec()); + let mut encrypt_reader = EncryptReader::new(reader, original_plaintext_key, original_nonce); + let mut encrypted_data = Vec::new(); + encrypt_reader.read_to_end(&mut encrypted_data).await.unwrap(); + + // Decrypt with recovered key (simulating GET operation). + let reader = Cursor::new(encrypted_data); + let mut decrypt_reader = DecryptReader::new( + reader, + decrypted_plaintext_key, + original_nonce, // In real scenario, read from metadata + ); + let mut decrypted_data = Vec::new(); + decrypt_reader.read_to_end(&mut decrypted_data).await.unwrap(); + + // Verify + assert_eq!(decrypted_data, plaintext, "Data decrypted with recovered key should match original"); + + println!("✅ Full cycle (generate -> encrypt DEK -> decrypt DEK -> decrypt data) test passed!"); + } } diff --git a/rustfs/src/storage/storage_api.rs b/rustfs/src/storage/storage_api.rs index d19a8becdb..7775bc4a98 100644 --- a/rustfs/src/storage/storage_api.rs +++ b/rustfs/src/storage/storage_api.rs @@ -452,8 +452,8 @@ pub(crate) mod s3_api_consumer { pub(crate) mod sse_consumer { pub(crate) use super::super::sse::{ - EncryptionKeyKind, bucket_default_write_sse, build_ssec_read_headers, encryption_material_to_metadata, - extract_ssec_params_from_headers, extract_ssekms_context_from_headers, log_sse_kms_key_policy_mode, + 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, init_sse_startup, map_get_object_reader_error, mark_encrypted_multipart_metadata, multipart_completion_authorization, stored_ssec_metadata, }; pub(crate) use super::{ @@ -484,8 +484,7 @@ pub(crate) mod test_consumer { pub(crate) use super::super::access_owned::object_read::authorize_head_object; pub(crate) use super::super::legacy_s3_test_types; pub(crate) mod sse { - pub(crate) use super::super::super::sse::TestAuthorizationHooks; - pub(crate) use super::super::super::sse::tests::{RecordingKmsKeyAuthorizer, sse_kms_object_metadata}; + pub(crate) use super::super::super::sse::{RecordingKmsKeyAuthorizer, TestAuthorizationHooks, sse_kms_object_metadata}; } pub(crate) use super::super::{ apply_cors_headers, apply_default_lock_retention_metadata, check_preconditions, decode_tags_to_map, diff --git a/rustfs/src/storage_api.rs b/rustfs/src/storage_api.rs index 077be6a148..5cd35ab94f 100644 --- a/rustfs/src/storage_api.rs +++ b/rustfs/src/storage_api.rs @@ -453,7 +453,7 @@ pub(crate) mod startup { } pub(crate) mod sse { - pub(crate) use crate::storage::storage_api::sse_consumer::log_sse_kms_key_policy_mode; + pub(crate) use crate::storage::storage_api::sse_consumer::init_sse_startup; } pub(crate) mod notification { diff --git a/scripts/check_architecture_migration_rules.sh b/scripts/check_architecture_migration_rules.sh index f914eb724b..edf0ea25b1 100755 --- a/scripts/check_architecture_migration_rules.sh +++ b/scripts/check_architecture_migration_rules.sh @@ -5497,13 +5497,18 @@ require_source_contains \ # its internal dependency surface is pinned to exactly rustfs-signer so it cannot # quietly grow storage-side dependencies. Adding any other rustfs-* dependency to # any of these five crates needs its own adjudication, not a quiet Cargo.toml edit. +# sse sits between the S3 layer and the storage engine and reaches the running +# server only through its `SseHost` port, so its internal dependency surface is +# pinned as well: the KMS it calls, the policy and S3 vocabularies it speaks, and +# the two foundation crates. An edge to ecstore, iam, or the binary would let key +# resolution reach engine or identity state behind the port. # The pattern matches both TOML dependency spellings: `rustfs-x = ...` and the # dotted `rustfs-x.workspace = true` form (which previously escaped this guard). LEAF_CRATE_DEP_HITS_FILE="${TMP_DIR}/leaf_crate_dep_hits.txt" : >"$LEAF_CRATE_DEP_HITS_FILE" ( cd "$ROOT_DIR" - for leaf in config credentials crypto io-metrics madmin; do + for leaf in config credentials crypto io-metrics madmin sse; do manifest="crates/${leaf}/Cargo.toml" [[ -f "$manifest" ]] || continue leaf_dep_status=0 @@ -5518,6 +5523,9 @@ LEAF_CRATE_DEP_HITS_FILE="${TMP_DIR}/leaf_crate_dep_hits.txt" madmin) rg -v '^[^:]*:[0-9]+:rustfs-signer(\.[a-zA-Z_-]+)* *=' "${TMP_DIR}/leaf_dep_raw.txt" >>"$LEAF_CRATE_DEP_HITS_FILE" || true ;; + sse) + rg -v '^[^:]*:[0-9]+:rustfs-(config|kms|policy|s3-types|utils)(\.[a-zA-Z_-]+)* *=' "${TMP_DIR}/leaf_dep_raw.txt" >>"$LEAF_CRATE_DEP_HITS_FILE" || true + ;; *) cat "${TMP_DIR}/leaf_dep_raw.txt" >>"$LEAF_CRATE_DEP_HITS_FILE" ;; @@ -5526,7 +5534,7 @@ LEAF_CRATE_DEP_HITS_FILE="${TMP_DIR}/leaf_crate_dep_hits.txt" ) if [[ -s "$LEAF_CRATE_DEP_HITS_FILE" ]]; then - report_failure "leaf/pinned-dep crates: config/credentials/crypto take no internal rustfs-* dependency; io-metrics only rustfs-s3-ops (pure contract crate, backlog#1834); madmin only rustfs-signer (admin SDK SigV4 client, #6166); any new edge needs its own adjudication: $(paste -sd '; ' "$LEAF_CRATE_DEP_HITS_FILE")" + report_failure "leaf/pinned-dep crates: config/credentials/crypto take no internal rustfs-* dependency; io-metrics only rustfs-s3-ops (pure contract crate, backlog#1834); madmin only rustfs-signer (admin SDK SigV4 client, #6166); sse only rustfs-config/kms/policy/s3-types/utils (it reaches the server through SseHost); any new edge needs its own adjudication: $(paste -sd '; ' "$LEAF_CRATE_DEP_HITS_FILE")" fi # --- ecstore module-level lint blankets (backlog#1823 step 9) ---